xref: /openbmc/qemu/ui/vnc.c (revision a9dd38db)
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     if (vs->need_update && vs->csock != -1) {
891         VncDisplay *vd = vs->vd;
892         VncJob *job;
893         int y;
894         int height, width;
895         int n = 0;
896 
897         if (vs->output.offset && !vs->audio_cap && !vs->force_update)
898             /* kernel send buffers are full -> drop frames to throttle */
899             return 0;
900 
901         if (!has_dirty && !vs->audio_cap && !vs->force_update)
902             return 0;
903 
904         /*
905          * Send screen updates to the vnc client using the server
906          * surface and server dirty map.  guest surface updates
907          * happening in parallel don't disturb us, the next pass will
908          * send them to the client.
909          */
910         job = vnc_job_new(vs);
911 
912         height = pixman_image_get_height(vd->server);
913         width = pixman_image_get_width(vd->server);
914 
915         y = 0;
916         for (;;) {
917             int x, h;
918             unsigned long x2;
919             unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
920                                                  height * VNC_DIRTY_BPL(vs),
921                                                  y * VNC_DIRTY_BPL(vs));
922             if (offset == height * VNC_DIRTY_BPL(vs)) {
923                 /* no more dirty bits */
924                 break;
925             }
926             y = offset / VNC_DIRTY_BPL(vs);
927             x = offset % VNC_DIRTY_BPL(vs);
928             x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
929                                     VNC_DIRTY_BPL(vs), x);
930             bitmap_clear(vs->dirty[y], x, x2 - x);
931             h = find_and_clear_dirty_height(vs, y, x, x2, height);
932             x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
933             if (x2 > x) {
934                 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
935                                       (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
936             }
937         }
938 
939         vnc_job_push(job);
940         if (sync) {
941             vnc_jobs_join(vs);
942         }
943         vs->force_update = 0;
944         return n;
945     }
946 
947     if (vs->csock == -1) {
948         vnc_disconnect_finish(vs);
949     } else if (sync) {
950         vnc_jobs_join(vs);
951     }
952 
953     return 0;
954 }
955 
956 /* audio */
957 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
958 {
959     VncState *vs = opaque;
960 
961     switch (cmd) {
962     case AUD_CNOTIFY_DISABLE:
963         vnc_lock_output(vs);
964         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
965         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
966         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
967         vnc_unlock_output(vs);
968         vnc_flush(vs);
969         break;
970 
971     case AUD_CNOTIFY_ENABLE:
972         vnc_lock_output(vs);
973         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
974         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
975         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
976         vnc_unlock_output(vs);
977         vnc_flush(vs);
978         break;
979     }
980 }
981 
982 static void audio_capture_destroy(void *opaque)
983 {
984 }
985 
986 static void audio_capture(void *opaque, void *buf, int size)
987 {
988     VncState *vs = opaque;
989 
990     vnc_lock_output(vs);
991     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
992     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
993     vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
994     vnc_write_u32(vs, size);
995     vnc_write(vs, buf, size);
996     vnc_unlock_output(vs);
997     vnc_flush(vs);
998 }
999 
1000 static void audio_add(VncState *vs)
1001 {
1002     struct audio_capture_ops ops;
1003 
1004     if (vs->audio_cap) {
1005         error_report("audio already running");
1006         return;
1007     }
1008 
1009     ops.notify = audio_capture_notify;
1010     ops.destroy = audio_capture_destroy;
1011     ops.capture = audio_capture;
1012 
1013     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1014     if (!vs->audio_cap) {
1015         error_report("Failed to add audio capture");
1016     }
1017 }
1018 
1019 static void audio_del(VncState *vs)
1020 {
1021     if (vs->audio_cap) {
1022         AUD_del_capture(vs->audio_cap, vs);
1023         vs->audio_cap = NULL;
1024     }
1025 }
1026 
1027 static void vnc_disconnect_start(VncState *vs)
1028 {
1029     if (vs->csock == -1)
1030         return;
1031     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1032     qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1033     closesocket(vs->csock);
1034     vs->csock = -1;
1035 }
1036 
1037 void vnc_disconnect_finish(VncState *vs)
1038 {
1039     int i;
1040 
1041     vnc_jobs_join(vs); /* Wait encoding jobs */
1042 
1043     vnc_lock_output(vs);
1044     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1045 
1046     buffer_free(&vs->input);
1047     buffer_free(&vs->output);
1048 #ifdef CONFIG_VNC_WS
1049     buffer_free(&vs->ws_input);
1050     buffer_free(&vs->ws_output);
1051 #endif /* CONFIG_VNC_WS */
1052 
1053     qapi_free_VncClientInfo(vs->info);
1054 
1055     vnc_zlib_clear(vs);
1056     vnc_tight_clear(vs);
1057     vnc_zrle_clear(vs);
1058 
1059 #ifdef CONFIG_VNC_TLS
1060     vnc_tls_client_cleanup(vs);
1061 #endif /* CONFIG_VNC_TLS */
1062 #ifdef CONFIG_VNC_SASL
1063     vnc_sasl_client_cleanup(vs);
1064 #endif /* CONFIG_VNC_SASL */
1065     audio_del(vs);
1066     vnc_release_modifiers(vs);
1067 
1068     if (vs->initialized) {
1069         QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1070         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1071     }
1072 
1073     if (vs->vd->lock_key_sync)
1074         qemu_remove_led_event_handler(vs->led);
1075     vnc_unlock_output(vs);
1076 
1077     qemu_mutex_destroy(&vs->output_mutex);
1078     if (vs->bh != NULL) {
1079         qemu_bh_delete(vs->bh);
1080     }
1081     buffer_free(&vs->jobs_buffer);
1082 
1083     for (i = 0; i < VNC_STAT_ROWS; ++i) {
1084         g_free(vs->lossy_rect[i]);
1085     }
1086     g_free(vs->lossy_rect);
1087     g_free(vs);
1088 }
1089 
1090 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1091 {
1092     if (ret == 0 || ret == -1) {
1093         if (ret == -1) {
1094             switch (last_errno) {
1095                 case EINTR:
1096                 case EAGAIN:
1097 #ifdef _WIN32
1098                 case WSAEWOULDBLOCK:
1099 #endif
1100                     return 0;
1101                 default:
1102                     break;
1103             }
1104         }
1105 
1106         VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1107                   ret, ret < 0 ? last_errno : 0);
1108         vnc_disconnect_start(vs);
1109 
1110         return 0;
1111     }
1112     return ret;
1113 }
1114 
1115 
1116 void vnc_client_error(VncState *vs)
1117 {
1118     VNC_DEBUG("Closing down client sock: protocol error\n");
1119     vnc_disconnect_start(vs);
1120 }
1121 
1122 #ifdef CONFIG_VNC_TLS
1123 static long vnc_client_write_tls(gnutls_session_t *session,
1124                                  const uint8_t *data,
1125                                  size_t datalen)
1126 {
1127     long ret = gnutls_write(*session, data, datalen);
1128     if (ret < 0) {
1129         if (ret == GNUTLS_E_AGAIN) {
1130             errno = EAGAIN;
1131         } else {
1132             errno = EIO;
1133         }
1134         ret = -1;
1135     }
1136     return ret;
1137 }
1138 #endif /* CONFIG_VNC_TLS */
1139 
1140 /*
1141  * Called to write a chunk of data to the client socket. The data may
1142  * be the raw data, or may have already been encoded by SASL.
1143  * The data will be written either straight onto the socket, or
1144  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1145  *
1146  * NB, it is theoretically possible to have 2 layers of encryption,
1147  * both SASL, and this TLS layer. It is highly unlikely in practice
1148  * though, since SASL encryption will typically be a no-op if TLS
1149  * is active
1150  *
1151  * Returns the number of bytes written, which may be less than
1152  * the requested 'datalen' if the socket would block. Returns
1153  * -1 on error, and disconnects the client socket.
1154  */
1155 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1156 {
1157     long ret;
1158 #ifdef CONFIG_VNC_TLS
1159     if (vs->tls.session) {
1160         ret = vnc_client_write_tls(&vs->tls.session, data, datalen);
1161     } else {
1162 #ifdef CONFIG_VNC_WS
1163         if (vs->ws_tls.session) {
1164             ret = vnc_client_write_tls(&vs->ws_tls.session, data, datalen);
1165         } else
1166 #endif /* CONFIG_VNC_WS */
1167 #endif /* CONFIG_VNC_TLS */
1168         {
1169             ret = send(vs->csock, (const void *)data, datalen, 0);
1170         }
1171 #ifdef CONFIG_VNC_TLS
1172     }
1173 #endif /* CONFIG_VNC_TLS */
1174     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1175     return vnc_client_io_error(vs, ret, socket_error());
1176 }
1177 
1178 
1179 /*
1180  * Called to write buffered data to the client socket, when not
1181  * using any SASL SSF encryption layers. Will write as much data
1182  * as possible without blocking. If all buffered data is written,
1183  * will switch the FD poll() handler back to read monitoring.
1184  *
1185  * Returns the number of bytes written, which may be less than
1186  * the buffered output data if the socket would block. Returns
1187  * -1 on error, and disconnects the client socket.
1188  */
1189 static long vnc_client_write_plain(VncState *vs)
1190 {
1191     long ret;
1192 
1193 #ifdef CONFIG_VNC_SASL
1194     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1195               vs->output.buffer, vs->output.capacity, vs->output.offset,
1196               vs->sasl.waitWriteSSF);
1197 
1198     if (vs->sasl.conn &&
1199         vs->sasl.runSSF &&
1200         vs->sasl.waitWriteSSF) {
1201         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1202         if (ret)
1203             vs->sasl.waitWriteSSF -= ret;
1204     } else
1205 #endif /* CONFIG_VNC_SASL */
1206         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1207     if (!ret)
1208         return 0;
1209 
1210     buffer_advance(&vs->output, ret);
1211 
1212     if (vs->output.offset == 0) {
1213         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1214     }
1215 
1216     return ret;
1217 }
1218 
1219 
1220 /*
1221  * First function called whenever there is data to be written to
1222  * the client socket. Will delegate actual work according to whether
1223  * SASL SSF layers are enabled (thus requiring encryption calls)
1224  */
1225 static void vnc_client_write_locked(void *opaque)
1226 {
1227     VncState *vs = opaque;
1228 
1229 #ifdef CONFIG_VNC_SASL
1230     if (vs->sasl.conn &&
1231         vs->sasl.runSSF &&
1232         !vs->sasl.waitWriteSSF) {
1233         vnc_client_write_sasl(vs);
1234     } else
1235 #endif /* CONFIG_VNC_SASL */
1236     {
1237 #ifdef CONFIG_VNC_WS
1238         if (vs->encode_ws) {
1239             vnc_client_write_ws(vs);
1240         } else
1241 #endif /* CONFIG_VNC_WS */
1242         {
1243             vnc_client_write_plain(vs);
1244         }
1245     }
1246 }
1247 
1248 void vnc_client_write(void *opaque)
1249 {
1250     VncState *vs = opaque;
1251 
1252     vnc_lock_output(vs);
1253     if (vs->output.offset
1254 #ifdef CONFIG_VNC_WS
1255             || vs->ws_output.offset
1256 #endif
1257             ) {
1258         vnc_client_write_locked(opaque);
1259     } else if (vs->csock != -1) {
1260         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1261     }
1262     vnc_unlock_output(vs);
1263 }
1264 
1265 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1266 {
1267     vs->read_handler = func;
1268     vs->read_handler_expect = expecting;
1269 }
1270 
1271 #ifdef CONFIG_VNC_TLS
1272 static long vnc_client_read_tls(gnutls_session_t *session, uint8_t *data,
1273                                 size_t datalen)
1274 {
1275     long ret = gnutls_read(*session, data, datalen);
1276     if (ret < 0) {
1277         if (ret == GNUTLS_E_AGAIN) {
1278             errno = EAGAIN;
1279         } else {
1280             errno = EIO;
1281         }
1282         ret = -1;
1283     }
1284     return ret;
1285 }
1286 #endif /* CONFIG_VNC_TLS */
1287 
1288 /*
1289  * Called to read a chunk of data from the client socket. The data may
1290  * be the raw data, or may need to be further decoded by SASL.
1291  * The data will be read either straight from to the socket, or
1292  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1293  *
1294  * NB, it is theoretically possible to have 2 layers of encryption,
1295  * both SASL, and this TLS layer. It is highly unlikely in practice
1296  * though, since SASL encryption will typically be a no-op if TLS
1297  * is active
1298  *
1299  * Returns the number of bytes read, which may be less than
1300  * the requested 'datalen' if the socket would block. Returns
1301  * -1 on error, and disconnects the client socket.
1302  */
1303 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1304 {
1305     long ret;
1306 #ifdef CONFIG_VNC_TLS
1307     if (vs->tls.session) {
1308         ret = vnc_client_read_tls(&vs->tls.session, data, datalen);
1309     } else {
1310 #ifdef CONFIG_VNC_WS
1311         if (vs->ws_tls.session) {
1312             ret = vnc_client_read_tls(&vs->ws_tls.session, data, datalen);
1313         } else
1314 #endif /* CONFIG_VNC_WS */
1315 #endif /* CONFIG_VNC_TLS */
1316         {
1317             ret = qemu_recv(vs->csock, data, datalen, 0);
1318         }
1319 #ifdef CONFIG_VNC_TLS
1320     }
1321 #endif /* CONFIG_VNC_TLS */
1322     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1323     return vnc_client_io_error(vs, ret, socket_error());
1324 }
1325 
1326 
1327 /*
1328  * Called to read data from the client socket to the input buffer,
1329  * when not using any SASL SSF encryption layers. Will read as much
1330  * data as possible without blocking.
1331  *
1332  * Returns the number of bytes read. Returns -1 on error, and
1333  * disconnects the client socket.
1334  */
1335 static long vnc_client_read_plain(VncState *vs)
1336 {
1337     int ret;
1338     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1339               vs->input.buffer, vs->input.capacity, vs->input.offset);
1340     buffer_reserve(&vs->input, 4096);
1341     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1342     if (!ret)
1343         return 0;
1344     vs->input.offset += ret;
1345     return ret;
1346 }
1347 
1348 static void vnc_jobs_bh(void *opaque)
1349 {
1350     VncState *vs = opaque;
1351 
1352     vnc_jobs_consume_buffer(vs);
1353 }
1354 
1355 /*
1356  * First function called whenever there is more data to be read from
1357  * the client socket. Will delegate actual work according to whether
1358  * SASL SSF layers are enabled (thus requiring decryption calls)
1359  */
1360 void vnc_client_read(void *opaque)
1361 {
1362     VncState *vs = opaque;
1363     long ret;
1364 
1365 #ifdef CONFIG_VNC_SASL
1366     if (vs->sasl.conn && vs->sasl.runSSF)
1367         ret = vnc_client_read_sasl(vs);
1368     else
1369 #endif /* CONFIG_VNC_SASL */
1370 #ifdef CONFIG_VNC_WS
1371         if (vs->encode_ws) {
1372             ret = vnc_client_read_ws(vs);
1373             if (ret == -1) {
1374                 vnc_disconnect_start(vs);
1375                 return;
1376             } else if (ret == -2) {
1377                 vnc_client_error(vs);
1378                 return;
1379             }
1380         } else
1381 #endif /* CONFIG_VNC_WS */
1382         {
1383         ret = vnc_client_read_plain(vs);
1384         }
1385     if (!ret) {
1386         if (vs->csock == -1)
1387             vnc_disconnect_finish(vs);
1388         return;
1389     }
1390 
1391     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1392         size_t len = vs->read_handler_expect;
1393         int ret;
1394 
1395         ret = vs->read_handler(vs, vs->input.buffer, len);
1396         if (vs->csock == -1) {
1397             vnc_disconnect_finish(vs);
1398             return;
1399         }
1400 
1401         if (!ret) {
1402             buffer_advance(&vs->input, len);
1403         } else {
1404             vs->read_handler_expect = ret;
1405         }
1406     }
1407 }
1408 
1409 void vnc_write(VncState *vs, const void *data, size_t len)
1410 {
1411     buffer_reserve(&vs->output, len);
1412 
1413     if (vs->csock != -1 && buffer_empty(&vs->output)) {
1414         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1415     }
1416 
1417     buffer_append(&vs->output, data, len);
1418 }
1419 
1420 void vnc_write_s32(VncState *vs, int32_t value)
1421 {
1422     vnc_write_u32(vs, *(uint32_t *)&value);
1423 }
1424 
1425 void vnc_write_u32(VncState *vs, uint32_t value)
1426 {
1427     uint8_t buf[4];
1428 
1429     buf[0] = (value >> 24) & 0xFF;
1430     buf[1] = (value >> 16) & 0xFF;
1431     buf[2] = (value >>  8) & 0xFF;
1432     buf[3] = value & 0xFF;
1433 
1434     vnc_write(vs, buf, 4);
1435 }
1436 
1437 void vnc_write_u16(VncState *vs, uint16_t value)
1438 {
1439     uint8_t buf[2];
1440 
1441     buf[0] = (value >> 8) & 0xFF;
1442     buf[1] = value & 0xFF;
1443 
1444     vnc_write(vs, buf, 2);
1445 }
1446 
1447 void vnc_write_u8(VncState *vs, uint8_t value)
1448 {
1449     vnc_write(vs, (char *)&value, 1);
1450 }
1451 
1452 void vnc_flush(VncState *vs)
1453 {
1454     vnc_lock_output(vs);
1455     if (vs->csock != -1 && (vs->output.offset
1456 #ifdef CONFIG_VNC_WS
1457                 || vs->ws_output.offset
1458 #endif
1459                 )) {
1460         vnc_client_write_locked(vs);
1461     }
1462     vnc_unlock_output(vs);
1463 }
1464 
1465 static uint8_t read_u8(uint8_t *data, size_t offset)
1466 {
1467     return data[offset];
1468 }
1469 
1470 static uint16_t read_u16(uint8_t *data, size_t offset)
1471 {
1472     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1473 }
1474 
1475 static int32_t read_s32(uint8_t *data, size_t offset)
1476 {
1477     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1478                      (data[offset + 2] << 8) | data[offset + 3]);
1479 }
1480 
1481 uint32_t read_u32(uint8_t *data, size_t offset)
1482 {
1483     return ((data[offset] << 24) | (data[offset + 1] << 16) |
1484             (data[offset + 2] << 8) | data[offset + 3]);
1485 }
1486 
1487 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1488 {
1489 }
1490 
1491 static void check_pointer_type_change(Notifier *notifier, void *data)
1492 {
1493     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1494     int absolute = qemu_input_is_absolute();
1495 
1496     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1497         vnc_lock_output(vs);
1498         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1499         vnc_write_u8(vs, 0);
1500         vnc_write_u16(vs, 1);
1501         vnc_framebuffer_update(vs, absolute, 0,
1502                                pixman_image_get_width(vs->vd->server),
1503                                pixman_image_get_height(vs->vd->server),
1504                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1505         vnc_unlock_output(vs);
1506         vnc_flush(vs);
1507     }
1508     vs->absolute = absolute;
1509 }
1510 
1511 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1512 {
1513     static uint32_t bmap[INPUT_BUTTON_MAX] = {
1514         [INPUT_BUTTON_LEFT]       = 0x01,
1515         [INPUT_BUTTON_MIDDLE]     = 0x02,
1516         [INPUT_BUTTON_RIGHT]      = 0x04,
1517         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1518         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1519     };
1520     QemuConsole *con = vs->vd->dcl.con;
1521     int width = pixman_image_get_width(vs->vd->server);
1522     int height = pixman_image_get_height(vs->vd->server);
1523 
1524     if (vs->last_bmask != button_mask) {
1525         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1526         vs->last_bmask = button_mask;
1527     }
1528 
1529     if (vs->absolute) {
1530         qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
1531         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
1532     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1533         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1534         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1535     } else {
1536         if (vs->last_x != -1) {
1537             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1538             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1539         }
1540         vs->last_x = x;
1541         vs->last_y = y;
1542     }
1543     qemu_input_event_sync();
1544 }
1545 
1546 static void reset_keys(VncState *vs)
1547 {
1548     int i;
1549     for(i = 0; i < 256; i++) {
1550         if (vs->modifiers_state[i]) {
1551             qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1552             vs->modifiers_state[i] = 0;
1553         }
1554     }
1555 }
1556 
1557 static void press_key(VncState *vs, int keysym)
1558 {
1559     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1560     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1561     qemu_input_event_send_key_delay(0);
1562     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1563     qemu_input_event_send_key_delay(0);
1564 }
1565 
1566 static int current_led_state(VncState *vs)
1567 {
1568     int ledstate = 0;
1569 
1570     if (vs->modifiers_state[0x46]) {
1571         ledstate |= QEMU_SCROLL_LOCK_LED;
1572     }
1573     if (vs->modifiers_state[0x45]) {
1574         ledstate |= QEMU_NUM_LOCK_LED;
1575     }
1576     if (vs->modifiers_state[0x3a]) {
1577         ledstate |= QEMU_CAPS_LOCK_LED;
1578     }
1579 
1580     return ledstate;
1581 }
1582 
1583 static void vnc_led_state_change(VncState *vs)
1584 {
1585     int ledstate = 0;
1586 
1587     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1588         return;
1589     }
1590 
1591     ledstate = current_led_state(vs);
1592     vnc_lock_output(vs);
1593     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1594     vnc_write_u8(vs, 0);
1595     vnc_write_u16(vs, 1);
1596     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1597     vnc_write_u8(vs, ledstate);
1598     vnc_unlock_output(vs);
1599     vnc_flush(vs);
1600 }
1601 
1602 static void kbd_leds(void *opaque, int ledstate)
1603 {
1604     VncState *vs = opaque;
1605     int caps, num, scr;
1606     bool has_changed = (ledstate != current_led_state(vs));
1607 
1608     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1609                              (ledstate & QEMU_NUM_LOCK_LED),
1610                              (ledstate & QEMU_SCROLL_LOCK_LED));
1611 
1612     caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1613     num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
1614     scr  = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
1615 
1616     if (vs->modifiers_state[0x3a] != caps) {
1617         vs->modifiers_state[0x3a] = caps;
1618     }
1619     if (vs->modifiers_state[0x45] != num) {
1620         vs->modifiers_state[0x45] = num;
1621     }
1622     if (vs->modifiers_state[0x46] != scr) {
1623         vs->modifiers_state[0x46] = scr;
1624     }
1625 
1626     /* Sending the current led state message to the client */
1627     if (has_changed) {
1628         vnc_led_state_change(vs);
1629     }
1630 }
1631 
1632 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1633 {
1634     /* QEMU console switch */
1635     switch(keycode) {
1636     case 0x2a:                          /* Left Shift */
1637     case 0x36:                          /* Right Shift */
1638     case 0x1d:                          /* Left CTRL */
1639     case 0x9d:                          /* Right CTRL */
1640     case 0x38:                          /* Left ALT */
1641     case 0xb8:                          /* Right ALT */
1642         if (down)
1643             vs->modifiers_state[keycode] = 1;
1644         else
1645             vs->modifiers_state[keycode] = 0;
1646         break;
1647     case 0x02 ... 0x0a: /* '1' to '9' keys */
1648         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1649             /* Reset the modifiers sent to the current console */
1650             reset_keys(vs);
1651             console_select(keycode - 0x02);
1652             return;
1653         }
1654         break;
1655     case 0x3a:                        /* CapsLock */
1656     case 0x45:                        /* NumLock */
1657         if (down)
1658             vs->modifiers_state[keycode] ^= 1;
1659         break;
1660     }
1661 
1662     /* Turn off the lock state sync logic if the client support the led
1663        state extension.
1664     */
1665     if (down && vs->vd->lock_key_sync &&
1666         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1667         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1668         /* If the numlock state needs to change then simulate an additional
1669            keypress before sending this one.  This will happen if the user
1670            toggles numlock away from the VNC window.
1671         */
1672         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1673             if (!vs->modifiers_state[0x45]) {
1674                 trace_vnc_key_sync_numlock(true);
1675                 vs->modifiers_state[0x45] = 1;
1676                 press_key(vs, 0xff7f);
1677             }
1678         } else {
1679             if (vs->modifiers_state[0x45]) {
1680                 trace_vnc_key_sync_numlock(false);
1681                 vs->modifiers_state[0x45] = 0;
1682                 press_key(vs, 0xff7f);
1683             }
1684         }
1685     }
1686 
1687     if (down && vs->vd->lock_key_sync &&
1688         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1689         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1690         /* If the capslock state needs to change then simulate an additional
1691            keypress before sending this one.  This will happen if the user
1692            toggles capslock away from the VNC window.
1693         */
1694         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1695         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1696         int capslock = !!(vs->modifiers_state[0x3a]);
1697         if (capslock) {
1698             if (uppercase == shift) {
1699                 trace_vnc_key_sync_capslock(false);
1700                 vs->modifiers_state[0x3a] = 0;
1701                 press_key(vs, 0xffe5);
1702             }
1703         } else {
1704             if (uppercase != shift) {
1705                 trace_vnc_key_sync_capslock(true);
1706                 vs->modifiers_state[0x3a] = 1;
1707                 press_key(vs, 0xffe5);
1708             }
1709         }
1710     }
1711 
1712     if (qemu_console_is_graphic(NULL)) {
1713         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1714     } else {
1715         bool numlock = vs->modifiers_state[0x45];
1716         bool control = (vs->modifiers_state[0x1d] ||
1717                         vs->modifiers_state[0x9d]);
1718         /* QEMU console emulation */
1719         if (down) {
1720             switch (keycode) {
1721             case 0x2a:                          /* Left Shift */
1722             case 0x36:                          /* Right Shift */
1723             case 0x1d:                          /* Left CTRL */
1724             case 0x9d:                          /* Right CTRL */
1725             case 0x38:                          /* Left ALT */
1726             case 0xb8:                          /* Right ALT */
1727                 break;
1728             case 0xc8:
1729                 kbd_put_keysym(QEMU_KEY_UP);
1730                 break;
1731             case 0xd0:
1732                 kbd_put_keysym(QEMU_KEY_DOWN);
1733                 break;
1734             case 0xcb:
1735                 kbd_put_keysym(QEMU_KEY_LEFT);
1736                 break;
1737             case 0xcd:
1738                 kbd_put_keysym(QEMU_KEY_RIGHT);
1739                 break;
1740             case 0xd3:
1741                 kbd_put_keysym(QEMU_KEY_DELETE);
1742                 break;
1743             case 0xc7:
1744                 kbd_put_keysym(QEMU_KEY_HOME);
1745                 break;
1746             case 0xcf:
1747                 kbd_put_keysym(QEMU_KEY_END);
1748                 break;
1749             case 0xc9:
1750                 kbd_put_keysym(QEMU_KEY_PAGEUP);
1751                 break;
1752             case 0xd1:
1753                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1754                 break;
1755 
1756             case 0x47:
1757                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1758                 break;
1759             case 0x48:
1760                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1761                 break;
1762             case 0x49:
1763                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1764                 break;
1765             case 0x4b:
1766                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1767                 break;
1768             case 0x4c:
1769                 kbd_put_keysym('5');
1770                 break;
1771             case 0x4d:
1772                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1773                 break;
1774             case 0x4f:
1775                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1776                 break;
1777             case 0x50:
1778                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1779                 break;
1780             case 0x51:
1781                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1782                 break;
1783             case 0x52:
1784                 kbd_put_keysym('0');
1785                 break;
1786             case 0x53:
1787                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1788                 break;
1789 
1790             case 0xb5:
1791                 kbd_put_keysym('/');
1792                 break;
1793             case 0x37:
1794                 kbd_put_keysym('*');
1795                 break;
1796             case 0x4a:
1797                 kbd_put_keysym('-');
1798                 break;
1799             case 0x4e:
1800                 kbd_put_keysym('+');
1801                 break;
1802             case 0x9c:
1803                 kbd_put_keysym('\n');
1804                 break;
1805 
1806             default:
1807                 if (control) {
1808                     kbd_put_keysym(sym & 0x1f);
1809                 } else {
1810                     kbd_put_keysym(sym);
1811                 }
1812                 break;
1813             }
1814         }
1815     }
1816 }
1817 
1818 static void vnc_release_modifiers(VncState *vs)
1819 {
1820     static const int keycodes[] = {
1821         /* shift, control, alt keys, both left & right */
1822         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1823     };
1824     int i, keycode;
1825 
1826     if (!qemu_console_is_graphic(NULL)) {
1827         return;
1828     }
1829     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1830         keycode = keycodes[i];
1831         if (!vs->modifiers_state[keycode]) {
1832             continue;
1833         }
1834         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1835     }
1836 }
1837 
1838 static const char *code2name(int keycode)
1839 {
1840     return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
1841 }
1842 
1843 static void key_event(VncState *vs, int down, uint32_t sym)
1844 {
1845     int keycode;
1846     int lsym = sym;
1847 
1848     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1849         lsym = lsym - 'A' + 'a';
1850     }
1851 
1852     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1853     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1854     do_key_event(vs, down, keycode, sym);
1855 }
1856 
1857 static void ext_key_event(VncState *vs, int down,
1858                           uint32_t sym, uint16_t keycode)
1859 {
1860     /* if the user specifies a keyboard layout, always use it */
1861     if (keyboard_layout) {
1862         key_event(vs, down, sym);
1863     } else {
1864         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
1865         do_key_event(vs, down, keycode, sym);
1866     }
1867 }
1868 
1869 static void framebuffer_update_request(VncState *vs, int incremental,
1870                                        int x, int y, int w, int h)
1871 {
1872     int width = pixman_image_get_width(vs->vd->server);
1873     int height = pixman_image_get_height(vs->vd->server);
1874 
1875     vs->need_update = 1;
1876 
1877     if (incremental) {
1878         return;
1879     }
1880 
1881     vnc_set_area_dirty(vs->dirty, width, height, x, y, w, h);
1882 }
1883 
1884 static void send_ext_key_event_ack(VncState *vs)
1885 {
1886     vnc_lock_output(vs);
1887     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1888     vnc_write_u8(vs, 0);
1889     vnc_write_u16(vs, 1);
1890     vnc_framebuffer_update(vs, 0, 0,
1891                            pixman_image_get_width(vs->vd->server),
1892                            pixman_image_get_height(vs->vd->server),
1893                            VNC_ENCODING_EXT_KEY_EVENT);
1894     vnc_unlock_output(vs);
1895     vnc_flush(vs);
1896 }
1897 
1898 static void send_ext_audio_ack(VncState *vs)
1899 {
1900     vnc_lock_output(vs);
1901     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1902     vnc_write_u8(vs, 0);
1903     vnc_write_u16(vs, 1);
1904     vnc_framebuffer_update(vs, 0, 0,
1905                            pixman_image_get_width(vs->vd->server),
1906                            pixman_image_get_height(vs->vd->server),
1907                            VNC_ENCODING_AUDIO);
1908     vnc_unlock_output(vs);
1909     vnc_flush(vs);
1910 }
1911 
1912 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1913 {
1914     int i;
1915     unsigned int enc = 0;
1916 
1917     vs->features = 0;
1918     vs->vnc_encoding = 0;
1919     vs->tight.compression = 9;
1920     vs->tight.quality = -1; /* Lossless by default */
1921     vs->absolute = -1;
1922 
1923     /*
1924      * Start from the end because the encodings are sent in order of preference.
1925      * This way the preferred encoding (first encoding defined in the array)
1926      * will be set at the end of the loop.
1927      */
1928     for (i = n_encodings - 1; i >= 0; i--) {
1929         enc = encodings[i];
1930         switch (enc) {
1931         case VNC_ENCODING_RAW:
1932             vs->vnc_encoding = enc;
1933             break;
1934         case VNC_ENCODING_COPYRECT:
1935             vs->features |= VNC_FEATURE_COPYRECT_MASK;
1936             break;
1937         case VNC_ENCODING_HEXTILE:
1938             vs->features |= VNC_FEATURE_HEXTILE_MASK;
1939             vs->vnc_encoding = enc;
1940             break;
1941         case VNC_ENCODING_TIGHT:
1942             vs->features |= VNC_FEATURE_TIGHT_MASK;
1943             vs->vnc_encoding = enc;
1944             break;
1945 #ifdef CONFIG_VNC_PNG
1946         case VNC_ENCODING_TIGHT_PNG:
1947             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
1948             vs->vnc_encoding = enc;
1949             break;
1950 #endif
1951         case VNC_ENCODING_ZLIB:
1952             vs->features |= VNC_FEATURE_ZLIB_MASK;
1953             vs->vnc_encoding = enc;
1954             break;
1955         case VNC_ENCODING_ZRLE:
1956             vs->features |= VNC_FEATURE_ZRLE_MASK;
1957             vs->vnc_encoding = enc;
1958             break;
1959         case VNC_ENCODING_ZYWRLE:
1960             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
1961             vs->vnc_encoding = enc;
1962             break;
1963         case VNC_ENCODING_DESKTOPRESIZE:
1964             vs->features |= VNC_FEATURE_RESIZE_MASK;
1965             break;
1966         case VNC_ENCODING_POINTER_TYPE_CHANGE:
1967             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1968             break;
1969         case VNC_ENCODING_RICH_CURSOR:
1970             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1971             break;
1972         case VNC_ENCODING_EXT_KEY_EVENT:
1973             send_ext_key_event_ack(vs);
1974             break;
1975         case VNC_ENCODING_AUDIO:
1976             send_ext_audio_ack(vs);
1977             break;
1978         case VNC_ENCODING_WMVi:
1979             vs->features |= VNC_FEATURE_WMVI_MASK;
1980             break;
1981         case VNC_ENCODING_LED_STATE:
1982             vs->features |= VNC_FEATURE_LED_STATE_MASK;
1983             break;
1984         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1985             vs->tight.compression = (enc & 0x0F);
1986             break;
1987         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1988             if (vs->vd->lossy) {
1989                 vs->tight.quality = (enc & 0x0F);
1990             }
1991             break;
1992         default:
1993             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1994             break;
1995         }
1996     }
1997     vnc_desktop_resize(vs);
1998     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
1999     vnc_led_state_change(vs);
2000 }
2001 
2002 static void set_pixel_conversion(VncState *vs)
2003 {
2004     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2005 
2006     if (fmt == VNC_SERVER_FB_FORMAT) {
2007         vs->write_pixels = vnc_write_pixels_copy;
2008         vnc_hextile_set_pixel_conversion(vs, 0);
2009     } else {
2010         vs->write_pixels = vnc_write_pixels_generic;
2011         vnc_hextile_set_pixel_conversion(vs, 1);
2012     }
2013 }
2014 
2015 static void set_pixel_format(VncState *vs,
2016                              int bits_per_pixel, int depth,
2017                              int big_endian_flag, int true_color_flag,
2018                              int red_max, int green_max, int blue_max,
2019                              int red_shift, int green_shift, int blue_shift)
2020 {
2021     if (!true_color_flag) {
2022         vnc_client_error(vs);
2023         return;
2024     }
2025 
2026     vs->client_pf.rmax = red_max;
2027     vs->client_pf.rbits = hweight_long(red_max);
2028     vs->client_pf.rshift = red_shift;
2029     vs->client_pf.rmask = red_max << red_shift;
2030     vs->client_pf.gmax = green_max;
2031     vs->client_pf.gbits = hweight_long(green_max);
2032     vs->client_pf.gshift = green_shift;
2033     vs->client_pf.gmask = green_max << green_shift;
2034     vs->client_pf.bmax = blue_max;
2035     vs->client_pf.bbits = hweight_long(blue_max);
2036     vs->client_pf.bshift = blue_shift;
2037     vs->client_pf.bmask = blue_max << blue_shift;
2038     vs->client_pf.bits_per_pixel = bits_per_pixel;
2039     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2040     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2041     vs->client_be = big_endian_flag;
2042 
2043     set_pixel_conversion(vs);
2044 
2045     graphic_hw_invalidate(NULL);
2046     graphic_hw_update(NULL);
2047 }
2048 
2049 static void pixel_format_message (VncState *vs) {
2050     char pad[3] = { 0, 0, 0 };
2051 
2052     vs->client_pf = qemu_default_pixelformat(32);
2053 
2054     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2055     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2056 
2057 #ifdef HOST_WORDS_BIGENDIAN
2058     vnc_write_u8(vs, 1);             /* big-endian-flag */
2059 #else
2060     vnc_write_u8(vs, 0);             /* big-endian-flag */
2061 #endif
2062     vnc_write_u8(vs, 1);             /* true-color-flag */
2063     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
2064     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
2065     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
2066     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
2067     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
2068     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
2069     vnc_write(vs, pad, 3);           /* padding */
2070 
2071     vnc_hextile_set_pixel_conversion(vs, 0);
2072     vs->write_pixels = vnc_write_pixels_copy;
2073 }
2074 
2075 static void vnc_colordepth(VncState *vs)
2076 {
2077     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2078         /* Sending a WMVi message to notify the client*/
2079         vnc_lock_output(vs);
2080         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2081         vnc_write_u8(vs, 0);
2082         vnc_write_u16(vs, 1); /* number of rects */
2083         vnc_framebuffer_update(vs, 0, 0,
2084                                pixman_image_get_width(vs->vd->server),
2085                                pixman_image_get_height(vs->vd->server),
2086                                VNC_ENCODING_WMVi);
2087         pixel_format_message(vs);
2088         vnc_unlock_output(vs);
2089         vnc_flush(vs);
2090     } else {
2091         set_pixel_conversion(vs);
2092     }
2093 }
2094 
2095 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2096 {
2097     int i;
2098     uint16_t limit;
2099     VncDisplay *vd = vs->vd;
2100 
2101     if (data[0] > 3) {
2102         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2103     }
2104 
2105     switch (data[0]) {
2106     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2107         if (len == 1)
2108             return 20;
2109 
2110         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
2111                          read_u8(data, 6), read_u8(data, 7),
2112                          read_u16(data, 8), read_u16(data, 10),
2113                          read_u16(data, 12), read_u8(data, 14),
2114                          read_u8(data, 15), read_u8(data, 16));
2115         break;
2116     case VNC_MSG_CLIENT_SET_ENCODINGS:
2117         if (len == 1)
2118             return 4;
2119 
2120         if (len == 4) {
2121             limit = read_u16(data, 2);
2122             if (limit > 0)
2123                 return 4 + (limit * 4);
2124         } else
2125             limit = read_u16(data, 2);
2126 
2127         for (i = 0; i < limit; i++) {
2128             int32_t val = read_s32(data, 4 + (i * 4));
2129             memcpy(data + 4 + (i * 4), &val, sizeof(val));
2130         }
2131 
2132         set_encodings(vs, (int32_t *)(data + 4), limit);
2133         break;
2134     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2135         if (len == 1)
2136             return 10;
2137 
2138         framebuffer_update_request(vs,
2139                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2140                                    read_u16(data, 6), read_u16(data, 8));
2141         break;
2142     case VNC_MSG_CLIENT_KEY_EVENT:
2143         if (len == 1)
2144             return 8;
2145 
2146         key_event(vs, read_u8(data, 1), read_u32(data, 4));
2147         break;
2148     case VNC_MSG_CLIENT_POINTER_EVENT:
2149         if (len == 1)
2150             return 6;
2151 
2152         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2153         break;
2154     case VNC_MSG_CLIENT_CUT_TEXT:
2155         if (len == 1) {
2156             return 8;
2157         }
2158         if (len == 8) {
2159             uint32_t dlen = read_u32(data, 4);
2160             if (dlen > (1 << 20)) {
2161                 error_report("vnc: client_cut_text msg payload has %u bytes"
2162                              " which exceeds our limit of 1MB.", dlen);
2163                 vnc_client_error(vs);
2164                 break;
2165             }
2166             if (dlen > 0) {
2167                 return 8 + dlen;
2168             }
2169         }
2170 
2171         client_cut_text(vs, read_u32(data, 4), data + 8);
2172         break;
2173     case VNC_MSG_CLIENT_QEMU:
2174         if (len == 1)
2175             return 2;
2176 
2177         switch (read_u8(data, 1)) {
2178         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2179             if (len == 2)
2180                 return 12;
2181 
2182             ext_key_event(vs, read_u16(data, 2),
2183                           read_u32(data, 4), read_u32(data, 8));
2184             break;
2185         case VNC_MSG_CLIENT_QEMU_AUDIO:
2186             if (len == 2)
2187                 return 4;
2188 
2189             switch (read_u16 (data, 2)) {
2190             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2191                 audio_add(vs);
2192                 break;
2193             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2194                 audio_del(vs);
2195                 break;
2196             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2197                 if (len == 4)
2198                     return 10;
2199                 switch (read_u8(data, 4)) {
2200                 case 0: vs->as.fmt = AUD_FMT_U8; break;
2201                 case 1: vs->as.fmt = AUD_FMT_S8; break;
2202                 case 2: vs->as.fmt = AUD_FMT_U16; break;
2203                 case 3: vs->as.fmt = AUD_FMT_S16; break;
2204                 case 4: vs->as.fmt = AUD_FMT_U32; break;
2205                 case 5: vs->as.fmt = AUD_FMT_S32; break;
2206                 default:
2207                     printf("Invalid audio format %d\n", read_u8(data, 4));
2208                     vnc_client_error(vs);
2209                     break;
2210                 }
2211                 vs->as.nchannels = read_u8(data, 5);
2212                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2213                     printf("Invalid audio channel coount %d\n",
2214                            read_u8(data, 5));
2215                     vnc_client_error(vs);
2216                     break;
2217                 }
2218                 vs->as.freq = read_u32(data, 6);
2219                 break;
2220             default:
2221                 printf ("Invalid audio message %d\n", read_u8(data, 4));
2222                 vnc_client_error(vs);
2223                 break;
2224             }
2225             break;
2226 
2227         default:
2228             printf("Msg: %d\n", read_u16(data, 0));
2229             vnc_client_error(vs);
2230             break;
2231         }
2232         break;
2233     default:
2234         printf("Msg: %d\n", data[0]);
2235         vnc_client_error(vs);
2236         break;
2237     }
2238 
2239     vnc_read_when(vs, protocol_client_msg, 1);
2240     return 0;
2241 }
2242 
2243 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2244 {
2245     char buf[1024];
2246     VncShareMode mode;
2247     int size;
2248 
2249     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2250     switch (vs->vd->share_policy) {
2251     case VNC_SHARE_POLICY_IGNORE:
2252         /*
2253          * Ignore the shared flag.  Nothing to do here.
2254          *
2255          * Doesn't conform to the rfb spec but is traditional qemu
2256          * behavior, thus left here as option for compatibility
2257          * reasons.
2258          */
2259         break;
2260     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2261         /*
2262          * Policy: Allow clients ask for exclusive access.
2263          *
2264          * Implementation: When a client asks for exclusive access,
2265          * disconnect all others. Shared connects are allowed as long
2266          * as no exclusive connection exists.
2267          *
2268          * This is how the rfb spec suggests to handle the shared flag.
2269          */
2270         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2271             VncState *client;
2272             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2273                 if (vs == client) {
2274                     continue;
2275                 }
2276                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2277                     client->share_mode != VNC_SHARE_MODE_SHARED) {
2278                     continue;
2279                 }
2280                 vnc_disconnect_start(client);
2281             }
2282         }
2283         if (mode == VNC_SHARE_MODE_SHARED) {
2284             if (vs->vd->num_exclusive > 0) {
2285                 vnc_disconnect_start(vs);
2286                 return 0;
2287             }
2288         }
2289         break;
2290     case VNC_SHARE_POLICY_FORCE_SHARED:
2291         /*
2292          * Policy: Shared connects only.
2293          * Implementation: Disallow clients asking for exclusive access.
2294          *
2295          * Useful for shared desktop sessions where you don't want
2296          * someone forgetting to say -shared when running the vnc
2297          * client disconnect everybody else.
2298          */
2299         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2300             vnc_disconnect_start(vs);
2301             return 0;
2302         }
2303         break;
2304     }
2305     vnc_set_share_mode(vs, mode);
2306 
2307     vs->client_width = pixman_image_get_width(vs->vd->server);
2308     vs->client_height = pixman_image_get_height(vs->vd->server);
2309     vnc_write_u16(vs, vs->client_width);
2310     vnc_write_u16(vs, vs->client_height);
2311 
2312     pixel_format_message(vs);
2313 
2314     if (qemu_name)
2315         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2316     else
2317         size = snprintf(buf, sizeof(buf), "QEMU");
2318 
2319     vnc_write_u32(vs, size);
2320     vnc_write(vs, buf, size);
2321     vnc_flush(vs);
2322 
2323     vnc_client_cache_auth(vs);
2324     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2325 
2326     vnc_read_when(vs, protocol_client_msg, 1);
2327 
2328     return 0;
2329 }
2330 
2331 void start_client_init(VncState *vs)
2332 {
2333     vnc_read_when(vs, protocol_client_init, 1);
2334 }
2335 
2336 static void make_challenge(VncState *vs)
2337 {
2338     int i;
2339 
2340     srand(time(NULL)+getpid()+getpid()*987654+rand());
2341 
2342     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2343         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2344 }
2345 
2346 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2347 {
2348     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2349     int i, j, pwlen;
2350     unsigned char key[8];
2351     time_t now = time(NULL);
2352 
2353     if (!vs->vd->password) {
2354         VNC_DEBUG("No password configured on server");
2355         goto reject;
2356     }
2357     if (vs->vd->expires < now) {
2358         VNC_DEBUG("Password is expired");
2359         goto reject;
2360     }
2361 
2362     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2363 
2364     /* Calculate the expected challenge response */
2365     pwlen = strlen(vs->vd->password);
2366     for (i=0; i<sizeof(key); i++)
2367         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2368     deskey(key, EN0);
2369     for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2370         des(response+j, response+j);
2371 
2372     /* Compare expected vs actual challenge response */
2373     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2374         VNC_DEBUG("Client challenge response did not match\n");
2375         goto reject;
2376     } else {
2377         VNC_DEBUG("Accepting VNC challenge response\n");
2378         vnc_write_u32(vs, 0); /* Accept auth */
2379         vnc_flush(vs);
2380 
2381         start_client_init(vs);
2382     }
2383     return 0;
2384 
2385 reject:
2386     vnc_write_u32(vs, 1); /* Reject auth */
2387     if (vs->minor >= 8) {
2388         static const char err[] = "Authentication failed";
2389         vnc_write_u32(vs, sizeof(err));
2390         vnc_write(vs, err, sizeof(err));
2391     }
2392     vnc_flush(vs);
2393     vnc_client_error(vs);
2394     return 0;
2395 }
2396 
2397 void start_auth_vnc(VncState *vs)
2398 {
2399     make_challenge(vs);
2400     /* Send client a 'random' challenge */
2401     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2402     vnc_flush(vs);
2403 
2404     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2405 }
2406 
2407 
2408 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2409 {
2410     /* We only advertise 1 auth scheme at a time, so client
2411      * must pick the one we sent. Verify this */
2412     if (data[0] != vs->auth) { /* Reject auth */
2413        VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2414        vnc_write_u32(vs, 1);
2415        if (vs->minor >= 8) {
2416            static const char err[] = "Authentication failed";
2417            vnc_write_u32(vs, sizeof(err));
2418            vnc_write(vs, err, sizeof(err));
2419        }
2420        vnc_client_error(vs);
2421     } else { /* Accept requested auth */
2422        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2423        switch (vs->auth) {
2424        case VNC_AUTH_NONE:
2425            VNC_DEBUG("Accept auth none\n");
2426            if (vs->minor >= 8) {
2427                vnc_write_u32(vs, 0); /* Accept auth completion */
2428                vnc_flush(vs);
2429            }
2430            start_client_init(vs);
2431            break;
2432 
2433        case VNC_AUTH_VNC:
2434            VNC_DEBUG("Start VNC auth\n");
2435            start_auth_vnc(vs);
2436            break;
2437 
2438 #ifdef CONFIG_VNC_TLS
2439        case VNC_AUTH_VENCRYPT:
2440            VNC_DEBUG("Accept VeNCrypt auth\n");
2441            start_auth_vencrypt(vs);
2442            break;
2443 #endif /* CONFIG_VNC_TLS */
2444 
2445 #ifdef CONFIG_VNC_SASL
2446        case VNC_AUTH_SASL:
2447            VNC_DEBUG("Accept SASL auth\n");
2448            start_auth_sasl(vs);
2449            break;
2450 #endif /* CONFIG_VNC_SASL */
2451 
2452        default: /* Should not be possible, but just in case */
2453            VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2454            vnc_write_u8(vs, 1);
2455            if (vs->minor >= 8) {
2456                static const char err[] = "Authentication failed";
2457                vnc_write_u32(vs, sizeof(err));
2458                vnc_write(vs, err, sizeof(err));
2459            }
2460            vnc_client_error(vs);
2461        }
2462     }
2463     return 0;
2464 }
2465 
2466 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2467 {
2468     char local[13];
2469 
2470     memcpy(local, version, 12);
2471     local[12] = 0;
2472 
2473     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2474         VNC_DEBUG("Malformed protocol version %s\n", local);
2475         vnc_client_error(vs);
2476         return 0;
2477     }
2478     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2479     if (vs->major != 3 ||
2480         (vs->minor != 3 &&
2481          vs->minor != 4 &&
2482          vs->minor != 5 &&
2483          vs->minor != 7 &&
2484          vs->minor != 8)) {
2485         VNC_DEBUG("Unsupported client version\n");
2486         vnc_write_u32(vs, VNC_AUTH_INVALID);
2487         vnc_flush(vs);
2488         vnc_client_error(vs);
2489         return 0;
2490     }
2491     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2492      * as equivalent to v3.3 by servers
2493      */
2494     if (vs->minor == 4 || vs->minor == 5)
2495         vs->minor = 3;
2496 
2497     if (vs->minor == 3) {
2498         if (vs->auth == VNC_AUTH_NONE) {
2499             VNC_DEBUG("Tell client auth none\n");
2500             vnc_write_u32(vs, vs->auth);
2501             vnc_flush(vs);
2502             start_client_init(vs);
2503        } else if (vs->auth == VNC_AUTH_VNC) {
2504             VNC_DEBUG("Tell client VNC auth\n");
2505             vnc_write_u32(vs, vs->auth);
2506             vnc_flush(vs);
2507             start_auth_vnc(vs);
2508        } else {
2509             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2510             vnc_write_u32(vs, VNC_AUTH_INVALID);
2511             vnc_flush(vs);
2512             vnc_client_error(vs);
2513        }
2514     } else {
2515         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2516         vnc_write_u8(vs, 1); /* num auth */
2517         vnc_write_u8(vs, vs->auth);
2518         vnc_read_when(vs, protocol_client_auth, 1);
2519         vnc_flush(vs);
2520     }
2521 
2522     return 0;
2523 }
2524 
2525 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2526 {
2527     struct VncSurface *vs = &vd->guest;
2528 
2529     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2530 }
2531 
2532 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2533 {
2534     int i, j;
2535 
2536     w = (x + w) / VNC_STAT_RECT;
2537     h = (y + h) / VNC_STAT_RECT;
2538     x /= VNC_STAT_RECT;
2539     y /= VNC_STAT_RECT;
2540 
2541     for (j = y; j <= h; j++) {
2542         for (i = x; i <= w; i++) {
2543             vs->lossy_rect[j][i] = 1;
2544         }
2545     }
2546 }
2547 
2548 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2549 {
2550     VncState *vs;
2551     int sty = y / VNC_STAT_RECT;
2552     int stx = x / VNC_STAT_RECT;
2553     int has_dirty = 0;
2554 
2555     y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2556     x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2557 
2558     QTAILQ_FOREACH(vs, &vd->clients, next) {
2559         int j;
2560 
2561         /* kernel send buffers are full -> refresh later */
2562         if (vs->output.offset) {
2563             continue;
2564         }
2565 
2566         if (!vs->lossy_rect[sty][stx]) {
2567             continue;
2568         }
2569 
2570         vs->lossy_rect[sty][stx] = 0;
2571         for (j = 0; j < VNC_STAT_RECT; ++j) {
2572             bitmap_set(vs->dirty[y + j],
2573                        x / VNC_DIRTY_PIXELS_PER_BIT,
2574                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2575         }
2576         has_dirty++;
2577     }
2578 
2579     return has_dirty;
2580 }
2581 
2582 static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2583 {
2584     int width = pixman_image_get_width(vd->guest.fb);
2585     int height = pixman_image_get_height(vd->guest.fb);
2586     int x, y;
2587     struct timeval res;
2588     int has_dirty = 0;
2589 
2590     for (y = 0; y < height; y += VNC_STAT_RECT) {
2591         for (x = 0; x < width; x += VNC_STAT_RECT) {
2592             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2593 
2594             rect->updated = false;
2595         }
2596     }
2597 
2598     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2599 
2600     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2601         return has_dirty;
2602     }
2603     vd->guest.last_freq_check = *tv;
2604 
2605     for (y = 0; y < height; y += VNC_STAT_RECT) {
2606         for (x = 0; x < width; x += VNC_STAT_RECT) {
2607             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2608             int count = ARRAY_SIZE(rect->times);
2609             struct timeval min, max;
2610 
2611             if (!timerisset(&rect->times[count - 1])) {
2612                 continue ;
2613             }
2614 
2615             max = rect->times[(rect->idx + count - 1) % count];
2616             qemu_timersub(tv, &max, &res);
2617 
2618             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2619                 rect->freq = 0;
2620                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2621                 memset(rect->times, 0, sizeof (rect->times));
2622                 continue ;
2623             }
2624 
2625             min = rect->times[rect->idx];
2626             max = rect->times[(rect->idx + count - 1) % count];
2627             qemu_timersub(&max, &min, &res);
2628 
2629             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2630             rect->freq /= count;
2631             rect->freq = 1. / rect->freq;
2632         }
2633     }
2634     return has_dirty;
2635 }
2636 
2637 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2638 {
2639     int i, j;
2640     double total = 0;
2641     int num = 0;
2642 
2643     x =  (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2644     y =  (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2645 
2646     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2647         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2648             total += vnc_stat_rect(vs->vd, i, j)->freq;
2649             num++;
2650         }
2651     }
2652 
2653     if (num) {
2654         return total / num;
2655     } else {
2656         return 0;
2657     }
2658 }
2659 
2660 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2661 {
2662     VncRectStat *rect;
2663 
2664     rect = vnc_stat_rect(vd, x, y);
2665     if (rect->updated) {
2666         return ;
2667     }
2668     rect->times[rect->idx] = *tv;
2669     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2670     rect->updated = true;
2671 }
2672 
2673 static int vnc_refresh_server_surface(VncDisplay *vd)
2674 {
2675     int width = MIN(pixman_image_get_width(vd->guest.fb),
2676                     pixman_image_get_width(vd->server));
2677     int height = MIN(pixman_image_get_height(vd->guest.fb),
2678                      pixman_image_get_height(vd->server));
2679     int cmp_bytes, server_stride, min_stride, guest_stride, y = 0;
2680     uint8_t *guest_row0 = NULL, *server_row0;
2681     VncState *vs;
2682     int has_dirty = 0;
2683     pixman_image_t *tmpbuf = NULL;
2684 
2685     struct timeval tv = { 0, 0 };
2686 
2687     if (!vd->non_adaptive) {
2688         gettimeofday(&tv, NULL);
2689         has_dirty = vnc_update_stats(vd, &tv);
2690     }
2691 
2692     /*
2693      * Walk through the guest dirty map.
2694      * Check and copy modified bits from guest to server surface.
2695      * Update server dirty map.
2696      */
2697     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2698     server_stride = guest_stride = pixman_image_get_stride(vd->server);
2699     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2700                     server_stride);
2701     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2702         int width = pixman_image_get_width(vd->server);
2703         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2704     } else {
2705         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2706         guest_stride = pixman_image_get_stride(vd->guest.fb);
2707     }
2708     min_stride = MIN(server_stride, guest_stride);
2709 
2710     for (;;) {
2711         int x;
2712         uint8_t *guest_ptr, *server_ptr;
2713         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2714                                              height * VNC_DIRTY_BPL(&vd->guest),
2715                                              y * VNC_DIRTY_BPL(&vd->guest));
2716         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2717             /* no more dirty bits */
2718             break;
2719         }
2720         y = offset / VNC_DIRTY_BPL(&vd->guest);
2721         x = offset % VNC_DIRTY_BPL(&vd->guest);
2722 
2723         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2724 
2725         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2726             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2727             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2728         } else {
2729             guest_ptr = guest_row0 + y * guest_stride;
2730         }
2731         guest_ptr += x * cmp_bytes;
2732 
2733         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2734              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2735             int _cmp_bytes = cmp_bytes;
2736             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2737                 continue;
2738             }
2739             if ((x + 1) * cmp_bytes > min_stride) {
2740                 _cmp_bytes = min_stride - x * cmp_bytes;
2741             }
2742             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2743                 continue;
2744             }
2745             memcpy(server_ptr, guest_ptr, _cmp_bytes);
2746             if (!vd->non_adaptive) {
2747                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2748                                  y, &tv);
2749             }
2750             QTAILQ_FOREACH(vs, &vd->clients, next) {
2751                 set_bit(x, vs->dirty[y]);
2752             }
2753             has_dirty++;
2754         }
2755 
2756         y++;
2757     }
2758     qemu_pixman_image_unref(tmpbuf);
2759     return has_dirty;
2760 }
2761 
2762 static void vnc_refresh(DisplayChangeListener *dcl)
2763 {
2764     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2765     VncState *vs, *vn;
2766     int has_dirty, rects = 0;
2767 
2768     graphic_hw_update(NULL);
2769 
2770     if (vnc_trylock_display(vd)) {
2771         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2772         return;
2773     }
2774 
2775     has_dirty = vnc_refresh_server_surface(vd);
2776     vnc_unlock_display(vd);
2777 
2778     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2779         rects += vnc_update_client(vs, has_dirty, false);
2780         /* vs might be free()ed here */
2781     }
2782 
2783     if (QTAILQ_EMPTY(&vd->clients)) {
2784         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2785         return;
2786     }
2787 
2788     if (has_dirty && rects) {
2789         vd->dcl.update_interval /= 2;
2790         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
2791             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
2792         }
2793     } else {
2794         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
2795         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
2796             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
2797         }
2798     }
2799 }
2800 
2801 static void vnc_connect(VncDisplay *vd, int csock,
2802                         bool skipauth, bool websocket)
2803 {
2804     VncState *vs = g_malloc0(sizeof(VncState));
2805     int i;
2806 
2807     vs->csock = csock;
2808 
2809     if (skipauth) {
2810 	vs->auth = VNC_AUTH_NONE;
2811 #ifdef CONFIG_VNC_TLS
2812 	vs->subauth = VNC_AUTH_INVALID;
2813 #endif
2814     } else {
2815 	vs->auth = vd->auth;
2816 #ifdef CONFIG_VNC_TLS
2817 	vs->subauth = vd->subauth;
2818 #endif
2819     }
2820 
2821     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
2822     for (i = 0; i < VNC_STAT_ROWS; ++i) {
2823         vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
2824     }
2825 
2826     VNC_DEBUG("New client on socket %d\n", csock);
2827     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2828     qemu_set_nonblock(vs->csock);
2829 #ifdef CONFIG_VNC_WS
2830     if (websocket) {
2831         vs->websocket = 1;
2832 #ifdef CONFIG_VNC_TLS
2833         if (vd->tls.x509cert) {
2834             qemu_set_fd_handler2(vs->csock, NULL, vncws_tls_handshake_peek,
2835                                  NULL, vs);
2836         } else
2837 #endif /* CONFIG_VNC_TLS */
2838         {
2839             qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read,
2840                                  NULL, vs);
2841         }
2842     } else
2843 #endif /* CONFIG_VNC_WS */
2844     {
2845         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2846     }
2847 
2848     vnc_client_cache_addr(vs);
2849     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
2850     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
2851 
2852     vs->vd = vd;
2853 
2854 #ifdef CONFIG_VNC_WS
2855     if (!vs->websocket)
2856 #endif
2857     {
2858         vnc_init_state(vs);
2859     }
2860 }
2861 
2862 void vnc_init_state(VncState *vs)
2863 {
2864     vs->initialized = true;
2865     VncDisplay *vd = vs->vd;
2866 
2867     vs->last_x = -1;
2868     vs->last_y = -1;
2869 
2870     vs->as.freq = 44100;
2871     vs->as.nchannels = 2;
2872     vs->as.fmt = AUD_FMT_S16;
2873     vs->as.endianness = 0;
2874 
2875     qemu_mutex_init(&vs->output_mutex);
2876     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
2877 
2878     QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2879 
2880     graphic_hw_update(NULL);
2881 
2882     vnc_write(vs, "RFB 003.008\n", 12);
2883     vnc_flush(vs);
2884     vnc_read_when(vs, protocol_version, 12);
2885     reset_keys(vs);
2886     if (vs->vd->lock_key_sync)
2887         vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2888 
2889     vs->mouse_mode_notifier.notify = check_pointer_type_change;
2890     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2891 
2892     /* vs might be free()ed here */
2893 }
2894 
2895 static void vnc_listen_read(void *opaque, bool websocket)
2896 {
2897     VncDisplay *vs = opaque;
2898     struct sockaddr_in addr;
2899     socklen_t addrlen = sizeof(addr);
2900     int csock;
2901 
2902     /* Catch-up */
2903     graphic_hw_update(NULL);
2904 #ifdef CONFIG_VNC_WS
2905     if (websocket) {
2906         csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
2907     } else
2908 #endif /* CONFIG_VNC_WS */
2909     {
2910         csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2911     }
2912 
2913     if (csock != -1) {
2914         vnc_connect(vs, csock, false, websocket);
2915     }
2916 }
2917 
2918 static void vnc_listen_regular_read(void *opaque)
2919 {
2920     vnc_listen_read(opaque, false);
2921 }
2922 
2923 #ifdef CONFIG_VNC_WS
2924 static void vnc_listen_websocket_read(void *opaque)
2925 {
2926     vnc_listen_read(opaque, true);
2927 }
2928 #endif /* CONFIG_VNC_WS */
2929 
2930 static const DisplayChangeListenerOps dcl_ops = {
2931     .dpy_name          = "vnc",
2932     .dpy_refresh       = vnc_refresh,
2933     .dpy_gfx_copy      = vnc_dpy_copy,
2934     .dpy_gfx_update    = vnc_dpy_update,
2935     .dpy_gfx_switch    = vnc_dpy_switch,
2936     .dpy_mouse_set     = vnc_mouse_set,
2937     .dpy_cursor_define = vnc_dpy_cursor_define,
2938 };
2939 
2940 void vnc_display_init(DisplayState *ds)
2941 {
2942     VncDisplay *vs = g_malloc0(sizeof(*vs));
2943 
2944     vnc_display = vs;
2945 
2946     vs->lsock = -1;
2947 #ifdef CONFIG_VNC_WS
2948     vs->lwebsock = -1;
2949 #endif
2950 
2951     QTAILQ_INIT(&vs->clients);
2952     vs->expires = TIME_MAX;
2953 
2954     if (keyboard_layout) {
2955         trace_vnc_key_map_init(keyboard_layout);
2956         vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2957     } else {
2958         vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2959     }
2960 
2961     if (!vs->kbd_layout)
2962         exit(1);
2963 
2964     qemu_mutex_init(&vs->mutex);
2965     vnc_start_worker_thread();
2966 
2967     vs->dcl.ops = &dcl_ops;
2968     register_displaychangelistener(&vs->dcl);
2969 }
2970 
2971 
2972 static void vnc_display_close(DisplayState *ds)
2973 {
2974     VncDisplay *vs = vnc_display;
2975 
2976     if (!vs)
2977         return;
2978     g_free(vs->display);
2979     vs->display = NULL;
2980     if (vs->lsock != -1) {
2981         qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2982         close(vs->lsock);
2983         vs->lsock = -1;
2984     }
2985 #ifdef CONFIG_VNC_WS
2986     g_free(vs->ws_display);
2987     vs->ws_display = NULL;
2988     if (vs->lwebsock != -1) {
2989         qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
2990         close(vs->lwebsock);
2991         vs->lwebsock = -1;
2992     }
2993 #endif /* CONFIG_VNC_WS */
2994     vs->auth = VNC_AUTH_INVALID;
2995 #ifdef CONFIG_VNC_TLS
2996     vs->subauth = VNC_AUTH_INVALID;
2997     vs->tls.x509verify = 0;
2998 #endif
2999 }
3000 
3001 int vnc_display_password(DisplayState *ds, const char *password)
3002 {
3003     VncDisplay *vs = vnc_display;
3004 
3005     if (!vs) {
3006         return -EINVAL;
3007     }
3008     if (vs->auth == VNC_AUTH_NONE) {
3009         error_printf_unless_qmp("If you want use passwords please enable "
3010                                 "password auth using '-vnc ${dpy},password'.");
3011         return -EINVAL;
3012     }
3013 
3014     g_free(vs->password);
3015     vs->password = g_strdup(password);
3016 
3017     return 0;
3018 }
3019 
3020 int vnc_display_pw_expire(DisplayState *ds, time_t expires)
3021 {
3022     VncDisplay *vs = vnc_display;
3023 
3024     if (!vs) {
3025         return -EINVAL;
3026     }
3027 
3028     vs->expires = expires;
3029     return 0;
3030 }
3031 
3032 char *vnc_display_local_addr(DisplayState *ds)
3033 {
3034     VncDisplay *vs = vnc_display;
3035 
3036     return vnc_socket_local_addr("%s:%s", vs->lsock);
3037 }
3038 
3039 void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
3040 {
3041     VncDisplay *vs = vnc_display;
3042     const char *options;
3043     int password = 0;
3044     int reverse = 0;
3045 #ifdef CONFIG_VNC_TLS
3046     int tls = 0, x509 = 0;
3047 #endif
3048 #ifdef CONFIG_VNC_SASL
3049     int sasl = 0;
3050     int saslErr;
3051 #endif
3052 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3053     int acl = 0;
3054 #endif
3055     int lock_key_sync = 1;
3056 
3057     if (!vnc_display) {
3058         error_setg(errp, "VNC display not active");
3059         return;
3060     }
3061     vnc_display_close(ds);
3062     if (strcmp(display, "none") == 0)
3063         return;
3064 
3065     vs->display = g_strdup(display);
3066     vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3067 
3068     options = display;
3069     while ((options = strchr(options, ','))) {
3070         options++;
3071         if (strncmp(options, "password", 8) == 0) {
3072             if (fips_get_state()) {
3073                 error_setg(errp,
3074                            "VNC password auth disabled due to FIPS mode, "
3075                            "consider using the VeNCrypt or SASL authentication "
3076                            "methods as an alternative");
3077                 goto fail;
3078             }
3079             password = 1; /* Require password auth */
3080         } else if (strncmp(options, "reverse", 7) == 0) {
3081             reverse = 1;
3082         } else if (strncmp(options, "no-lock-key-sync", 16) == 0) {
3083             lock_key_sync = 0;
3084 #ifdef CONFIG_VNC_SASL
3085         } else if (strncmp(options, "sasl", 4) == 0) {
3086             sasl = 1; /* Require SASL auth */
3087 #endif
3088 #ifdef CONFIG_VNC_WS
3089         } else if (strncmp(options, "websocket", 9) == 0) {
3090             char *start, *end;
3091             vs->websocket = 1;
3092 
3093             /* Check for 'websocket=<port>' */
3094             start = strchr(options, '=');
3095             end = strchr(options, ',');
3096             if (start && (!end || (start < end))) {
3097                 int len = end ? end-(start+1) : strlen(start+1);
3098                 if (len < 6) {
3099                     /* extract the host specification from display */
3100                     char  *host = NULL, *port = NULL, *host_end = NULL;
3101                     port = g_strndup(start + 1, len);
3102 
3103                     /* ipv6 hosts have colons */
3104                     end = strchr(display, ',');
3105                     host_end = g_strrstr_len(display, end - display, ":");
3106 
3107                     if (host_end) {
3108                         host = g_strndup(display, host_end - display + 1);
3109                     } else {
3110                         host = g_strndup(":", 1);
3111                     }
3112                     vs->ws_display = g_strconcat(host, port, NULL);
3113                     g_free(host);
3114                     g_free(port);
3115                 }
3116             }
3117 #endif /* CONFIG_VNC_WS */
3118 #ifdef CONFIG_VNC_TLS
3119         } else if (strncmp(options, "tls", 3) == 0) {
3120             tls = 1; /* Require TLS */
3121         } else if (strncmp(options, "x509", 4) == 0) {
3122             char *start, *end;
3123             x509 = 1; /* Require x509 certificates */
3124             if (strncmp(options, "x509verify", 10) == 0)
3125                 vs->tls.x509verify = 1; /* ...and verify client certs */
3126 
3127             /* Now check for 'x509=/some/path' postfix
3128              * and use that to setup x509 certificate/key paths */
3129             start = strchr(options, '=');
3130             end = strchr(options, ',');
3131             if (start && (!end || (start < end))) {
3132                 int len = end ? end-(start+1) : strlen(start+1);
3133                 char *path = g_strndup(start + 1, len);
3134 
3135                 VNC_DEBUG("Trying certificate path '%s'\n", path);
3136                 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
3137                     error_setg(errp, "Failed to find x509 certificates/keys in %s", path);
3138                     g_free(path);
3139                     goto fail;
3140                 }
3141                 g_free(path);
3142             } else {
3143                 error_setg(errp, "No certificate path provided");
3144                 goto fail;
3145             }
3146 #endif
3147 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3148         } else if (strncmp(options, "acl", 3) == 0) {
3149             acl = 1;
3150 #endif
3151         } else if (strncmp(options, "lossy", 5) == 0) {
3152 #ifdef CONFIG_VNC_JPEG
3153             vs->lossy = true;
3154 #endif
3155         } else if (strncmp(options, "non-adaptive", 12) == 0) {
3156             vs->non_adaptive = true;
3157         } else if (strncmp(options, "share=", 6) == 0) {
3158             if (strncmp(options+6, "ignore", 6) == 0) {
3159                 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
3160             } else if (strncmp(options+6, "allow-exclusive", 15) == 0) {
3161                 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3162             } else if (strncmp(options+6, "force-shared", 12) == 0) {
3163                 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3164             } else {
3165                 error_setg(errp, "unknown vnc share= option");
3166                 goto fail;
3167             }
3168         }
3169     }
3170 
3171     /* adaptive updates are only used with tight encoding and
3172      * if lossy updates are enabled so we can disable all the
3173      * calculations otherwise */
3174     if (!vs->lossy) {
3175         vs->non_adaptive = true;
3176     }
3177 
3178 #ifdef CONFIG_VNC_TLS
3179     if (acl && x509 && vs->tls.x509verify) {
3180         if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
3181             fprintf(stderr, "Failed to create x509 dname ACL\n");
3182             exit(1);
3183         }
3184     }
3185 #endif
3186 #ifdef CONFIG_VNC_SASL
3187     if (acl && sasl) {
3188         if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
3189             fprintf(stderr, "Failed to create username ACL\n");
3190             exit(1);
3191         }
3192     }
3193 #endif
3194 
3195     /*
3196      * Combinations we support here:
3197      *
3198      *  - no-auth                (clear text, no auth)
3199      *  - password               (clear text, weak auth)
3200      *  - sasl                   (encrypt, good auth *IF* using Kerberos via GSSAPI)
3201      *  - tls                    (encrypt, weak anonymous creds, no auth)
3202      *  - tls + password         (encrypt, weak anonymous creds, weak auth)
3203      *  - tls + sasl             (encrypt, weak anonymous creds, good auth)
3204      *  - tls + x509             (encrypt, good x509 creds, no auth)
3205      *  - tls + x509 + password  (encrypt, good x509 creds, weak auth)
3206      *  - tls + x509 + sasl      (encrypt, good x509 creds, good auth)
3207      *
3208      * NB1. TLS is a stackable auth scheme.
3209      * NB2. the x509 schemes have option to validate a client cert dname
3210      */
3211     if (password) {
3212 #ifdef CONFIG_VNC_TLS
3213         if (tls) {
3214             vs->auth = VNC_AUTH_VENCRYPT;
3215             if (x509) {
3216                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3217                 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
3218             } else {
3219                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3220                 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3221             }
3222         } else {
3223 #endif /* CONFIG_VNC_TLS */
3224             VNC_DEBUG("Initializing VNC server with password auth\n");
3225             vs->auth = VNC_AUTH_VNC;
3226 #ifdef CONFIG_VNC_TLS
3227             vs->subauth = VNC_AUTH_INVALID;
3228         }
3229 #endif /* CONFIG_VNC_TLS */
3230 #ifdef CONFIG_VNC_SASL
3231     } else if (sasl) {
3232 #ifdef CONFIG_VNC_TLS
3233         if (tls) {
3234             vs->auth = VNC_AUTH_VENCRYPT;
3235             if (x509) {
3236                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3237                 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3238             } else {
3239                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3240                 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3241             }
3242         } else {
3243 #endif /* CONFIG_VNC_TLS */
3244             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3245             vs->auth = VNC_AUTH_SASL;
3246 #ifdef CONFIG_VNC_TLS
3247             vs->subauth = VNC_AUTH_INVALID;
3248         }
3249 #endif /* CONFIG_VNC_TLS */
3250 #endif /* CONFIG_VNC_SASL */
3251     } else {
3252 #ifdef CONFIG_VNC_TLS
3253         if (tls) {
3254             vs->auth = VNC_AUTH_VENCRYPT;
3255             if (x509) {
3256                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3257                 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3258             } else {
3259                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3260                 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3261             }
3262         } else {
3263 #endif
3264             VNC_DEBUG("Initializing VNC server with no auth\n");
3265             vs->auth = VNC_AUTH_NONE;
3266 #ifdef CONFIG_VNC_TLS
3267             vs->subauth = VNC_AUTH_INVALID;
3268         }
3269 #endif
3270     }
3271 
3272 #ifdef CONFIG_VNC_SASL
3273     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3274         error_setg(errp, "Failed to initialize SASL auth: %s",
3275                    sasl_errstring(saslErr, NULL, NULL));
3276         goto fail;
3277     }
3278 #endif
3279     vs->lock_key_sync = lock_key_sync;
3280 
3281     if (reverse) {
3282         /* connect to viewer */
3283         int csock;
3284         vs->lsock = -1;
3285 #ifdef CONFIG_VNC_WS
3286         vs->lwebsock = -1;
3287 #endif
3288         if (strncmp(display, "unix:", 5) == 0) {
3289             csock = unix_connect(display+5, errp);
3290         } else {
3291             csock = inet_connect(display, errp);
3292         }
3293         if (csock < 0) {
3294             goto fail;
3295         }
3296         vnc_connect(vs, csock, false, false);
3297     } else {
3298         /* listen for connects */
3299         char *dpy;
3300         dpy = g_malloc(256);
3301         if (strncmp(display, "unix:", 5) == 0) {
3302             pstrcpy(dpy, 256, "unix:");
3303             vs->lsock = unix_listen(display+5, dpy+5, 256-5, errp);
3304         } else {
3305             vs->lsock = inet_listen(display, dpy, 256,
3306                                     SOCK_STREAM, 5900, errp);
3307             if (vs->lsock < 0) {
3308                 g_free(dpy);
3309                 goto fail;
3310             }
3311 #ifdef CONFIG_VNC_WS
3312             if (vs->websocket) {
3313                 if (vs->ws_display) {
3314                     vs->lwebsock = inet_listen(vs->ws_display, NULL, 256,
3315                         SOCK_STREAM, 0, errp);
3316                 } else {
3317                     vs->lwebsock = inet_listen(vs->display, NULL, 256,
3318                         SOCK_STREAM, 5700, errp);
3319                 }
3320 
3321                 if (vs->lwebsock < 0) {
3322                     if (vs->lsock) {
3323                         close(vs->lsock);
3324                         vs->lsock = -1;
3325                     }
3326                     g_free(dpy);
3327                     goto fail;
3328                 }
3329             }
3330 #endif /* CONFIG_VNC_WS */
3331         }
3332         g_free(vs->display);
3333         vs->display = dpy;
3334         qemu_set_fd_handler2(vs->lsock, NULL,
3335                 vnc_listen_regular_read, NULL, vs);
3336 #ifdef CONFIG_VNC_WS
3337         if (vs->websocket) {
3338             qemu_set_fd_handler2(vs->lwebsock, NULL,
3339                     vnc_listen_websocket_read, NULL, vs);
3340         }
3341 #endif /* CONFIG_VNC_WS */
3342     }
3343     return;
3344 
3345 fail:
3346     g_free(vs->display);
3347     vs->display = NULL;
3348 #ifdef CONFIG_VNC_WS
3349     g_free(vs->ws_display);
3350     vs->ws_display = NULL;
3351 #endif /* CONFIG_VNC_WS */
3352 }
3353 
3354 void vnc_display_add_client(DisplayState *ds, int csock, bool skipauth)
3355 {
3356     VncDisplay *vs = vnc_display;
3357 
3358     vnc_connect(vs, csock, skipauth, false);
3359 }
3360