xref: /openbmc/qemu/ui/vnc.c (revision 228aa992)
1 /*
2  * QEMU VNC display driver
3  *
4  * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5  * Copyright (C) 2006 Fabrice Bellard
6  * Copyright (C) 2009 Red Hat, Inc
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a copy
9  * of this software and associated documentation files (the "Software"), to deal
10  * in the Software without restriction, including without limitation the rights
11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12  * copies of the Software, and to permit persons to whom the Software is
13  * furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24  * THE SOFTWARE.
25  */
26 
27 #include "vnc.h"
28 #include "vnc-jobs.h"
29 #include "trace.h"
30 #include "sysemu/sysemu.h"
31 #include "qemu/sockets.h"
32 #include "qemu/timer.h"
33 #include "qemu/acl.h"
34 #include "qapi/qmp/types.h"
35 #include "qmp-commands.h"
36 #include "qemu/osdep.h"
37 #include "ui/input.h"
38 #include "qapi-event.h"
39 
40 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
41 #define VNC_REFRESH_INTERVAL_INC  50
42 #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
43 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
44 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
45 
46 #include "vnc_keysym.h"
47 #include "d3des.h"
48 
49 static VncDisplay *vnc_display; /* needed for info vnc */
50 
51 static int vnc_cursor_define(VncState *vs);
52 static void vnc_release_modifiers(VncState *vs);
53 
54 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
55 {
56 #ifdef _VNC_DEBUG
57     static const char *mn[] = {
58         [0]                           = "undefined",
59         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
60         [VNC_SHARE_MODE_SHARED]       = "shared",
61         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
62         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
63     };
64     fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
65             vs->csock, mn[vs->share_mode], mn[mode]);
66 #endif
67 
68     if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
69         vs->vd->num_exclusive--;
70     }
71     vs->share_mode = mode;
72     if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
73         vs->vd->num_exclusive++;
74     }
75 }
76 
77 static char *addr_to_string(const char *format,
78                             struct sockaddr_storage *sa,
79                             socklen_t salen) {
80     char *addr;
81     char host[NI_MAXHOST];
82     char serv[NI_MAXSERV];
83     int err;
84     size_t addrlen;
85 
86     if ((err = getnameinfo((struct sockaddr *)sa, salen,
87                            host, sizeof(host),
88                            serv, sizeof(serv),
89                            NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
90         VNC_DEBUG("Cannot resolve address %d: %s\n",
91                   err, gai_strerror(err));
92         return NULL;
93     }
94 
95     /* Enough for the existing format + the 2 vars we're
96      * substituting in. */
97     addrlen = strlen(format) + strlen(host) + strlen(serv);
98     addr = g_malloc(addrlen + 1);
99     snprintf(addr, addrlen, format, host, serv);
100     addr[addrlen] = '\0';
101 
102     return addr;
103 }
104 
105 
106 char *vnc_socket_local_addr(const char *format, int fd) {
107     struct sockaddr_storage sa;
108     socklen_t salen;
109 
110     salen = sizeof(sa);
111     if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
112         return NULL;
113 
114     return addr_to_string(format, &sa, salen);
115 }
116 
117 char *vnc_socket_remote_addr(const char *format, int fd) {
118     struct sockaddr_storage sa;
119     socklen_t salen;
120 
121     salen = sizeof(sa);
122     if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
123         return NULL;
124 
125     return addr_to_string(format, &sa, salen);
126 }
127 
128 static VncBasicInfo *vnc_basic_info_get(struct sockaddr_storage *sa,
129                                         socklen_t salen)
130 {
131     VncBasicInfo *info;
132     char host[NI_MAXHOST];
133     char serv[NI_MAXSERV];
134     int err;
135 
136     if ((err = getnameinfo((struct sockaddr *)sa, salen,
137                            host, sizeof(host),
138                            serv, sizeof(serv),
139                            NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
140         VNC_DEBUG("Cannot resolve address %d: %s\n",
141                   err, gai_strerror(err));
142         return NULL;
143     }
144 
145     info = g_malloc0(sizeof(VncBasicInfo));
146     info->host = g_strdup(host);
147     info->service = g_strdup(serv);
148     info->family = inet_netfamily(sa->ss_family);
149     return info;
150 }
151 
152 static VncBasicInfo *vnc_basic_info_get_from_server_addr(int fd)
153 {
154     struct sockaddr_storage sa;
155     socklen_t salen;
156 
157     salen = sizeof(sa);
158     if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
159         return NULL;
160     }
161 
162     return vnc_basic_info_get(&sa, salen);
163 }
164 
165 static VncBasicInfo *vnc_basic_info_get_from_remote_addr(int fd)
166 {
167     struct sockaddr_storage sa;
168     socklen_t salen;
169 
170     salen = sizeof(sa);
171     if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
172         return NULL;
173     }
174 
175     return vnc_basic_info_get(&sa, salen);
176 }
177 
178 static const char *vnc_auth_name(VncDisplay *vd) {
179     switch (vd->auth) {
180     case VNC_AUTH_INVALID:
181         return "invalid";
182     case VNC_AUTH_NONE:
183         return "none";
184     case VNC_AUTH_VNC:
185         return "vnc";
186     case VNC_AUTH_RA2:
187         return "ra2";
188     case VNC_AUTH_RA2NE:
189         return "ra2ne";
190     case VNC_AUTH_TIGHT:
191         return "tight";
192     case VNC_AUTH_ULTRA:
193         return "ultra";
194     case VNC_AUTH_TLS:
195         return "tls";
196     case VNC_AUTH_VENCRYPT:
197 #ifdef CONFIG_VNC_TLS
198         switch (vd->subauth) {
199         case VNC_AUTH_VENCRYPT_PLAIN:
200             return "vencrypt+plain";
201         case VNC_AUTH_VENCRYPT_TLSNONE:
202             return "vencrypt+tls+none";
203         case VNC_AUTH_VENCRYPT_TLSVNC:
204             return "vencrypt+tls+vnc";
205         case VNC_AUTH_VENCRYPT_TLSPLAIN:
206             return "vencrypt+tls+plain";
207         case VNC_AUTH_VENCRYPT_X509NONE:
208             return "vencrypt+x509+none";
209         case VNC_AUTH_VENCRYPT_X509VNC:
210             return "vencrypt+x509+vnc";
211         case VNC_AUTH_VENCRYPT_X509PLAIN:
212             return "vencrypt+x509+plain";
213         case VNC_AUTH_VENCRYPT_TLSSASL:
214             return "vencrypt+tls+sasl";
215         case VNC_AUTH_VENCRYPT_X509SASL:
216             return "vencrypt+x509+sasl";
217         default:
218             return "vencrypt";
219         }
220 #else
221         return "vencrypt";
222 #endif
223     case VNC_AUTH_SASL:
224         return "sasl";
225     }
226     return "unknown";
227 }
228 
229 static VncServerInfo *vnc_server_info_get(void)
230 {
231     VncServerInfo *info;
232     VncBasicInfo *bi = vnc_basic_info_get_from_server_addr(vnc_display->lsock);
233     if (!bi) {
234         return NULL;
235     }
236 
237     info = g_malloc(sizeof(*info));
238     info->base = bi;
239     info->has_auth = true;
240     info->auth = g_strdup(vnc_auth_name(vnc_display));
241     return info;
242 }
243 
244 static void vnc_client_cache_auth(VncState *client)
245 {
246     if (!client->info) {
247         return;
248     }
249 
250 #ifdef CONFIG_VNC_TLS
251     if (client->tls.session &&
252         client->tls.dname) {
253         client->info->has_x509_dname = true;
254         client->info->x509_dname = g_strdup(client->tls.dname);
255     }
256 #endif
257 #ifdef CONFIG_VNC_SASL
258     if (client->sasl.conn &&
259         client->sasl.username) {
260         client->info->has_sasl_username = true;
261         client->info->sasl_username = g_strdup(client->sasl.username);
262     }
263 #endif
264 }
265 
266 static void vnc_client_cache_addr(VncState *client)
267 {
268     VncBasicInfo *bi = vnc_basic_info_get_from_remote_addr(client->csock);
269 
270     if (bi) {
271         client->info = g_malloc0(sizeof(*client->info));
272         client->info->base = bi;
273     }
274 }
275 
276 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
277 {
278     VncServerInfo *si;
279 
280     if (!vs->info) {
281         return;
282     }
283     g_assert(vs->info->base);
284 
285     si = vnc_server_info_get();
286     if (!si) {
287         return;
288     }
289 
290     switch (event) {
291     case QAPI_EVENT_VNC_CONNECTED:
292         qapi_event_send_vnc_connected(si, vs->info->base, &error_abort);
293         break;
294     case QAPI_EVENT_VNC_INITIALIZED:
295         qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
296         break;
297     case QAPI_EVENT_VNC_DISCONNECTED:
298         qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
299         break;
300     default:
301         break;
302     }
303 
304     qapi_free_VncServerInfo(si);
305 }
306 
307 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
308 {
309     struct sockaddr_storage sa;
310     socklen_t salen = sizeof(sa);
311     char host[NI_MAXHOST];
312     char serv[NI_MAXSERV];
313     VncClientInfo *info;
314 
315     if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
316         return NULL;
317     }
318 
319     if (getnameinfo((struct sockaddr *)&sa, salen,
320                     host, sizeof(host),
321                     serv, sizeof(serv),
322                     NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
323         return NULL;
324     }
325 
326     info = g_malloc0(sizeof(*info));
327     info->base = g_malloc0(sizeof(*info->base));
328     info->base->host = g_strdup(host);
329     info->base->service = g_strdup(serv);
330     info->base->family = inet_netfamily(sa.ss_family);
331 
332 #ifdef CONFIG_VNC_TLS
333     if (client->tls.session && client->tls.dname) {
334         info->has_x509_dname = true;
335         info->x509_dname = g_strdup(client->tls.dname);
336     }
337 #endif
338 #ifdef CONFIG_VNC_SASL
339     if (client->sasl.conn && client->sasl.username) {
340         info->has_sasl_username = true;
341         info->sasl_username = g_strdup(client->sasl.username);
342     }
343 #endif
344 
345     return info;
346 }
347 
348 VncInfo *qmp_query_vnc(Error **errp)
349 {
350     VncInfo *info = g_malloc0(sizeof(*info));
351 
352     if (vnc_display == NULL || vnc_display->display == NULL) {
353         info->enabled = false;
354     } else {
355         VncClientInfoList *cur_item = NULL;
356         struct sockaddr_storage sa;
357         socklen_t salen = sizeof(sa);
358         char host[NI_MAXHOST];
359         char serv[NI_MAXSERV];
360         VncState *client;
361 
362         info->enabled = true;
363 
364         /* for compatibility with the original command */
365         info->has_clients = true;
366 
367         QTAILQ_FOREACH(client, &vnc_display->clients, next) {
368             VncClientInfoList *cinfo = g_malloc0(sizeof(*info));
369             cinfo->value = qmp_query_vnc_client(client);
370 
371             /* XXX: waiting for the qapi to support GSList */
372             if (!cur_item) {
373                 info->clients = cur_item = cinfo;
374             } else {
375                 cur_item->next = cinfo;
376                 cur_item = cinfo;
377             }
378         }
379 
380         if (vnc_display->lsock == -1) {
381             return info;
382         }
383 
384         if (getsockname(vnc_display->lsock, (struct sockaddr *)&sa,
385                         &salen) == -1) {
386             error_set(errp, QERR_UNDEFINED_ERROR);
387             goto out_error;
388         }
389 
390         if (getnameinfo((struct sockaddr *)&sa, salen,
391                         host, sizeof(host),
392                         serv, sizeof(serv),
393                         NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
394             error_set(errp, QERR_UNDEFINED_ERROR);
395             goto out_error;
396         }
397 
398         info->has_host = true;
399         info->host = g_strdup(host);
400 
401         info->has_service = true;
402         info->service = g_strdup(serv);
403 
404         info->has_family = true;
405         info->family = inet_netfamily(sa.ss_family);
406 
407         info->has_auth = true;
408         info->auth = g_strdup(vnc_auth_name(vnc_display));
409     }
410 
411     return info;
412 
413 out_error:
414     qapi_free_VncInfo(info);
415     return NULL;
416 }
417 
418 /* TODO
419    1) Get the queue working for IO.
420    2) there is some weirdness when using the -S option (the screen is grey
421       and not totally invalidated
422    3) resolutions > 1024
423 */
424 
425 static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
426 static void vnc_disconnect_start(VncState *vs);
427 
428 static void vnc_colordepth(VncState *vs);
429 static void framebuffer_update_request(VncState *vs, int incremental,
430                                        int x_position, int y_position,
431                                        int w, int h);
432 static void vnc_refresh(DisplayChangeListener *dcl);
433 static int vnc_refresh_server_surface(VncDisplay *vd);
434 
435 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
436                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
437                                int width, int height,
438                                int x, int y, int w, int h) {
439     /* this is needed this to ensure we updated all affected
440      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
441     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
442     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
443 
444     x = MIN(x, width);
445     y = MIN(y, height);
446     w = MIN(x + w, width) - x;
447     h = MIN(y + h, height);
448 
449     for (; y < h; y++) {
450         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
451                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
452     }
453 }
454 
455 static void vnc_dpy_update(DisplayChangeListener *dcl,
456                            int x, int y, int w, int h)
457 {
458     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
459     struct VncSurface *s = &vd->guest;
460     int width = pixman_image_get_width(vd->server);
461     int height = pixman_image_get_height(vd->server);
462 
463     vnc_set_area_dirty(s->dirty, width, height, x, y, w, h);
464 }
465 
466 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
467                             int32_t encoding)
468 {
469     vnc_write_u16(vs, x);
470     vnc_write_u16(vs, y);
471     vnc_write_u16(vs, w);
472     vnc_write_u16(vs, h);
473 
474     vnc_write_s32(vs, encoding);
475 }
476 
477 void buffer_reserve(Buffer *buffer, size_t len)
478 {
479     if ((buffer->capacity - buffer->offset) < len) {
480         buffer->capacity += (len + 1024);
481         buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
482         if (buffer->buffer == NULL) {
483             fprintf(stderr, "vnc: out of memory\n");
484             exit(1);
485         }
486     }
487 }
488 
489 static int buffer_empty(Buffer *buffer)
490 {
491     return buffer->offset == 0;
492 }
493 
494 uint8_t *buffer_end(Buffer *buffer)
495 {
496     return buffer->buffer + buffer->offset;
497 }
498 
499 void buffer_reset(Buffer *buffer)
500 {
501         buffer->offset = 0;
502 }
503 
504 void buffer_free(Buffer *buffer)
505 {
506     g_free(buffer->buffer);
507     buffer->offset = 0;
508     buffer->capacity = 0;
509     buffer->buffer = NULL;
510 }
511 
512 void buffer_append(Buffer *buffer, const void *data, size_t len)
513 {
514     memcpy(buffer->buffer + buffer->offset, data, len);
515     buffer->offset += len;
516 }
517 
518 void buffer_advance(Buffer *buf, size_t len)
519 {
520     memmove(buf->buffer, buf->buffer + len,
521             (buf->offset - len));
522     buf->offset -= len;
523 }
524 
525 static void vnc_desktop_resize(VncState *vs)
526 {
527     if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
528         return;
529     }
530     if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
531         vs->client_height == pixman_image_get_height(vs->vd->server)) {
532         return;
533     }
534     vs->client_width = pixman_image_get_width(vs->vd->server);
535     vs->client_height = pixman_image_get_height(vs->vd->server);
536     vnc_lock_output(vs);
537     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
538     vnc_write_u8(vs, 0);
539     vnc_write_u16(vs, 1); /* number of rects */
540     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
541                            VNC_ENCODING_DESKTOPRESIZE);
542     vnc_unlock_output(vs);
543     vnc_flush(vs);
544 }
545 
546 static void vnc_abort_display_jobs(VncDisplay *vd)
547 {
548     VncState *vs;
549 
550     QTAILQ_FOREACH(vs, &vd->clients, next) {
551         vnc_lock_output(vs);
552         vs->abort = true;
553         vnc_unlock_output(vs);
554     }
555     QTAILQ_FOREACH(vs, &vd->clients, next) {
556         vnc_jobs_join(vs);
557     }
558     QTAILQ_FOREACH(vs, &vd->clients, next) {
559         vnc_lock_output(vs);
560         vs->abort = false;
561         vnc_unlock_output(vs);
562     }
563 }
564 
565 int vnc_server_fb_stride(VncDisplay *vd)
566 {
567     return pixman_image_get_stride(vd->server);
568 }
569 
570 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
571 {
572     uint8_t *ptr;
573 
574     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
575     ptr += y * vnc_server_fb_stride(vd);
576     ptr += x * VNC_SERVER_FB_BYTES;
577     return ptr;
578 }
579 
580 static void vnc_dpy_switch(DisplayChangeListener *dcl,
581                            DisplaySurface *surface)
582 {
583     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
584     VncState *vs;
585     int width, height;
586 
587     vnc_abort_display_jobs(vd);
588 
589     /* server surface */
590     qemu_pixman_image_unref(vd->server);
591     vd->ds = surface;
592     width = MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
593                                         VNC_DIRTY_PIXELS_PER_BIT));
594     height = MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
595     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
596                                           width, height, NULL, 0);
597 
598     /* guest surface */
599 #if 0 /* FIXME */
600     if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
601         console_color_init(ds);
602 #endif
603     qemu_pixman_image_unref(vd->guest.fb);
604     vd->guest.fb = pixman_image_ref(surface->image);
605     vd->guest.format = surface->format;
606     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
607     vnc_set_area_dirty(vd->guest.dirty, width, height, 0, 0,
608                        width, height);
609 
610     QTAILQ_FOREACH(vs, &vd->clients, next) {
611         vnc_colordepth(vs);
612         vnc_desktop_resize(vs);
613         if (vs->vd->cursor) {
614             vnc_cursor_define(vs);
615         }
616         memset(vs->dirty, 0x00, sizeof(vs->dirty));
617         vnc_set_area_dirty(vs->dirty, width, height, 0, 0,
618                            width, height);
619     }
620 }
621 
622 /* fastest code */
623 static void vnc_write_pixels_copy(VncState *vs,
624                                   void *pixels, int size)
625 {
626     vnc_write(vs, pixels, size);
627 }
628 
629 /* slowest but generic code. */
630 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
631 {
632     uint8_t r, g, b;
633 
634 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
635     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
636     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
637     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
638 #else
639 # error need some bits here if you change VNC_SERVER_FB_FORMAT
640 #endif
641     v = (r << vs->client_pf.rshift) |
642         (g << vs->client_pf.gshift) |
643         (b << vs->client_pf.bshift);
644     switch (vs->client_pf.bytes_per_pixel) {
645     case 1:
646         buf[0] = v;
647         break;
648     case 2:
649         if (vs->client_be) {
650             buf[0] = v >> 8;
651             buf[1] = v;
652         } else {
653             buf[1] = v >> 8;
654             buf[0] = v;
655         }
656         break;
657     default:
658     case 4:
659         if (vs->client_be) {
660             buf[0] = v >> 24;
661             buf[1] = v >> 16;
662             buf[2] = v >> 8;
663             buf[3] = v;
664         } else {
665             buf[3] = v >> 24;
666             buf[2] = v >> 16;
667             buf[1] = v >> 8;
668             buf[0] = v;
669         }
670         break;
671     }
672 }
673 
674 static void vnc_write_pixels_generic(VncState *vs,
675                                      void *pixels1, int size)
676 {
677     uint8_t buf[4];
678 
679     if (VNC_SERVER_FB_BYTES == 4) {
680         uint32_t *pixels = pixels1;
681         int n, i;
682         n = size >> 2;
683         for (i = 0; i < n; i++) {
684             vnc_convert_pixel(vs, buf, pixels[i]);
685             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
686         }
687     }
688 }
689 
690 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
691 {
692     int i;
693     uint8_t *row;
694     VncDisplay *vd = vs->vd;
695 
696     row = vnc_server_fb_ptr(vd, x, y);
697     for (i = 0; i < h; i++) {
698         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
699         row += vnc_server_fb_stride(vd);
700     }
701     return 1;
702 }
703 
704 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
705 {
706     int n = 0;
707 
708     switch(vs->vnc_encoding) {
709         case VNC_ENCODING_ZLIB:
710             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
711             break;
712         case VNC_ENCODING_HEXTILE:
713             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
714             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
715             break;
716         case VNC_ENCODING_TIGHT:
717             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
718             break;
719         case VNC_ENCODING_TIGHT_PNG:
720             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
721             break;
722         case VNC_ENCODING_ZRLE:
723             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
724             break;
725         case VNC_ENCODING_ZYWRLE:
726             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
727             break;
728         default:
729             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
730             n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
731             break;
732     }
733     return n;
734 }
735 
736 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
737 {
738     /* send bitblit op to the vnc client */
739     vnc_lock_output(vs);
740     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
741     vnc_write_u8(vs, 0);
742     vnc_write_u16(vs, 1); /* number of rects */
743     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
744     vnc_write_u16(vs, src_x);
745     vnc_write_u16(vs, src_y);
746     vnc_unlock_output(vs);
747     vnc_flush(vs);
748 }
749 
750 static void vnc_dpy_copy(DisplayChangeListener *dcl,
751                          int src_x, int src_y,
752                          int dst_x, int dst_y, int w, int h)
753 {
754     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
755     VncState *vs, *vn;
756     uint8_t *src_row;
757     uint8_t *dst_row;
758     int i, x, y, pitch, inc, w_lim, s;
759     int cmp_bytes;
760 
761     vnc_refresh_server_surface(vd);
762     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
763         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
764             vs->force_update = 1;
765             vnc_update_client(vs, 1, true);
766             /* vs might be free()ed here */
767         }
768     }
769 
770     /* do bitblit op on the local surface too */
771     pitch = vnc_server_fb_stride(vd);
772     src_row = vnc_server_fb_ptr(vd, src_x, src_y);
773     dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
774     y = dst_y;
775     inc = 1;
776     if (dst_y > src_y) {
777         /* copy backwards */
778         src_row += pitch * (h-1);
779         dst_row += pitch * (h-1);
780         pitch = -pitch;
781         y = dst_y + h - 1;
782         inc = -1;
783     }
784     w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
785     if (w_lim < 0) {
786         w_lim = w;
787     } else {
788         w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
789     }
790     for (i = 0; i < h; i++) {
791         for (x = 0; x <= w_lim;
792                 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
793             if (x == w_lim) {
794                 if ((s = w - w_lim) == 0)
795                     break;
796             } else if (!x) {
797                 s = (VNC_DIRTY_PIXELS_PER_BIT -
798                     (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
799                 s = MIN(s, w_lim);
800             } else {
801                 s = VNC_DIRTY_PIXELS_PER_BIT;
802             }
803             cmp_bytes = s * VNC_SERVER_FB_BYTES;
804             if (memcmp(src_row, dst_row, cmp_bytes) == 0)
805                 continue;
806             memmove(dst_row, src_row, cmp_bytes);
807             QTAILQ_FOREACH(vs, &vd->clients, next) {
808                 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
809                     set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
810                             vs->dirty[y]);
811                 }
812             }
813         }
814         src_row += pitch - w * VNC_SERVER_FB_BYTES;
815         dst_row += pitch - w * VNC_SERVER_FB_BYTES;
816         y += inc;
817     }
818 
819     QTAILQ_FOREACH(vs, &vd->clients, next) {
820         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
821             vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
822         }
823     }
824 }
825 
826 static void vnc_mouse_set(DisplayChangeListener *dcl,
827                           int x, int y, int visible)
828 {
829     /* can we ask the client(s) to move the pointer ??? */
830 }
831 
832 static int vnc_cursor_define(VncState *vs)
833 {
834     QEMUCursor *c = vs->vd->cursor;
835     int isize;
836 
837     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
838         vnc_lock_output(vs);
839         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
840         vnc_write_u8(vs,  0);  /*  padding     */
841         vnc_write_u16(vs, 1);  /*  # of rects  */
842         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
843                                VNC_ENCODING_RICH_CURSOR);
844         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
845         vnc_write_pixels_generic(vs, c->data, isize);
846         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
847         vnc_unlock_output(vs);
848         return 0;
849     }
850     return -1;
851 }
852 
853 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
854                                   QEMUCursor *c)
855 {
856     VncDisplay *vd = vnc_display;
857     VncState *vs;
858 
859     cursor_put(vd->cursor);
860     g_free(vd->cursor_mask);
861 
862     vd->cursor = c;
863     cursor_get(vd->cursor);
864     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
865     vd->cursor_mask = g_malloc0(vd->cursor_msize);
866     cursor_get_mono_mask(c, 0, vd->cursor_mask);
867 
868     QTAILQ_FOREACH(vs, &vd->clients, next) {
869         vnc_cursor_define(vs);
870     }
871 }
872 
873 static int find_and_clear_dirty_height(struct VncState *vs,
874                                        int y, int last_x, int x, int height)
875 {
876     int h;
877 
878     for (h = 1; h < (height - y); h++) {
879         if (!test_bit(last_x, vs->dirty[y + h])) {
880             break;
881         }
882         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
883     }
884 
885     return h;
886 }
887 
888 static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
889 {
890     vs->has_dirty += has_dirty;
891     if (vs->need_update && vs->csock != -1) {
892         VncDisplay *vd = vs->vd;
893         VncJob *job;
894         int y;
895         int height, width;
896         int n = 0;
897 
898         if (vs->output.offset && !vs->audio_cap && !vs->force_update)
899             /* kernel send buffers are full -> drop frames to throttle */
900             return 0;
901 
902         if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)
903             return 0;
904 
905         /*
906          * Send screen updates to the vnc client using the server
907          * surface and server dirty map.  guest surface updates
908          * happening in parallel don't disturb us, the next pass will
909          * send them to the client.
910          */
911         job = vnc_job_new(vs);
912 
913         height = pixman_image_get_height(vd->server);
914         width = pixman_image_get_width(vd->server);
915 
916         y = 0;
917         for (;;) {
918             int x, h;
919             unsigned long x2;
920             unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
921                                                  height * VNC_DIRTY_BPL(vs),
922                                                  y * VNC_DIRTY_BPL(vs));
923             if (offset == height * VNC_DIRTY_BPL(vs)) {
924                 /* no more dirty bits */
925                 break;
926             }
927             y = offset / VNC_DIRTY_BPL(vs);
928             x = offset % VNC_DIRTY_BPL(vs);
929             x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
930                                     VNC_DIRTY_BPL(vs), x);
931             bitmap_clear(vs->dirty[y], x, x2 - x);
932             h = find_and_clear_dirty_height(vs, y, x, x2, height);
933             x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
934             if (x2 > x) {
935                 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
936                                       (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
937             }
938         }
939 
940         vnc_job_push(job);
941         if (sync) {
942             vnc_jobs_join(vs);
943         }
944         vs->force_update = 0;
945         vs->has_dirty = 0;
946         return n;
947     }
948 
949     if (vs->csock == -1) {
950         vnc_disconnect_finish(vs);
951     } else if (sync) {
952         vnc_jobs_join(vs);
953     }
954 
955     return 0;
956 }
957 
958 /* audio */
959 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
960 {
961     VncState *vs = opaque;
962 
963     switch (cmd) {
964     case AUD_CNOTIFY_DISABLE:
965         vnc_lock_output(vs);
966         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
967         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
968         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
969         vnc_unlock_output(vs);
970         vnc_flush(vs);
971         break;
972 
973     case AUD_CNOTIFY_ENABLE:
974         vnc_lock_output(vs);
975         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
976         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
977         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
978         vnc_unlock_output(vs);
979         vnc_flush(vs);
980         break;
981     }
982 }
983 
984 static void audio_capture_destroy(void *opaque)
985 {
986 }
987 
988 static void audio_capture(void *opaque, void *buf, int size)
989 {
990     VncState *vs = opaque;
991 
992     vnc_lock_output(vs);
993     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
994     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
995     vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
996     vnc_write_u32(vs, size);
997     vnc_write(vs, buf, size);
998     vnc_unlock_output(vs);
999     vnc_flush(vs);
1000 }
1001 
1002 static void audio_add(VncState *vs)
1003 {
1004     struct audio_capture_ops ops;
1005 
1006     if (vs->audio_cap) {
1007         error_report("audio already running");
1008         return;
1009     }
1010 
1011     ops.notify = audio_capture_notify;
1012     ops.destroy = audio_capture_destroy;
1013     ops.capture = audio_capture;
1014 
1015     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1016     if (!vs->audio_cap) {
1017         error_report("Failed to add audio capture");
1018     }
1019 }
1020 
1021 static void audio_del(VncState *vs)
1022 {
1023     if (vs->audio_cap) {
1024         AUD_del_capture(vs->audio_cap, vs);
1025         vs->audio_cap = NULL;
1026     }
1027 }
1028 
1029 static void vnc_disconnect_start(VncState *vs)
1030 {
1031     if (vs->csock == -1)
1032         return;
1033     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1034     qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1035     closesocket(vs->csock);
1036     vs->csock = -1;
1037 }
1038 
1039 void vnc_disconnect_finish(VncState *vs)
1040 {
1041     int i;
1042 
1043     vnc_jobs_join(vs); /* Wait encoding jobs */
1044 
1045     vnc_lock_output(vs);
1046     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1047 
1048     buffer_free(&vs->input);
1049     buffer_free(&vs->output);
1050 #ifdef CONFIG_VNC_WS
1051     buffer_free(&vs->ws_input);
1052     buffer_free(&vs->ws_output);
1053 #endif /* CONFIG_VNC_WS */
1054 
1055     qapi_free_VncClientInfo(vs->info);
1056 
1057     vnc_zlib_clear(vs);
1058     vnc_tight_clear(vs);
1059     vnc_zrle_clear(vs);
1060 
1061 #ifdef CONFIG_VNC_TLS
1062     vnc_tls_client_cleanup(vs);
1063 #endif /* CONFIG_VNC_TLS */
1064 #ifdef CONFIG_VNC_SASL
1065     vnc_sasl_client_cleanup(vs);
1066 #endif /* CONFIG_VNC_SASL */
1067     audio_del(vs);
1068     vnc_release_modifiers(vs);
1069 
1070     if (vs->initialized) {
1071         QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1072         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1073     }
1074 
1075     if (vs->vd->lock_key_sync)
1076         qemu_remove_led_event_handler(vs->led);
1077     vnc_unlock_output(vs);
1078 
1079     qemu_mutex_destroy(&vs->output_mutex);
1080     if (vs->bh != NULL) {
1081         qemu_bh_delete(vs->bh);
1082     }
1083     buffer_free(&vs->jobs_buffer);
1084 
1085     for (i = 0; i < VNC_STAT_ROWS; ++i) {
1086         g_free(vs->lossy_rect[i]);
1087     }
1088     g_free(vs->lossy_rect);
1089     g_free(vs);
1090 }
1091 
1092 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1093 {
1094     if (ret == 0 || ret == -1) {
1095         if (ret == -1) {
1096             switch (last_errno) {
1097                 case EINTR:
1098                 case EAGAIN:
1099 #ifdef _WIN32
1100                 case WSAEWOULDBLOCK:
1101 #endif
1102                     return 0;
1103                 default:
1104                     break;
1105             }
1106         }
1107 
1108         VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1109                   ret, ret < 0 ? last_errno : 0);
1110         vnc_disconnect_start(vs);
1111 
1112         return 0;
1113     }
1114     return ret;
1115 }
1116 
1117 
1118 void vnc_client_error(VncState *vs)
1119 {
1120     VNC_DEBUG("Closing down client sock: protocol error\n");
1121     vnc_disconnect_start(vs);
1122 }
1123 
1124 #ifdef CONFIG_VNC_TLS
1125 static long vnc_client_write_tls(gnutls_session_t *session,
1126                                  const uint8_t *data,
1127                                  size_t datalen)
1128 {
1129     long ret = gnutls_write(*session, data, datalen);
1130     if (ret < 0) {
1131         if (ret == GNUTLS_E_AGAIN) {
1132             errno = EAGAIN;
1133         } else {
1134             errno = EIO;
1135         }
1136         ret = -1;
1137     }
1138     return ret;
1139 }
1140 #endif /* CONFIG_VNC_TLS */
1141 
1142 /*
1143  * Called to write a chunk of data to the client socket. The data may
1144  * be the raw data, or may have already been encoded by SASL.
1145  * The data will be written either straight onto the socket, or
1146  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1147  *
1148  * NB, it is theoretically possible to have 2 layers of encryption,
1149  * both SASL, and this TLS layer. It is highly unlikely in practice
1150  * though, since SASL encryption will typically be a no-op if TLS
1151  * is active
1152  *
1153  * Returns the number of bytes written, which may be less than
1154  * the requested 'datalen' if the socket would block. Returns
1155  * -1 on error, and disconnects the client socket.
1156  */
1157 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1158 {
1159     long ret;
1160 #ifdef CONFIG_VNC_TLS
1161     if (vs->tls.session) {
1162         ret = vnc_client_write_tls(&vs->tls.session, data, datalen);
1163     } else {
1164 #ifdef CONFIG_VNC_WS
1165         if (vs->ws_tls.session) {
1166             ret = vnc_client_write_tls(&vs->ws_tls.session, data, datalen);
1167         } else
1168 #endif /* CONFIG_VNC_WS */
1169 #endif /* CONFIG_VNC_TLS */
1170         {
1171             ret = send(vs->csock, (const void *)data, datalen, 0);
1172         }
1173 #ifdef CONFIG_VNC_TLS
1174     }
1175 #endif /* CONFIG_VNC_TLS */
1176     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1177     return vnc_client_io_error(vs, ret, socket_error());
1178 }
1179 
1180 
1181 /*
1182  * Called to write buffered data to the client socket, when not
1183  * using any SASL SSF encryption layers. Will write as much data
1184  * as possible without blocking. If all buffered data is written,
1185  * will switch the FD poll() handler back to read monitoring.
1186  *
1187  * Returns the number of bytes written, which may be less than
1188  * the buffered output data if the socket would block. Returns
1189  * -1 on error, and disconnects the client socket.
1190  */
1191 static long vnc_client_write_plain(VncState *vs)
1192 {
1193     long ret;
1194 
1195 #ifdef CONFIG_VNC_SASL
1196     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1197               vs->output.buffer, vs->output.capacity, vs->output.offset,
1198               vs->sasl.waitWriteSSF);
1199 
1200     if (vs->sasl.conn &&
1201         vs->sasl.runSSF &&
1202         vs->sasl.waitWriteSSF) {
1203         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1204         if (ret)
1205             vs->sasl.waitWriteSSF -= ret;
1206     } else
1207 #endif /* CONFIG_VNC_SASL */
1208         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1209     if (!ret)
1210         return 0;
1211 
1212     buffer_advance(&vs->output, ret);
1213 
1214     if (vs->output.offset == 0) {
1215         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1216     }
1217 
1218     return ret;
1219 }
1220 
1221 
1222 /*
1223  * First function called whenever there is data to be written to
1224  * the client socket. Will delegate actual work according to whether
1225  * SASL SSF layers are enabled (thus requiring encryption calls)
1226  */
1227 static void vnc_client_write_locked(void *opaque)
1228 {
1229     VncState *vs = opaque;
1230 
1231 #ifdef CONFIG_VNC_SASL
1232     if (vs->sasl.conn &&
1233         vs->sasl.runSSF &&
1234         !vs->sasl.waitWriteSSF) {
1235         vnc_client_write_sasl(vs);
1236     } else
1237 #endif /* CONFIG_VNC_SASL */
1238     {
1239 #ifdef CONFIG_VNC_WS
1240         if (vs->encode_ws) {
1241             vnc_client_write_ws(vs);
1242         } else
1243 #endif /* CONFIG_VNC_WS */
1244         {
1245             vnc_client_write_plain(vs);
1246         }
1247     }
1248 }
1249 
1250 void vnc_client_write(void *opaque)
1251 {
1252     VncState *vs = opaque;
1253 
1254     vnc_lock_output(vs);
1255     if (vs->output.offset
1256 #ifdef CONFIG_VNC_WS
1257             || vs->ws_output.offset
1258 #endif
1259             ) {
1260         vnc_client_write_locked(opaque);
1261     } else if (vs->csock != -1) {
1262         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1263     }
1264     vnc_unlock_output(vs);
1265 }
1266 
1267 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1268 {
1269     vs->read_handler = func;
1270     vs->read_handler_expect = expecting;
1271 }
1272 
1273 #ifdef CONFIG_VNC_TLS
1274 static long vnc_client_read_tls(gnutls_session_t *session, uint8_t *data,
1275                                 size_t datalen)
1276 {
1277     long ret = gnutls_read(*session, data, datalen);
1278     if (ret < 0) {
1279         if (ret == GNUTLS_E_AGAIN) {
1280             errno = EAGAIN;
1281         } else {
1282             errno = EIO;
1283         }
1284         ret = -1;
1285     }
1286     return ret;
1287 }
1288 #endif /* CONFIG_VNC_TLS */
1289 
1290 /*
1291  * Called to read a chunk of data from the client socket. The data may
1292  * be the raw data, or may need to be further decoded by SASL.
1293  * The data will be read either straight from to the socket, or
1294  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1295  *
1296  * NB, it is theoretically possible to have 2 layers of encryption,
1297  * both SASL, and this TLS layer. It is highly unlikely in practice
1298  * though, since SASL encryption will typically be a no-op if TLS
1299  * is active
1300  *
1301  * Returns the number of bytes read, which may be less than
1302  * the requested 'datalen' if the socket would block. Returns
1303  * -1 on error, and disconnects the client socket.
1304  */
1305 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1306 {
1307     long ret;
1308 #ifdef CONFIG_VNC_TLS
1309     if (vs->tls.session) {
1310         ret = vnc_client_read_tls(&vs->tls.session, data, datalen);
1311     } else {
1312 #ifdef CONFIG_VNC_WS
1313         if (vs->ws_tls.session) {
1314             ret = vnc_client_read_tls(&vs->ws_tls.session, data, datalen);
1315         } else
1316 #endif /* CONFIG_VNC_WS */
1317 #endif /* CONFIG_VNC_TLS */
1318         {
1319             ret = qemu_recv(vs->csock, data, datalen, 0);
1320         }
1321 #ifdef CONFIG_VNC_TLS
1322     }
1323 #endif /* CONFIG_VNC_TLS */
1324     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1325     return vnc_client_io_error(vs, ret, socket_error());
1326 }
1327 
1328 
1329 /*
1330  * Called to read data from the client socket to the input buffer,
1331  * when not using any SASL SSF encryption layers. Will read as much
1332  * data as possible without blocking.
1333  *
1334  * Returns the number of bytes read. Returns -1 on error, and
1335  * disconnects the client socket.
1336  */
1337 static long vnc_client_read_plain(VncState *vs)
1338 {
1339     int ret;
1340     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1341               vs->input.buffer, vs->input.capacity, vs->input.offset);
1342     buffer_reserve(&vs->input, 4096);
1343     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1344     if (!ret)
1345         return 0;
1346     vs->input.offset += ret;
1347     return ret;
1348 }
1349 
1350 static void vnc_jobs_bh(void *opaque)
1351 {
1352     VncState *vs = opaque;
1353 
1354     vnc_jobs_consume_buffer(vs);
1355 }
1356 
1357 /*
1358  * First function called whenever there is more data to be read from
1359  * the client socket. Will delegate actual work according to whether
1360  * SASL SSF layers are enabled (thus requiring decryption calls)
1361  */
1362 void vnc_client_read(void *opaque)
1363 {
1364     VncState *vs = opaque;
1365     long ret;
1366 
1367 #ifdef CONFIG_VNC_SASL
1368     if (vs->sasl.conn && vs->sasl.runSSF)
1369         ret = vnc_client_read_sasl(vs);
1370     else
1371 #endif /* CONFIG_VNC_SASL */
1372 #ifdef CONFIG_VNC_WS
1373         if (vs->encode_ws) {
1374             ret = vnc_client_read_ws(vs);
1375             if (ret == -1) {
1376                 vnc_disconnect_start(vs);
1377                 return;
1378             } else if (ret == -2) {
1379                 vnc_client_error(vs);
1380                 return;
1381             }
1382         } else
1383 #endif /* CONFIG_VNC_WS */
1384         {
1385         ret = vnc_client_read_plain(vs);
1386         }
1387     if (!ret) {
1388         if (vs->csock == -1)
1389             vnc_disconnect_finish(vs);
1390         return;
1391     }
1392 
1393     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1394         size_t len = vs->read_handler_expect;
1395         int ret;
1396 
1397         ret = vs->read_handler(vs, vs->input.buffer, len);
1398         if (vs->csock == -1) {
1399             vnc_disconnect_finish(vs);
1400             return;
1401         }
1402 
1403         if (!ret) {
1404             buffer_advance(&vs->input, len);
1405         } else {
1406             vs->read_handler_expect = ret;
1407         }
1408     }
1409 }
1410 
1411 void vnc_write(VncState *vs, const void *data, size_t len)
1412 {
1413     buffer_reserve(&vs->output, len);
1414 
1415     if (vs->csock != -1 && buffer_empty(&vs->output)) {
1416         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1417     }
1418 
1419     buffer_append(&vs->output, data, len);
1420 }
1421 
1422 void vnc_write_s32(VncState *vs, int32_t value)
1423 {
1424     vnc_write_u32(vs, *(uint32_t *)&value);
1425 }
1426 
1427 void vnc_write_u32(VncState *vs, uint32_t value)
1428 {
1429     uint8_t buf[4];
1430 
1431     buf[0] = (value >> 24) & 0xFF;
1432     buf[1] = (value >> 16) & 0xFF;
1433     buf[2] = (value >>  8) & 0xFF;
1434     buf[3] = value & 0xFF;
1435 
1436     vnc_write(vs, buf, 4);
1437 }
1438 
1439 void vnc_write_u16(VncState *vs, uint16_t value)
1440 {
1441     uint8_t buf[2];
1442 
1443     buf[0] = (value >> 8) & 0xFF;
1444     buf[1] = value & 0xFF;
1445 
1446     vnc_write(vs, buf, 2);
1447 }
1448 
1449 void vnc_write_u8(VncState *vs, uint8_t value)
1450 {
1451     vnc_write(vs, (char *)&value, 1);
1452 }
1453 
1454 void vnc_flush(VncState *vs)
1455 {
1456     vnc_lock_output(vs);
1457     if (vs->csock != -1 && (vs->output.offset
1458 #ifdef CONFIG_VNC_WS
1459                 || vs->ws_output.offset
1460 #endif
1461                 )) {
1462         vnc_client_write_locked(vs);
1463     }
1464     vnc_unlock_output(vs);
1465 }
1466 
1467 static uint8_t read_u8(uint8_t *data, size_t offset)
1468 {
1469     return data[offset];
1470 }
1471 
1472 static uint16_t read_u16(uint8_t *data, size_t offset)
1473 {
1474     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1475 }
1476 
1477 static int32_t read_s32(uint8_t *data, size_t offset)
1478 {
1479     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1480                      (data[offset + 2] << 8) | data[offset + 3]);
1481 }
1482 
1483 uint32_t read_u32(uint8_t *data, size_t offset)
1484 {
1485     return ((data[offset] << 24) | (data[offset + 1] << 16) |
1486             (data[offset + 2] << 8) | data[offset + 3]);
1487 }
1488 
1489 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1490 {
1491 }
1492 
1493 static void check_pointer_type_change(Notifier *notifier, void *data)
1494 {
1495     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1496     int absolute = qemu_input_is_absolute();
1497 
1498     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1499         vnc_lock_output(vs);
1500         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1501         vnc_write_u8(vs, 0);
1502         vnc_write_u16(vs, 1);
1503         vnc_framebuffer_update(vs, absolute, 0,
1504                                pixman_image_get_width(vs->vd->server),
1505                                pixman_image_get_height(vs->vd->server),
1506                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1507         vnc_unlock_output(vs);
1508         vnc_flush(vs);
1509     }
1510     vs->absolute = absolute;
1511 }
1512 
1513 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1514 {
1515     static uint32_t bmap[INPUT_BUTTON_MAX] = {
1516         [INPUT_BUTTON_LEFT]       = 0x01,
1517         [INPUT_BUTTON_MIDDLE]     = 0x02,
1518         [INPUT_BUTTON_RIGHT]      = 0x04,
1519         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1520         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1521     };
1522     QemuConsole *con = vs->vd->dcl.con;
1523     int width = pixman_image_get_width(vs->vd->server);
1524     int height = pixman_image_get_height(vs->vd->server);
1525 
1526     if (vs->last_bmask != button_mask) {
1527         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1528         vs->last_bmask = button_mask;
1529     }
1530 
1531     if (vs->absolute) {
1532         qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
1533         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
1534     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1535         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1536         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1537     } else {
1538         if (vs->last_x != -1) {
1539             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1540             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1541         }
1542         vs->last_x = x;
1543         vs->last_y = y;
1544     }
1545     qemu_input_event_sync();
1546 }
1547 
1548 static void reset_keys(VncState *vs)
1549 {
1550     int i;
1551     for(i = 0; i < 256; i++) {
1552         if (vs->modifiers_state[i]) {
1553             qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1554             vs->modifiers_state[i] = 0;
1555         }
1556     }
1557 }
1558 
1559 static void press_key(VncState *vs, int keysym)
1560 {
1561     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1562     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1563     qemu_input_event_send_key_delay(0);
1564     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1565     qemu_input_event_send_key_delay(0);
1566 }
1567 
1568 static int current_led_state(VncState *vs)
1569 {
1570     int ledstate = 0;
1571 
1572     if (vs->modifiers_state[0x46]) {
1573         ledstate |= QEMU_SCROLL_LOCK_LED;
1574     }
1575     if (vs->modifiers_state[0x45]) {
1576         ledstate |= QEMU_NUM_LOCK_LED;
1577     }
1578     if (vs->modifiers_state[0x3a]) {
1579         ledstate |= QEMU_CAPS_LOCK_LED;
1580     }
1581 
1582     return ledstate;
1583 }
1584 
1585 static void vnc_led_state_change(VncState *vs)
1586 {
1587     int ledstate = 0;
1588 
1589     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1590         return;
1591     }
1592 
1593     ledstate = current_led_state(vs);
1594     vnc_lock_output(vs);
1595     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1596     vnc_write_u8(vs, 0);
1597     vnc_write_u16(vs, 1);
1598     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1599     vnc_write_u8(vs, ledstate);
1600     vnc_unlock_output(vs);
1601     vnc_flush(vs);
1602 }
1603 
1604 static void kbd_leds(void *opaque, int ledstate)
1605 {
1606     VncState *vs = opaque;
1607     int caps, num, scr;
1608     bool has_changed = (ledstate != current_led_state(vs));
1609 
1610     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1611                              (ledstate & QEMU_NUM_LOCK_LED),
1612                              (ledstate & QEMU_SCROLL_LOCK_LED));
1613 
1614     caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1615     num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
1616     scr  = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
1617 
1618     if (vs->modifiers_state[0x3a] != caps) {
1619         vs->modifiers_state[0x3a] = caps;
1620     }
1621     if (vs->modifiers_state[0x45] != num) {
1622         vs->modifiers_state[0x45] = num;
1623     }
1624     if (vs->modifiers_state[0x46] != scr) {
1625         vs->modifiers_state[0x46] = scr;
1626     }
1627 
1628     /* Sending the current led state message to the client */
1629     if (has_changed) {
1630         vnc_led_state_change(vs);
1631     }
1632 }
1633 
1634 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1635 {
1636     /* QEMU console switch */
1637     switch(keycode) {
1638     case 0x2a:                          /* Left Shift */
1639     case 0x36:                          /* Right Shift */
1640     case 0x1d:                          /* Left CTRL */
1641     case 0x9d:                          /* Right CTRL */
1642     case 0x38:                          /* Left ALT */
1643     case 0xb8:                          /* Right ALT */
1644         if (down)
1645             vs->modifiers_state[keycode] = 1;
1646         else
1647             vs->modifiers_state[keycode] = 0;
1648         break;
1649     case 0x02 ... 0x0a: /* '1' to '9' keys */
1650         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1651             /* Reset the modifiers sent to the current console */
1652             reset_keys(vs);
1653             console_select(keycode - 0x02);
1654             return;
1655         }
1656         break;
1657     case 0x3a:                        /* CapsLock */
1658     case 0x45:                        /* NumLock */
1659         if (down)
1660             vs->modifiers_state[keycode] ^= 1;
1661         break;
1662     }
1663 
1664     /* Turn off the lock state sync logic if the client support the led
1665        state extension.
1666     */
1667     if (down && vs->vd->lock_key_sync &&
1668         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1669         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1670         /* If the numlock state needs to change then simulate an additional
1671            keypress before sending this one.  This will happen if the user
1672            toggles numlock away from the VNC window.
1673         */
1674         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1675             if (!vs->modifiers_state[0x45]) {
1676                 trace_vnc_key_sync_numlock(true);
1677                 vs->modifiers_state[0x45] = 1;
1678                 press_key(vs, 0xff7f);
1679             }
1680         } else {
1681             if (vs->modifiers_state[0x45]) {
1682                 trace_vnc_key_sync_numlock(false);
1683                 vs->modifiers_state[0x45] = 0;
1684                 press_key(vs, 0xff7f);
1685             }
1686         }
1687     }
1688 
1689     if (down && vs->vd->lock_key_sync &&
1690         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1691         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1692         /* If the capslock state needs to change then simulate an additional
1693            keypress before sending this one.  This will happen if the user
1694            toggles capslock away from the VNC window.
1695         */
1696         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1697         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1698         int capslock = !!(vs->modifiers_state[0x3a]);
1699         if (capslock) {
1700             if (uppercase == shift) {
1701                 trace_vnc_key_sync_capslock(false);
1702                 vs->modifiers_state[0x3a] = 0;
1703                 press_key(vs, 0xffe5);
1704             }
1705         } else {
1706             if (uppercase != shift) {
1707                 trace_vnc_key_sync_capslock(true);
1708                 vs->modifiers_state[0x3a] = 1;
1709                 press_key(vs, 0xffe5);
1710             }
1711         }
1712     }
1713 
1714     if (qemu_console_is_graphic(NULL)) {
1715         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1716     } else {
1717         bool numlock = vs->modifiers_state[0x45];
1718         bool control = (vs->modifiers_state[0x1d] ||
1719                         vs->modifiers_state[0x9d]);
1720         /* QEMU console emulation */
1721         if (down) {
1722             switch (keycode) {
1723             case 0x2a:                          /* Left Shift */
1724             case 0x36:                          /* Right Shift */
1725             case 0x1d:                          /* Left CTRL */
1726             case 0x9d:                          /* Right CTRL */
1727             case 0x38:                          /* Left ALT */
1728             case 0xb8:                          /* Right ALT */
1729                 break;
1730             case 0xc8:
1731                 kbd_put_keysym(QEMU_KEY_UP);
1732                 break;
1733             case 0xd0:
1734                 kbd_put_keysym(QEMU_KEY_DOWN);
1735                 break;
1736             case 0xcb:
1737                 kbd_put_keysym(QEMU_KEY_LEFT);
1738                 break;
1739             case 0xcd:
1740                 kbd_put_keysym(QEMU_KEY_RIGHT);
1741                 break;
1742             case 0xd3:
1743                 kbd_put_keysym(QEMU_KEY_DELETE);
1744                 break;
1745             case 0xc7:
1746                 kbd_put_keysym(QEMU_KEY_HOME);
1747                 break;
1748             case 0xcf:
1749                 kbd_put_keysym(QEMU_KEY_END);
1750                 break;
1751             case 0xc9:
1752                 kbd_put_keysym(QEMU_KEY_PAGEUP);
1753                 break;
1754             case 0xd1:
1755                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1756                 break;
1757 
1758             case 0x47:
1759                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1760                 break;
1761             case 0x48:
1762                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1763                 break;
1764             case 0x49:
1765                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1766                 break;
1767             case 0x4b:
1768                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1769                 break;
1770             case 0x4c:
1771                 kbd_put_keysym('5');
1772                 break;
1773             case 0x4d:
1774                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1775                 break;
1776             case 0x4f:
1777                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1778                 break;
1779             case 0x50:
1780                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1781                 break;
1782             case 0x51:
1783                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1784                 break;
1785             case 0x52:
1786                 kbd_put_keysym('0');
1787                 break;
1788             case 0x53:
1789                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1790                 break;
1791 
1792             case 0xb5:
1793                 kbd_put_keysym('/');
1794                 break;
1795             case 0x37:
1796                 kbd_put_keysym('*');
1797                 break;
1798             case 0x4a:
1799                 kbd_put_keysym('-');
1800                 break;
1801             case 0x4e:
1802                 kbd_put_keysym('+');
1803                 break;
1804             case 0x9c:
1805                 kbd_put_keysym('\n');
1806                 break;
1807 
1808             default:
1809                 if (control) {
1810                     kbd_put_keysym(sym & 0x1f);
1811                 } else {
1812                     kbd_put_keysym(sym);
1813                 }
1814                 break;
1815             }
1816         }
1817     }
1818 }
1819 
1820 static void vnc_release_modifiers(VncState *vs)
1821 {
1822     static const int keycodes[] = {
1823         /* shift, control, alt keys, both left & right */
1824         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1825     };
1826     int i, keycode;
1827 
1828     if (!qemu_console_is_graphic(NULL)) {
1829         return;
1830     }
1831     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1832         keycode = keycodes[i];
1833         if (!vs->modifiers_state[keycode]) {
1834             continue;
1835         }
1836         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1837     }
1838 }
1839 
1840 static const char *code2name(int keycode)
1841 {
1842     return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
1843 }
1844 
1845 static void key_event(VncState *vs, int down, uint32_t sym)
1846 {
1847     int keycode;
1848     int lsym = sym;
1849 
1850     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1851         lsym = lsym - 'A' + 'a';
1852     }
1853 
1854     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1855     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1856     do_key_event(vs, down, keycode, sym);
1857 }
1858 
1859 static void ext_key_event(VncState *vs, int down,
1860                           uint32_t sym, uint16_t keycode)
1861 {
1862     /* if the user specifies a keyboard layout, always use it */
1863     if (keyboard_layout) {
1864         key_event(vs, down, sym);
1865     } else {
1866         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
1867         do_key_event(vs, down, keycode, sym);
1868     }
1869 }
1870 
1871 static void framebuffer_update_request(VncState *vs, int incremental,
1872                                        int x, int y, int w, int h)
1873 {
1874     int width = pixman_image_get_width(vs->vd->server);
1875     int height = pixman_image_get_height(vs->vd->server);
1876 
1877     vs->need_update = 1;
1878 
1879     if (incremental) {
1880         return;
1881     }
1882 
1883     vs->force_update = 1;
1884     vnc_set_area_dirty(vs->dirty, width, height, x, y, w, h);
1885 }
1886 
1887 static void send_ext_key_event_ack(VncState *vs)
1888 {
1889     vnc_lock_output(vs);
1890     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1891     vnc_write_u8(vs, 0);
1892     vnc_write_u16(vs, 1);
1893     vnc_framebuffer_update(vs, 0, 0,
1894                            pixman_image_get_width(vs->vd->server),
1895                            pixman_image_get_height(vs->vd->server),
1896                            VNC_ENCODING_EXT_KEY_EVENT);
1897     vnc_unlock_output(vs);
1898     vnc_flush(vs);
1899 }
1900 
1901 static void send_ext_audio_ack(VncState *vs)
1902 {
1903     vnc_lock_output(vs);
1904     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1905     vnc_write_u8(vs, 0);
1906     vnc_write_u16(vs, 1);
1907     vnc_framebuffer_update(vs, 0, 0,
1908                            pixman_image_get_width(vs->vd->server),
1909                            pixman_image_get_height(vs->vd->server),
1910                            VNC_ENCODING_AUDIO);
1911     vnc_unlock_output(vs);
1912     vnc_flush(vs);
1913 }
1914 
1915 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1916 {
1917     int i;
1918     unsigned int enc = 0;
1919 
1920     vs->features = 0;
1921     vs->vnc_encoding = 0;
1922     vs->tight.compression = 9;
1923     vs->tight.quality = -1; /* Lossless by default */
1924     vs->absolute = -1;
1925 
1926     /*
1927      * Start from the end because the encodings are sent in order of preference.
1928      * This way the preferred encoding (first encoding defined in the array)
1929      * will be set at the end of the loop.
1930      */
1931     for (i = n_encodings - 1; i >= 0; i--) {
1932         enc = encodings[i];
1933         switch (enc) {
1934         case VNC_ENCODING_RAW:
1935             vs->vnc_encoding = enc;
1936             break;
1937         case VNC_ENCODING_COPYRECT:
1938             vs->features |= VNC_FEATURE_COPYRECT_MASK;
1939             break;
1940         case VNC_ENCODING_HEXTILE:
1941             vs->features |= VNC_FEATURE_HEXTILE_MASK;
1942             vs->vnc_encoding = enc;
1943             break;
1944         case VNC_ENCODING_TIGHT:
1945             vs->features |= VNC_FEATURE_TIGHT_MASK;
1946             vs->vnc_encoding = enc;
1947             break;
1948 #ifdef CONFIG_VNC_PNG
1949         case VNC_ENCODING_TIGHT_PNG:
1950             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
1951             vs->vnc_encoding = enc;
1952             break;
1953 #endif
1954         case VNC_ENCODING_ZLIB:
1955             vs->features |= VNC_FEATURE_ZLIB_MASK;
1956             vs->vnc_encoding = enc;
1957             break;
1958         case VNC_ENCODING_ZRLE:
1959             vs->features |= VNC_FEATURE_ZRLE_MASK;
1960             vs->vnc_encoding = enc;
1961             break;
1962         case VNC_ENCODING_ZYWRLE:
1963             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
1964             vs->vnc_encoding = enc;
1965             break;
1966         case VNC_ENCODING_DESKTOPRESIZE:
1967             vs->features |= VNC_FEATURE_RESIZE_MASK;
1968             break;
1969         case VNC_ENCODING_POINTER_TYPE_CHANGE:
1970             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1971             break;
1972         case VNC_ENCODING_RICH_CURSOR:
1973             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1974             break;
1975         case VNC_ENCODING_EXT_KEY_EVENT:
1976             send_ext_key_event_ack(vs);
1977             break;
1978         case VNC_ENCODING_AUDIO:
1979             send_ext_audio_ack(vs);
1980             break;
1981         case VNC_ENCODING_WMVi:
1982             vs->features |= VNC_FEATURE_WMVI_MASK;
1983             break;
1984         case VNC_ENCODING_LED_STATE:
1985             vs->features |= VNC_FEATURE_LED_STATE_MASK;
1986             break;
1987         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1988             vs->tight.compression = (enc & 0x0F);
1989             break;
1990         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1991             if (vs->vd->lossy) {
1992                 vs->tight.quality = (enc & 0x0F);
1993             }
1994             break;
1995         default:
1996             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1997             break;
1998         }
1999     }
2000     vnc_desktop_resize(vs);
2001     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2002     vnc_led_state_change(vs);
2003 }
2004 
2005 static void set_pixel_conversion(VncState *vs)
2006 {
2007     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2008 
2009     if (fmt == VNC_SERVER_FB_FORMAT) {
2010         vs->write_pixels = vnc_write_pixels_copy;
2011         vnc_hextile_set_pixel_conversion(vs, 0);
2012     } else {
2013         vs->write_pixels = vnc_write_pixels_generic;
2014         vnc_hextile_set_pixel_conversion(vs, 1);
2015     }
2016 }
2017 
2018 static void set_pixel_format(VncState *vs,
2019                              int bits_per_pixel, int depth,
2020                              int big_endian_flag, int true_color_flag,
2021                              int red_max, int green_max, int blue_max,
2022                              int red_shift, int green_shift, int blue_shift)
2023 {
2024     if (!true_color_flag) {
2025         vnc_client_error(vs);
2026         return;
2027     }
2028 
2029     switch (bits_per_pixel) {
2030     case 8:
2031     case 16:
2032     case 32:
2033         break;
2034     default:
2035         vnc_client_error(vs);
2036         return;
2037     }
2038 
2039     vs->client_pf.rmax = red_max;
2040     vs->client_pf.rbits = hweight_long(red_max);
2041     vs->client_pf.rshift = red_shift;
2042     vs->client_pf.rmask = red_max << red_shift;
2043     vs->client_pf.gmax = green_max;
2044     vs->client_pf.gbits = hweight_long(green_max);
2045     vs->client_pf.gshift = green_shift;
2046     vs->client_pf.gmask = green_max << green_shift;
2047     vs->client_pf.bmax = blue_max;
2048     vs->client_pf.bbits = hweight_long(blue_max);
2049     vs->client_pf.bshift = blue_shift;
2050     vs->client_pf.bmask = blue_max << blue_shift;
2051     vs->client_pf.bits_per_pixel = bits_per_pixel;
2052     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2053     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2054     vs->client_be = big_endian_flag;
2055 
2056     set_pixel_conversion(vs);
2057 
2058     graphic_hw_invalidate(NULL);
2059     graphic_hw_update(NULL);
2060 }
2061 
2062 static void pixel_format_message (VncState *vs) {
2063     char pad[3] = { 0, 0, 0 };
2064 
2065     vs->client_pf = qemu_default_pixelformat(32);
2066 
2067     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2068     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2069 
2070 #ifdef HOST_WORDS_BIGENDIAN
2071     vnc_write_u8(vs, 1);             /* big-endian-flag */
2072 #else
2073     vnc_write_u8(vs, 0);             /* big-endian-flag */
2074 #endif
2075     vnc_write_u8(vs, 1);             /* true-color-flag */
2076     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
2077     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
2078     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
2079     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
2080     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
2081     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
2082     vnc_write(vs, pad, 3);           /* padding */
2083 
2084     vnc_hextile_set_pixel_conversion(vs, 0);
2085     vs->write_pixels = vnc_write_pixels_copy;
2086 }
2087 
2088 static void vnc_colordepth(VncState *vs)
2089 {
2090     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2091         /* Sending a WMVi message to notify the client*/
2092         vnc_lock_output(vs);
2093         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2094         vnc_write_u8(vs, 0);
2095         vnc_write_u16(vs, 1); /* number of rects */
2096         vnc_framebuffer_update(vs, 0, 0,
2097                                pixman_image_get_width(vs->vd->server),
2098                                pixman_image_get_height(vs->vd->server),
2099                                VNC_ENCODING_WMVi);
2100         pixel_format_message(vs);
2101         vnc_unlock_output(vs);
2102         vnc_flush(vs);
2103     } else {
2104         set_pixel_conversion(vs);
2105     }
2106 }
2107 
2108 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2109 {
2110     int i;
2111     uint16_t limit;
2112     VncDisplay *vd = vs->vd;
2113 
2114     if (data[0] > 3) {
2115         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2116     }
2117 
2118     switch (data[0]) {
2119     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2120         if (len == 1)
2121             return 20;
2122 
2123         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
2124                          read_u8(data, 6), read_u8(data, 7),
2125                          read_u16(data, 8), read_u16(data, 10),
2126                          read_u16(data, 12), read_u8(data, 14),
2127                          read_u8(data, 15), read_u8(data, 16));
2128         break;
2129     case VNC_MSG_CLIENT_SET_ENCODINGS:
2130         if (len == 1)
2131             return 4;
2132 
2133         if (len == 4) {
2134             limit = read_u16(data, 2);
2135             if (limit > 0)
2136                 return 4 + (limit * 4);
2137         } else
2138             limit = read_u16(data, 2);
2139 
2140         for (i = 0; i < limit; i++) {
2141             int32_t val = read_s32(data, 4 + (i * 4));
2142             memcpy(data + 4 + (i * 4), &val, sizeof(val));
2143         }
2144 
2145         set_encodings(vs, (int32_t *)(data + 4), limit);
2146         break;
2147     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2148         if (len == 1)
2149             return 10;
2150 
2151         framebuffer_update_request(vs,
2152                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2153                                    read_u16(data, 6), read_u16(data, 8));
2154         break;
2155     case VNC_MSG_CLIENT_KEY_EVENT:
2156         if (len == 1)
2157             return 8;
2158 
2159         key_event(vs, read_u8(data, 1), read_u32(data, 4));
2160         break;
2161     case VNC_MSG_CLIENT_POINTER_EVENT:
2162         if (len == 1)
2163             return 6;
2164 
2165         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2166         break;
2167     case VNC_MSG_CLIENT_CUT_TEXT:
2168         if (len == 1) {
2169             return 8;
2170         }
2171         if (len == 8) {
2172             uint32_t dlen = read_u32(data, 4);
2173             if (dlen > (1 << 20)) {
2174                 error_report("vnc: client_cut_text msg payload has %u bytes"
2175                              " which exceeds our limit of 1MB.", dlen);
2176                 vnc_client_error(vs);
2177                 break;
2178             }
2179             if (dlen > 0) {
2180                 return 8 + dlen;
2181             }
2182         }
2183 
2184         client_cut_text(vs, read_u32(data, 4), data + 8);
2185         break;
2186     case VNC_MSG_CLIENT_QEMU:
2187         if (len == 1)
2188             return 2;
2189 
2190         switch (read_u8(data, 1)) {
2191         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2192             if (len == 2)
2193                 return 12;
2194 
2195             ext_key_event(vs, read_u16(data, 2),
2196                           read_u32(data, 4), read_u32(data, 8));
2197             break;
2198         case VNC_MSG_CLIENT_QEMU_AUDIO:
2199             if (len == 2)
2200                 return 4;
2201 
2202             switch (read_u16 (data, 2)) {
2203             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2204                 audio_add(vs);
2205                 break;
2206             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2207                 audio_del(vs);
2208                 break;
2209             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2210                 if (len == 4)
2211                     return 10;
2212                 switch (read_u8(data, 4)) {
2213                 case 0: vs->as.fmt = AUD_FMT_U8; break;
2214                 case 1: vs->as.fmt = AUD_FMT_S8; break;
2215                 case 2: vs->as.fmt = AUD_FMT_U16; break;
2216                 case 3: vs->as.fmt = AUD_FMT_S16; break;
2217                 case 4: vs->as.fmt = AUD_FMT_U32; break;
2218                 case 5: vs->as.fmt = AUD_FMT_S32; break;
2219                 default:
2220                     printf("Invalid audio format %d\n", read_u8(data, 4));
2221                     vnc_client_error(vs);
2222                     break;
2223                 }
2224                 vs->as.nchannels = read_u8(data, 5);
2225                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2226                     printf("Invalid audio channel coount %d\n",
2227                            read_u8(data, 5));
2228                     vnc_client_error(vs);
2229                     break;
2230                 }
2231                 vs->as.freq = read_u32(data, 6);
2232                 break;
2233             default:
2234                 printf ("Invalid audio message %d\n", read_u8(data, 4));
2235                 vnc_client_error(vs);
2236                 break;
2237             }
2238             break;
2239 
2240         default:
2241             printf("Msg: %d\n", read_u16(data, 0));
2242             vnc_client_error(vs);
2243             break;
2244         }
2245         break;
2246     default:
2247         printf("Msg: %d\n", data[0]);
2248         vnc_client_error(vs);
2249         break;
2250     }
2251 
2252     vnc_read_when(vs, protocol_client_msg, 1);
2253     return 0;
2254 }
2255 
2256 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2257 {
2258     char buf[1024];
2259     VncShareMode mode;
2260     int size;
2261 
2262     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2263     switch (vs->vd->share_policy) {
2264     case VNC_SHARE_POLICY_IGNORE:
2265         /*
2266          * Ignore the shared flag.  Nothing to do here.
2267          *
2268          * Doesn't conform to the rfb spec but is traditional qemu
2269          * behavior, thus left here as option for compatibility
2270          * reasons.
2271          */
2272         break;
2273     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2274         /*
2275          * Policy: Allow clients ask for exclusive access.
2276          *
2277          * Implementation: When a client asks for exclusive access,
2278          * disconnect all others. Shared connects are allowed as long
2279          * as no exclusive connection exists.
2280          *
2281          * This is how the rfb spec suggests to handle the shared flag.
2282          */
2283         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2284             VncState *client;
2285             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2286                 if (vs == client) {
2287                     continue;
2288                 }
2289                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2290                     client->share_mode != VNC_SHARE_MODE_SHARED) {
2291                     continue;
2292                 }
2293                 vnc_disconnect_start(client);
2294             }
2295         }
2296         if (mode == VNC_SHARE_MODE_SHARED) {
2297             if (vs->vd->num_exclusive > 0) {
2298                 vnc_disconnect_start(vs);
2299                 return 0;
2300             }
2301         }
2302         break;
2303     case VNC_SHARE_POLICY_FORCE_SHARED:
2304         /*
2305          * Policy: Shared connects only.
2306          * Implementation: Disallow clients asking for exclusive access.
2307          *
2308          * Useful for shared desktop sessions where you don't want
2309          * someone forgetting to say -shared when running the vnc
2310          * client disconnect everybody else.
2311          */
2312         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2313             vnc_disconnect_start(vs);
2314             return 0;
2315         }
2316         break;
2317     }
2318     vnc_set_share_mode(vs, mode);
2319 
2320     vs->client_width = pixman_image_get_width(vs->vd->server);
2321     vs->client_height = pixman_image_get_height(vs->vd->server);
2322     vnc_write_u16(vs, vs->client_width);
2323     vnc_write_u16(vs, vs->client_height);
2324 
2325     pixel_format_message(vs);
2326 
2327     if (qemu_name)
2328         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2329     else
2330         size = snprintf(buf, sizeof(buf), "QEMU");
2331 
2332     vnc_write_u32(vs, size);
2333     vnc_write(vs, buf, size);
2334     vnc_flush(vs);
2335 
2336     vnc_client_cache_auth(vs);
2337     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2338 
2339     vnc_read_when(vs, protocol_client_msg, 1);
2340 
2341     return 0;
2342 }
2343 
2344 void start_client_init(VncState *vs)
2345 {
2346     vnc_read_when(vs, protocol_client_init, 1);
2347 }
2348 
2349 static void make_challenge(VncState *vs)
2350 {
2351     int i;
2352 
2353     srand(time(NULL)+getpid()+getpid()*987654+rand());
2354 
2355     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2356         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2357 }
2358 
2359 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2360 {
2361     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2362     int i, j, pwlen;
2363     unsigned char key[8];
2364     time_t now = time(NULL);
2365 
2366     if (!vs->vd->password) {
2367         VNC_DEBUG("No password configured on server");
2368         goto reject;
2369     }
2370     if (vs->vd->expires < now) {
2371         VNC_DEBUG("Password is expired");
2372         goto reject;
2373     }
2374 
2375     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2376 
2377     /* Calculate the expected challenge response */
2378     pwlen = strlen(vs->vd->password);
2379     for (i=0; i<sizeof(key); i++)
2380         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2381     deskey(key, EN0);
2382     for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2383         des(response+j, response+j);
2384 
2385     /* Compare expected vs actual challenge response */
2386     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2387         VNC_DEBUG("Client challenge response did not match\n");
2388         goto reject;
2389     } else {
2390         VNC_DEBUG("Accepting VNC challenge response\n");
2391         vnc_write_u32(vs, 0); /* Accept auth */
2392         vnc_flush(vs);
2393 
2394         start_client_init(vs);
2395     }
2396     return 0;
2397 
2398 reject:
2399     vnc_write_u32(vs, 1); /* Reject auth */
2400     if (vs->minor >= 8) {
2401         static const char err[] = "Authentication failed";
2402         vnc_write_u32(vs, sizeof(err));
2403         vnc_write(vs, err, sizeof(err));
2404     }
2405     vnc_flush(vs);
2406     vnc_client_error(vs);
2407     return 0;
2408 }
2409 
2410 void start_auth_vnc(VncState *vs)
2411 {
2412     make_challenge(vs);
2413     /* Send client a 'random' challenge */
2414     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2415     vnc_flush(vs);
2416 
2417     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2418 }
2419 
2420 
2421 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2422 {
2423     /* We only advertise 1 auth scheme at a time, so client
2424      * must pick the one we sent. Verify this */
2425     if (data[0] != vs->auth) { /* Reject auth */
2426        VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2427        vnc_write_u32(vs, 1);
2428        if (vs->minor >= 8) {
2429            static const char err[] = "Authentication failed";
2430            vnc_write_u32(vs, sizeof(err));
2431            vnc_write(vs, err, sizeof(err));
2432        }
2433        vnc_client_error(vs);
2434     } else { /* Accept requested auth */
2435        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2436        switch (vs->auth) {
2437        case VNC_AUTH_NONE:
2438            VNC_DEBUG("Accept auth none\n");
2439            if (vs->minor >= 8) {
2440                vnc_write_u32(vs, 0); /* Accept auth completion */
2441                vnc_flush(vs);
2442            }
2443            start_client_init(vs);
2444            break;
2445 
2446        case VNC_AUTH_VNC:
2447            VNC_DEBUG("Start VNC auth\n");
2448            start_auth_vnc(vs);
2449            break;
2450 
2451 #ifdef CONFIG_VNC_TLS
2452        case VNC_AUTH_VENCRYPT:
2453            VNC_DEBUG("Accept VeNCrypt auth\n");
2454            start_auth_vencrypt(vs);
2455            break;
2456 #endif /* CONFIG_VNC_TLS */
2457 
2458 #ifdef CONFIG_VNC_SASL
2459        case VNC_AUTH_SASL:
2460            VNC_DEBUG("Accept SASL auth\n");
2461            start_auth_sasl(vs);
2462            break;
2463 #endif /* CONFIG_VNC_SASL */
2464 
2465        default: /* Should not be possible, but just in case */
2466            VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2467            vnc_write_u8(vs, 1);
2468            if (vs->minor >= 8) {
2469                static const char err[] = "Authentication failed";
2470                vnc_write_u32(vs, sizeof(err));
2471                vnc_write(vs, err, sizeof(err));
2472            }
2473            vnc_client_error(vs);
2474        }
2475     }
2476     return 0;
2477 }
2478 
2479 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2480 {
2481     char local[13];
2482 
2483     memcpy(local, version, 12);
2484     local[12] = 0;
2485 
2486     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2487         VNC_DEBUG("Malformed protocol version %s\n", local);
2488         vnc_client_error(vs);
2489         return 0;
2490     }
2491     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2492     if (vs->major != 3 ||
2493         (vs->minor != 3 &&
2494          vs->minor != 4 &&
2495          vs->minor != 5 &&
2496          vs->minor != 7 &&
2497          vs->minor != 8)) {
2498         VNC_DEBUG("Unsupported client version\n");
2499         vnc_write_u32(vs, VNC_AUTH_INVALID);
2500         vnc_flush(vs);
2501         vnc_client_error(vs);
2502         return 0;
2503     }
2504     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2505      * as equivalent to v3.3 by servers
2506      */
2507     if (vs->minor == 4 || vs->minor == 5)
2508         vs->minor = 3;
2509 
2510     if (vs->minor == 3) {
2511         if (vs->auth == VNC_AUTH_NONE) {
2512             VNC_DEBUG("Tell client auth none\n");
2513             vnc_write_u32(vs, vs->auth);
2514             vnc_flush(vs);
2515             start_client_init(vs);
2516        } else if (vs->auth == VNC_AUTH_VNC) {
2517             VNC_DEBUG("Tell client VNC auth\n");
2518             vnc_write_u32(vs, vs->auth);
2519             vnc_flush(vs);
2520             start_auth_vnc(vs);
2521        } else {
2522             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2523             vnc_write_u32(vs, VNC_AUTH_INVALID);
2524             vnc_flush(vs);
2525             vnc_client_error(vs);
2526        }
2527     } else {
2528         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2529         vnc_write_u8(vs, 1); /* num auth */
2530         vnc_write_u8(vs, vs->auth);
2531         vnc_read_when(vs, protocol_client_auth, 1);
2532         vnc_flush(vs);
2533     }
2534 
2535     return 0;
2536 }
2537 
2538 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2539 {
2540     struct VncSurface *vs = &vd->guest;
2541 
2542     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2543 }
2544 
2545 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2546 {
2547     int i, j;
2548 
2549     w = (x + w) / VNC_STAT_RECT;
2550     h = (y + h) / VNC_STAT_RECT;
2551     x /= VNC_STAT_RECT;
2552     y /= VNC_STAT_RECT;
2553 
2554     for (j = y; j <= h; j++) {
2555         for (i = x; i <= w; i++) {
2556             vs->lossy_rect[j][i] = 1;
2557         }
2558     }
2559 }
2560 
2561 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2562 {
2563     VncState *vs;
2564     int sty = y / VNC_STAT_RECT;
2565     int stx = x / VNC_STAT_RECT;
2566     int has_dirty = 0;
2567 
2568     y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2569     x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2570 
2571     QTAILQ_FOREACH(vs, &vd->clients, next) {
2572         int j;
2573 
2574         /* kernel send buffers are full -> refresh later */
2575         if (vs->output.offset) {
2576             continue;
2577         }
2578 
2579         if (!vs->lossy_rect[sty][stx]) {
2580             continue;
2581         }
2582 
2583         vs->lossy_rect[sty][stx] = 0;
2584         for (j = 0; j < VNC_STAT_RECT; ++j) {
2585             bitmap_set(vs->dirty[y + j],
2586                        x / VNC_DIRTY_PIXELS_PER_BIT,
2587                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2588         }
2589         has_dirty++;
2590     }
2591 
2592     return has_dirty;
2593 }
2594 
2595 static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2596 {
2597     int width = pixman_image_get_width(vd->guest.fb);
2598     int height = pixman_image_get_height(vd->guest.fb);
2599     int x, y;
2600     struct timeval res;
2601     int has_dirty = 0;
2602 
2603     for (y = 0; y < height; y += VNC_STAT_RECT) {
2604         for (x = 0; x < width; x += VNC_STAT_RECT) {
2605             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2606 
2607             rect->updated = false;
2608         }
2609     }
2610 
2611     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2612 
2613     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2614         return has_dirty;
2615     }
2616     vd->guest.last_freq_check = *tv;
2617 
2618     for (y = 0; y < height; y += VNC_STAT_RECT) {
2619         for (x = 0; x < width; x += VNC_STAT_RECT) {
2620             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2621             int count = ARRAY_SIZE(rect->times);
2622             struct timeval min, max;
2623 
2624             if (!timerisset(&rect->times[count - 1])) {
2625                 continue ;
2626             }
2627 
2628             max = rect->times[(rect->idx + count - 1) % count];
2629             qemu_timersub(tv, &max, &res);
2630 
2631             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2632                 rect->freq = 0;
2633                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2634                 memset(rect->times, 0, sizeof (rect->times));
2635                 continue ;
2636             }
2637 
2638             min = rect->times[rect->idx];
2639             max = rect->times[(rect->idx + count - 1) % count];
2640             qemu_timersub(&max, &min, &res);
2641 
2642             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2643             rect->freq /= count;
2644             rect->freq = 1. / rect->freq;
2645         }
2646     }
2647     return has_dirty;
2648 }
2649 
2650 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2651 {
2652     int i, j;
2653     double total = 0;
2654     int num = 0;
2655 
2656     x =  (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2657     y =  (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2658 
2659     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2660         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2661             total += vnc_stat_rect(vs->vd, i, j)->freq;
2662             num++;
2663         }
2664     }
2665 
2666     if (num) {
2667         return total / num;
2668     } else {
2669         return 0;
2670     }
2671 }
2672 
2673 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2674 {
2675     VncRectStat *rect;
2676 
2677     rect = vnc_stat_rect(vd, x, y);
2678     if (rect->updated) {
2679         return ;
2680     }
2681     rect->times[rect->idx] = *tv;
2682     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2683     rect->updated = true;
2684 }
2685 
2686 static int vnc_refresh_server_surface(VncDisplay *vd)
2687 {
2688     int width = MIN(pixman_image_get_width(vd->guest.fb),
2689                     pixman_image_get_width(vd->server));
2690     int height = MIN(pixman_image_get_height(vd->guest.fb),
2691                      pixman_image_get_height(vd->server));
2692     int cmp_bytes, server_stride, min_stride, guest_stride, y = 0;
2693     uint8_t *guest_row0 = NULL, *server_row0;
2694     VncState *vs;
2695     int has_dirty = 0;
2696     pixman_image_t *tmpbuf = NULL;
2697 
2698     struct timeval tv = { 0, 0 };
2699 
2700     if (!vd->non_adaptive) {
2701         gettimeofday(&tv, NULL);
2702         has_dirty = vnc_update_stats(vd, &tv);
2703     }
2704 
2705     /*
2706      * Walk through the guest dirty map.
2707      * Check and copy modified bits from guest to server surface.
2708      * Update server dirty map.
2709      */
2710     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2711     server_stride = guest_stride = pixman_image_get_stride(vd->server);
2712     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2713                     server_stride);
2714     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2715         int width = pixman_image_get_width(vd->server);
2716         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2717     } else {
2718         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2719         guest_stride = pixman_image_get_stride(vd->guest.fb);
2720     }
2721     min_stride = MIN(server_stride, guest_stride);
2722 
2723     for (;;) {
2724         int x;
2725         uint8_t *guest_ptr, *server_ptr;
2726         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2727                                              height * VNC_DIRTY_BPL(&vd->guest),
2728                                              y * VNC_DIRTY_BPL(&vd->guest));
2729         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2730             /* no more dirty bits */
2731             break;
2732         }
2733         y = offset / VNC_DIRTY_BPL(&vd->guest);
2734         x = offset % VNC_DIRTY_BPL(&vd->guest);
2735 
2736         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2737 
2738         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2739             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2740             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2741         } else {
2742             guest_ptr = guest_row0 + y * guest_stride;
2743         }
2744         guest_ptr += x * cmp_bytes;
2745 
2746         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2747              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2748             int _cmp_bytes = cmp_bytes;
2749             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2750                 continue;
2751             }
2752             if ((x + 1) * cmp_bytes > min_stride) {
2753                 _cmp_bytes = min_stride - x * cmp_bytes;
2754             }
2755             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2756                 continue;
2757             }
2758             memcpy(server_ptr, guest_ptr, _cmp_bytes);
2759             if (!vd->non_adaptive) {
2760                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2761                                  y, &tv);
2762             }
2763             QTAILQ_FOREACH(vs, &vd->clients, next) {
2764                 set_bit(x, vs->dirty[y]);
2765             }
2766             has_dirty++;
2767         }
2768 
2769         y++;
2770     }
2771     qemu_pixman_image_unref(tmpbuf);
2772     return has_dirty;
2773 }
2774 
2775 static void vnc_refresh(DisplayChangeListener *dcl)
2776 {
2777     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2778     VncState *vs, *vn;
2779     int has_dirty, rects = 0;
2780 
2781     if (QTAILQ_EMPTY(&vd->clients)) {
2782         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2783         return;
2784     }
2785 
2786     graphic_hw_update(NULL);
2787 
2788     if (vnc_trylock_display(vd)) {
2789         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2790         return;
2791     }
2792 
2793     has_dirty = vnc_refresh_server_surface(vd);
2794     vnc_unlock_display(vd);
2795 
2796     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2797         rects += vnc_update_client(vs, has_dirty, false);
2798         /* vs might be free()ed here */
2799     }
2800 
2801     if (has_dirty && rects) {
2802         vd->dcl.update_interval /= 2;
2803         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
2804             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
2805         }
2806     } else {
2807         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
2808         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
2809             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
2810         }
2811     }
2812 }
2813 
2814 static void vnc_connect(VncDisplay *vd, int csock,
2815                         bool skipauth, bool websocket)
2816 {
2817     VncState *vs = g_malloc0(sizeof(VncState));
2818     int i;
2819 
2820     vs->csock = csock;
2821 
2822     if (skipauth) {
2823 	vs->auth = VNC_AUTH_NONE;
2824 #ifdef CONFIG_VNC_TLS
2825 	vs->subauth = VNC_AUTH_INVALID;
2826 #endif
2827     } else {
2828 	vs->auth = vd->auth;
2829 #ifdef CONFIG_VNC_TLS
2830 	vs->subauth = vd->subauth;
2831 #endif
2832     }
2833 
2834     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
2835     for (i = 0; i < VNC_STAT_ROWS; ++i) {
2836         vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
2837     }
2838 
2839     VNC_DEBUG("New client on socket %d\n", csock);
2840     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2841     qemu_set_nonblock(vs->csock);
2842 #ifdef CONFIG_VNC_WS
2843     if (websocket) {
2844         vs->websocket = 1;
2845 #ifdef CONFIG_VNC_TLS
2846         if (vd->tls.x509cert) {
2847             qemu_set_fd_handler2(vs->csock, NULL, vncws_tls_handshake_peek,
2848                                  NULL, vs);
2849         } else
2850 #endif /* CONFIG_VNC_TLS */
2851         {
2852             qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read,
2853                                  NULL, vs);
2854         }
2855     } else
2856 #endif /* CONFIG_VNC_WS */
2857     {
2858         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2859     }
2860 
2861     vnc_client_cache_addr(vs);
2862     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
2863     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
2864 
2865     vs->vd = vd;
2866 
2867 #ifdef CONFIG_VNC_WS
2868     if (!vs->websocket)
2869 #endif
2870     {
2871         vnc_init_state(vs);
2872     }
2873 }
2874 
2875 void vnc_init_state(VncState *vs)
2876 {
2877     vs->initialized = true;
2878     VncDisplay *vd = vs->vd;
2879 
2880     vs->last_x = -1;
2881     vs->last_y = -1;
2882 
2883     vs->as.freq = 44100;
2884     vs->as.nchannels = 2;
2885     vs->as.fmt = AUD_FMT_S16;
2886     vs->as.endianness = 0;
2887 
2888     qemu_mutex_init(&vs->output_mutex);
2889     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
2890 
2891     QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2892 
2893     graphic_hw_update(NULL);
2894 
2895     vnc_write(vs, "RFB 003.008\n", 12);
2896     vnc_flush(vs);
2897     vnc_read_when(vs, protocol_version, 12);
2898     reset_keys(vs);
2899     if (vs->vd->lock_key_sync)
2900         vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2901 
2902     vs->mouse_mode_notifier.notify = check_pointer_type_change;
2903     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2904 
2905     /* vs might be free()ed here */
2906 }
2907 
2908 static void vnc_listen_read(void *opaque, bool websocket)
2909 {
2910     VncDisplay *vs = opaque;
2911     struct sockaddr_in addr;
2912     socklen_t addrlen = sizeof(addr);
2913     int csock;
2914 
2915     /* Catch-up */
2916     graphic_hw_update(NULL);
2917 #ifdef CONFIG_VNC_WS
2918     if (websocket) {
2919         csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
2920     } else
2921 #endif /* CONFIG_VNC_WS */
2922     {
2923         csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2924     }
2925 
2926     if (csock != -1) {
2927         socket_set_nodelay(csock);
2928         vnc_connect(vs, csock, false, websocket);
2929     }
2930 }
2931 
2932 static void vnc_listen_regular_read(void *opaque)
2933 {
2934     vnc_listen_read(opaque, false);
2935 }
2936 
2937 #ifdef CONFIG_VNC_WS
2938 static void vnc_listen_websocket_read(void *opaque)
2939 {
2940     vnc_listen_read(opaque, true);
2941 }
2942 #endif /* CONFIG_VNC_WS */
2943 
2944 static const DisplayChangeListenerOps dcl_ops = {
2945     .dpy_name          = "vnc",
2946     .dpy_refresh       = vnc_refresh,
2947     .dpy_gfx_copy      = vnc_dpy_copy,
2948     .dpy_gfx_update    = vnc_dpy_update,
2949     .dpy_gfx_switch    = vnc_dpy_switch,
2950     .dpy_mouse_set     = vnc_mouse_set,
2951     .dpy_cursor_define = vnc_dpy_cursor_define,
2952 };
2953 
2954 void vnc_display_init(DisplayState *ds)
2955 {
2956     VncDisplay *vs = g_malloc0(sizeof(*vs));
2957 
2958     vnc_display = vs;
2959 
2960     vs->lsock = -1;
2961 #ifdef CONFIG_VNC_WS
2962     vs->lwebsock = -1;
2963 #endif
2964 
2965     QTAILQ_INIT(&vs->clients);
2966     vs->expires = TIME_MAX;
2967 
2968     if (keyboard_layout) {
2969         trace_vnc_key_map_init(keyboard_layout);
2970         vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2971     } else {
2972         vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2973     }
2974 
2975     if (!vs->kbd_layout)
2976         exit(1);
2977 
2978     qemu_mutex_init(&vs->mutex);
2979     vnc_start_worker_thread();
2980 
2981     vs->dcl.ops = &dcl_ops;
2982     register_displaychangelistener(&vs->dcl);
2983 }
2984 
2985 
2986 static void vnc_display_close(DisplayState *ds)
2987 {
2988     VncDisplay *vs = vnc_display;
2989 
2990     if (!vs)
2991         return;
2992     g_free(vs->display);
2993     vs->display = NULL;
2994     if (vs->lsock != -1) {
2995         qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2996         close(vs->lsock);
2997         vs->lsock = -1;
2998     }
2999 #ifdef CONFIG_VNC_WS
3000     g_free(vs->ws_display);
3001     vs->ws_display = NULL;
3002     if (vs->lwebsock != -1) {
3003         qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
3004         close(vs->lwebsock);
3005         vs->lwebsock = -1;
3006     }
3007 #endif /* CONFIG_VNC_WS */
3008     vs->auth = VNC_AUTH_INVALID;
3009 #ifdef CONFIG_VNC_TLS
3010     vs->subauth = VNC_AUTH_INVALID;
3011     vs->tls.x509verify = 0;
3012 #endif
3013 }
3014 
3015 int vnc_display_password(DisplayState *ds, const char *password)
3016 {
3017     VncDisplay *vs = vnc_display;
3018 
3019     if (!vs) {
3020         return -EINVAL;
3021     }
3022     if (vs->auth == VNC_AUTH_NONE) {
3023         error_printf_unless_qmp("If you want use passwords please enable "
3024                                 "password auth using '-vnc ${dpy},password'.");
3025         return -EINVAL;
3026     }
3027 
3028     g_free(vs->password);
3029     vs->password = g_strdup(password);
3030 
3031     return 0;
3032 }
3033 
3034 int vnc_display_pw_expire(DisplayState *ds, time_t expires)
3035 {
3036     VncDisplay *vs = vnc_display;
3037 
3038     if (!vs) {
3039         return -EINVAL;
3040     }
3041 
3042     vs->expires = expires;
3043     return 0;
3044 }
3045 
3046 char *vnc_display_local_addr(DisplayState *ds)
3047 {
3048     VncDisplay *vs = vnc_display;
3049 
3050     return vnc_socket_local_addr("%s:%s", vs->lsock);
3051 }
3052 
3053 void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
3054 {
3055     VncDisplay *vs = vnc_display;
3056     const char *options;
3057     int password = 0;
3058     int reverse = 0;
3059 #ifdef CONFIG_VNC_TLS
3060     int tls = 0, x509 = 0;
3061 #endif
3062 #ifdef CONFIG_VNC_SASL
3063     int sasl = 0;
3064     int saslErr;
3065 #endif
3066 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3067     int acl = 0;
3068 #endif
3069     int lock_key_sync = 1;
3070 
3071     if (!vnc_display) {
3072         error_setg(errp, "VNC display not active");
3073         return;
3074     }
3075     vnc_display_close(ds);
3076     if (strcmp(display, "none") == 0)
3077         return;
3078 
3079     vs->display = g_strdup(display);
3080     vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3081 
3082     options = display;
3083     while ((options = strchr(options, ','))) {
3084         options++;
3085         if (strncmp(options, "password", 8) == 0) {
3086             if (fips_get_state()) {
3087                 error_setg(errp,
3088                            "VNC password auth disabled due to FIPS mode, "
3089                            "consider using the VeNCrypt or SASL authentication "
3090                            "methods as an alternative");
3091                 goto fail;
3092             }
3093             password = 1; /* Require password auth */
3094         } else if (strncmp(options, "reverse", 7) == 0) {
3095             reverse = 1;
3096         } else if (strncmp(options, "no-lock-key-sync", 16) == 0) {
3097             lock_key_sync = 0;
3098 #ifdef CONFIG_VNC_SASL
3099         } else if (strncmp(options, "sasl", 4) == 0) {
3100             sasl = 1; /* Require SASL auth */
3101 #endif
3102 #ifdef CONFIG_VNC_WS
3103         } else if (strncmp(options, "websocket", 9) == 0) {
3104             char *start, *end;
3105             vs->websocket = 1;
3106 
3107             /* Check for 'websocket=<port>' */
3108             start = strchr(options, '=');
3109             end = strchr(options, ',');
3110             if (start && (!end || (start < end))) {
3111                 int len = end ? end-(start+1) : strlen(start+1);
3112                 if (len < 6) {
3113                     /* extract the host specification from display */
3114                     char  *host = NULL, *port = NULL, *host_end = NULL;
3115                     port = g_strndup(start + 1, len);
3116 
3117                     /* ipv6 hosts have colons */
3118                     end = strchr(display, ',');
3119                     host_end = g_strrstr_len(display, end - display, ":");
3120 
3121                     if (host_end) {
3122                         host = g_strndup(display, host_end - display + 1);
3123                     } else {
3124                         host = g_strndup(":", 1);
3125                     }
3126                     vs->ws_display = g_strconcat(host, port, NULL);
3127                     g_free(host);
3128                     g_free(port);
3129                 }
3130             }
3131 #endif /* CONFIG_VNC_WS */
3132 #ifdef CONFIG_VNC_TLS
3133         } else if (strncmp(options, "tls", 3) == 0) {
3134             tls = 1; /* Require TLS */
3135         } else if (strncmp(options, "x509", 4) == 0) {
3136             char *start, *end;
3137             x509 = 1; /* Require x509 certificates */
3138             if (strncmp(options, "x509verify", 10) == 0)
3139                 vs->tls.x509verify = 1; /* ...and verify client certs */
3140 
3141             /* Now check for 'x509=/some/path' postfix
3142              * and use that to setup x509 certificate/key paths */
3143             start = strchr(options, '=');
3144             end = strchr(options, ',');
3145             if (start && (!end || (start < end))) {
3146                 int len = end ? end-(start+1) : strlen(start+1);
3147                 char *path = g_strndup(start + 1, len);
3148 
3149                 VNC_DEBUG("Trying certificate path '%s'\n", path);
3150                 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
3151                     error_setg(errp, "Failed to find x509 certificates/keys in %s", path);
3152                     g_free(path);
3153                     goto fail;
3154                 }
3155                 g_free(path);
3156             } else {
3157                 error_setg(errp, "No certificate path provided");
3158                 goto fail;
3159             }
3160 #endif
3161 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3162         } else if (strncmp(options, "acl", 3) == 0) {
3163             acl = 1;
3164 #endif
3165         } else if (strncmp(options, "lossy", 5) == 0) {
3166 #ifdef CONFIG_VNC_JPEG
3167             vs->lossy = true;
3168 #endif
3169         } else if (strncmp(options, "non-adaptive", 12) == 0) {
3170             vs->non_adaptive = true;
3171         } else if (strncmp(options, "share=", 6) == 0) {
3172             if (strncmp(options+6, "ignore", 6) == 0) {
3173                 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
3174             } else if (strncmp(options+6, "allow-exclusive", 15) == 0) {
3175                 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3176             } else if (strncmp(options+6, "force-shared", 12) == 0) {
3177                 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3178             } else {
3179                 error_setg(errp, "unknown vnc share= option");
3180                 goto fail;
3181             }
3182         }
3183     }
3184 
3185     /* adaptive updates are only used with tight encoding and
3186      * if lossy updates are enabled so we can disable all the
3187      * calculations otherwise */
3188     if (!vs->lossy) {
3189         vs->non_adaptive = true;
3190     }
3191 
3192 #ifdef CONFIG_VNC_TLS
3193     if (acl && x509 && vs->tls.x509verify) {
3194         if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
3195             fprintf(stderr, "Failed to create x509 dname ACL\n");
3196             exit(1);
3197         }
3198     }
3199 #endif
3200 #ifdef CONFIG_VNC_SASL
3201     if (acl && sasl) {
3202         if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
3203             fprintf(stderr, "Failed to create username ACL\n");
3204             exit(1);
3205         }
3206     }
3207 #endif
3208 
3209     /*
3210      * Combinations we support here:
3211      *
3212      *  - no-auth                (clear text, no auth)
3213      *  - password               (clear text, weak auth)
3214      *  - sasl                   (encrypt, good auth *IF* using Kerberos via GSSAPI)
3215      *  - tls                    (encrypt, weak anonymous creds, no auth)
3216      *  - tls + password         (encrypt, weak anonymous creds, weak auth)
3217      *  - tls + sasl             (encrypt, weak anonymous creds, good auth)
3218      *  - tls + x509             (encrypt, good x509 creds, no auth)
3219      *  - tls + x509 + password  (encrypt, good x509 creds, weak auth)
3220      *  - tls + x509 + sasl      (encrypt, good x509 creds, good auth)
3221      *
3222      * NB1. TLS is a stackable auth scheme.
3223      * NB2. the x509 schemes have option to validate a client cert dname
3224      */
3225     if (password) {
3226 #ifdef CONFIG_VNC_TLS
3227         if (tls) {
3228             vs->auth = VNC_AUTH_VENCRYPT;
3229             if (x509) {
3230                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3231                 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
3232             } else {
3233                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3234                 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3235             }
3236         } else {
3237 #endif /* CONFIG_VNC_TLS */
3238             VNC_DEBUG("Initializing VNC server with password auth\n");
3239             vs->auth = VNC_AUTH_VNC;
3240 #ifdef CONFIG_VNC_TLS
3241             vs->subauth = VNC_AUTH_INVALID;
3242         }
3243 #endif /* CONFIG_VNC_TLS */
3244 #ifdef CONFIG_VNC_SASL
3245     } else if (sasl) {
3246 #ifdef CONFIG_VNC_TLS
3247         if (tls) {
3248             vs->auth = VNC_AUTH_VENCRYPT;
3249             if (x509) {
3250                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3251                 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3252             } else {
3253                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3254                 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3255             }
3256         } else {
3257 #endif /* CONFIG_VNC_TLS */
3258             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3259             vs->auth = VNC_AUTH_SASL;
3260 #ifdef CONFIG_VNC_TLS
3261             vs->subauth = VNC_AUTH_INVALID;
3262         }
3263 #endif /* CONFIG_VNC_TLS */
3264 #endif /* CONFIG_VNC_SASL */
3265     } else {
3266 #ifdef CONFIG_VNC_TLS
3267         if (tls) {
3268             vs->auth = VNC_AUTH_VENCRYPT;
3269             if (x509) {
3270                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3271                 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3272             } else {
3273                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3274                 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3275             }
3276         } else {
3277 #endif
3278             VNC_DEBUG("Initializing VNC server with no auth\n");
3279             vs->auth = VNC_AUTH_NONE;
3280 #ifdef CONFIG_VNC_TLS
3281             vs->subauth = VNC_AUTH_INVALID;
3282         }
3283 #endif
3284     }
3285 
3286 #ifdef CONFIG_VNC_SASL
3287     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3288         error_setg(errp, "Failed to initialize SASL auth: %s",
3289                    sasl_errstring(saslErr, NULL, NULL));
3290         goto fail;
3291     }
3292 #endif
3293     vs->lock_key_sync = lock_key_sync;
3294 
3295     if (reverse) {
3296         /* connect to viewer */
3297         int csock;
3298         vs->lsock = -1;
3299 #ifdef CONFIG_VNC_WS
3300         vs->lwebsock = -1;
3301 #endif
3302         if (strncmp(display, "unix:", 5) == 0) {
3303             csock = unix_connect(display+5, errp);
3304         } else {
3305             csock = inet_connect(display, errp);
3306         }
3307         if (csock < 0) {
3308             goto fail;
3309         }
3310         vnc_connect(vs, csock, false, false);
3311     } else {
3312         /* listen for connects */
3313         char *dpy;
3314         dpy = g_malloc(256);
3315         if (strncmp(display, "unix:", 5) == 0) {
3316             pstrcpy(dpy, 256, "unix:");
3317             vs->lsock = unix_listen(display+5, dpy+5, 256-5, errp);
3318         } else {
3319             vs->lsock = inet_listen(display, dpy, 256,
3320                                     SOCK_STREAM, 5900, errp);
3321             if (vs->lsock < 0) {
3322                 g_free(dpy);
3323                 goto fail;
3324             }
3325 #ifdef CONFIG_VNC_WS
3326             if (vs->websocket) {
3327                 if (vs->ws_display) {
3328                     vs->lwebsock = inet_listen(vs->ws_display, NULL, 256,
3329                         SOCK_STREAM, 0, errp);
3330                 } else {
3331                     vs->lwebsock = inet_listen(vs->display, NULL, 256,
3332                         SOCK_STREAM, 5700, errp);
3333                 }
3334 
3335                 if (vs->lwebsock < 0) {
3336                     if (vs->lsock) {
3337                         close(vs->lsock);
3338                         vs->lsock = -1;
3339                     }
3340                     g_free(dpy);
3341                     goto fail;
3342                 }
3343             }
3344 #endif /* CONFIG_VNC_WS */
3345         }
3346         g_free(vs->display);
3347         vs->display = dpy;
3348         qemu_set_fd_handler2(vs->lsock, NULL,
3349                 vnc_listen_regular_read, NULL, vs);
3350 #ifdef CONFIG_VNC_WS
3351         if (vs->websocket) {
3352             qemu_set_fd_handler2(vs->lwebsock, NULL,
3353                     vnc_listen_websocket_read, NULL, vs);
3354         }
3355 #endif /* CONFIG_VNC_WS */
3356     }
3357     return;
3358 
3359 fail:
3360     g_free(vs->display);
3361     vs->display = NULL;
3362 #ifdef CONFIG_VNC_WS
3363     g_free(vs->ws_display);
3364     vs->ws_display = NULL;
3365 #endif /* CONFIG_VNC_WS */
3366 }
3367 
3368 void vnc_display_add_client(DisplayState *ds, int csock, bool skipauth)
3369 {
3370     VncDisplay *vs = vnc_display;
3371 
3372     vnc_connect(vs, csock, skipauth, false);
3373 }
3374