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