xref: /openbmc/qemu/ui/vnc.c (revision 5b262bb6)
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 "qemu/osdep.h"
28 #include "vnc.h"
29 #include "vnc-jobs.h"
30 #include "trace.h"
31 #include "hw/qdev.h"
32 #include "sysemu/sysemu.h"
33 #include "qemu/error-report.h"
34 #include "qemu/sockets.h"
35 #include "qemu/timer.h"
36 #include "qemu/acl.h"
37 #include "qemu/config-file.h"
38 #include "qapi/qmp/qerror.h"
39 #include "qapi/qmp/types.h"
40 #include "qmp-commands.h"
41 #include "ui/input.h"
42 #include "qapi-event.h"
43 #include "crypto/hash.h"
44 #include "crypto/tlscredsanon.h"
45 #include "crypto/tlscredsx509.h"
46 #include "qom/object_interfaces.h"
47 #include "qemu/cutils.h"
48 
49 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
50 #define VNC_REFRESH_INTERVAL_INC  50
51 #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
52 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
53 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
54 
55 #include "vnc_keysym.h"
56 #include "crypto/cipher.h"
57 
58 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
59     QTAILQ_HEAD_INITIALIZER(vnc_displays);
60 
61 static int vnc_cursor_define(VncState *vs);
62 static void vnc_release_modifiers(VncState *vs);
63 
64 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
65 {
66 #ifdef _VNC_DEBUG
67     static const char *mn[] = {
68         [0]                           = "undefined",
69         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
70         [VNC_SHARE_MODE_SHARED]       = "shared",
71         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
72         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
73     };
74     fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
75             vs->ioc, mn[vs->share_mode], mn[mode]);
76 #endif
77 
78     switch (vs->share_mode) {
79     case VNC_SHARE_MODE_CONNECTING:
80         vs->vd->num_connecting--;
81         break;
82     case VNC_SHARE_MODE_SHARED:
83         vs->vd->num_shared--;
84         break;
85     case VNC_SHARE_MODE_EXCLUSIVE:
86         vs->vd->num_exclusive--;
87         break;
88     default:
89         break;
90     }
91 
92     vs->share_mode = mode;
93 
94     switch (vs->share_mode) {
95     case VNC_SHARE_MODE_CONNECTING:
96         vs->vd->num_connecting++;
97         break;
98     case VNC_SHARE_MODE_SHARED:
99         vs->vd->num_shared++;
100         break;
101     case VNC_SHARE_MODE_EXCLUSIVE:
102         vs->vd->num_exclusive++;
103         break;
104     default:
105         break;
106     }
107 }
108 
109 
110 static void vnc_init_basic_info(SocketAddress *addr,
111                                 VncBasicInfo *info,
112                                 Error **errp)
113 {
114     switch (addr->type) {
115     case SOCKET_ADDRESS_KIND_INET:
116         info->host = g_strdup(addr->u.inet.data->host);
117         info->service = g_strdup(addr->u.inet.data->port);
118         if (addr->u.inet.data->ipv6) {
119             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
120         } else {
121             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
122         }
123         break;
124 
125     case SOCKET_ADDRESS_KIND_UNIX:
126         info->host = g_strdup("");
127         info->service = g_strdup(addr->u.q_unix.data->path);
128         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
129         break;
130 
131     default:
132         error_setg(errp, "Unsupported socket kind %d",
133                    addr->type);
134         break;
135     }
136 
137     return;
138 }
139 
140 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
141                                                  VncBasicInfo *info,
142                                                  Error **errp)
143 {
144     SocketAddress *addr = NULL;
145 
146     if (!ioc) {
147         error_setg(errp, "No listener socket available");
148         return;
149     }
150 
151     addr = qio_channel_socket_get_local_address(ioc, errp);
152     if (!addr) {
153         return;
154     }
155 
156     vnc_init_basic_info(addr, info, errp);
157     qapi_free_SocketAddress(addr);
158 }
159 
160 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
161                                                  VncBasicInfo *info,
162                                                  Error **errp)
163 {
164     SocketAddress *addr = NULL;
165 
166     addr = qio_channel_socket_get_remote_address(ioc, errp);
167     if (!addr) {
168         return;
169     }
170 
171     vnc_init_basic_info(addr, info, errp);
172     qapi_free_SocketAddress(addr);
173 }
174 
175 static const char *vnc_auth_name(VncDisplay *vd) {
176     switch (vd->auth) {
177     case VNC_AUTH_INVALID:
178         return "invalid";
179     case VNC_AUTH_NONE:
180         return "none";
181     case VNC_AUTH_VNC:
182         return "vnc";
183     case VNC_AUTH_RA2:
184         return "ra2";
185     case VNC_AUTH_RA2NE:
186         return "ra2ne";
187     case VNC_AUTH_TIGHT:
188         return "tight";
189     case VNC_AUTH_ULTRA:
190         return "ultra";
191     case VNC_AUTH_TLS:
192         return "tls";
193     case VNC_AUTH_VENCRYPT:
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     case VNC_AUTH_SASL:
217         return "sasl";
218     }
219     return "unknown";
220 }
221 
222 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
223 {
224     VncServerInfo *info;
225     Error *err = NULL;
226 
227     info = g_malloc0(sizeof(*info));
228     vnc_init_basic_info_from_server_addr(vd->lsock,
229                                          qapi_VncServerInfo_base(info), &err);
230     info->has_auth = true;
231     info->auth = g_strdup(vnc_auth_name(vd));
232     if (err) {
233         qapi_free_VncServerInfo(info);
234         info = NULL;
235         error_free(err);
236     }
237     return info;
238 }
239 
240 static void vnc_client_cache_auth(VncState *client)
241 {
242     if (!client->info) {
243         return;
244     }
245 
246     if (client->tls) {
247         client->info->x509_dname =
248             qcrypto_tls_session_get_peer_name(client->tls);
249         client->info->has_x509_dname =
250             client->info->x509_dname != NULL;
251     }
252 #ifdef CONFIG_VNC_SASL
253     if (client->sasl.conn &&
254         client->sasl.username) {
255         client->info->has_sasl_username = true;
256         client->info->sasl_username = g_strdup(client->sasl.username);
257     }
258 #endif
259 }
260 
261 static void vnc_client_cache_addr(VncState *client)
262 {
263     Error *err = NULL;
264 
265     client->info = g_malloc0(sizeof(*client->info));
266     vnc_init_basic_info_from_remote_addr(client->sioc,
267                                          qapi_VncClientInfo_base(client->info),
268                                          &err);
269     if (err) {
270         qapi_free_VncClientInfo(client->info);
271         client->info = NULL;
272         error_free(err);
273     }
274 }
275 
276 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
277 {
278     VncServerInfo *si;
279 
280     if (!vs->info) {
281         return;
282     }
283 
284     si = vnc_server_info_get(vs->vd);
285     if (!si) {
286         return;
287     }
288 
289     switch (event) {
290     case QAPI_EVENT_VNC_CONNECTED:
291         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info),
292                                       &error_abort);
293         break;
294     case QAPI_EVENT_VNC_INITIALIZED:
295         qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
296         break;
297     case QAPI_EVENT_VNC_DISCONNECTED:
298         qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
299         break;
300     default:
301         break;
302     }
303 
304     qapi_free_VncServerInfo(si);
305 }
306 
307 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
308 {
309     VncClientInfo *info;
310     Error *err = NULL;
311 
312     info = g_malloc0(sizeof(*info));
313 
314     vnc_init_basic_info_from_remote_addr(client->sioc,
315                                          qapi_VncClientInfo_base(info),
316                                          &err);
317     if (err) {
318         error_free(err);
319         qapi_free_VncClientInfo(info);
320         return NULL;
321     }
322 
323     info->websocket = client->websocket;
324 
325     if (client->tls) {
326         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
327         info->has_x509_dname = info->x509_dname != NULL;
328     }
329 #ifdef CONFIG_VNC_SASL
330     if (client->sasl.conn && client->sasl.username) {
331         info->has_sasl_username = true;
332         info->sasl_username = g_strdup(client->sasl.username);
333     }
334 #endif
335 
336     return info;
337 }
338 
339 static VncDisplay *vnc_display_find(const char *id)
340 {
341     VncDisplay *vd;
342 
343     if (id == NULL) {
344         return QTAILQ_FIRST(&vnc_displays);
345     }
346     QTAILQ_FOREACH(vd, &vnc_displays, next) {
347         if (strcmp(id, vd->id) == 0) {
348             return vd;
349         }
350     }
351     return NULL;
352 }
353 
354 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
355 {
356     VncClientInfoList *cinfo, *prev = NULL;
357     VncState *client;
358 
359     QTAILQ_FOREACH(client, &vd->clients, next) {
360         cinfo = g_new0(VncClientInfoList, 1);
361         cinfo->value = qmp_query_vnc_client(client);
362         cinfo->next = prev;
363         prev = cinfo;
364     }
365     return prev;
366 }
367 
368 VncInfo *qmp_query_vnc(Error **errp)
369 {
370     VncInfo *info = g_malloc0(sizeof(*info));
371     VncDisplay *vd = vnc_display_find(NULL);
372     SocketAddress *addr = NULL;
373 
374     if (vd == NULL || !vd->enabled) {
375         info->enabled = false;
376     } else {
377         info->enabled = true;
378 
379         /* for compatibility with the original command */
380         info->has_clients = true;
381         info->clients = qmp_query_client_list(vd);
382 
383         if (vd->lsock == NULL) {
384             return info;
385         }
386 
387         addr = qio_channel_socket_get_local_address(vd->lsock, errp);
388         if (!addr) {
389             goto out_error;
390         }
391 
392         switch (addr->type) {
393         case SOCKET_ADDRESS_KIND_INET:
394             info->host = g_strdup(addr->u.inet.data->host);
395             info->service = g_strdup(addr->u.inet.data->port);
396             if (addr->u.inet.data->ipv6) {
397                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
398             } else {
399                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
400             }
401             break;
402 
403         case SOCKET_ADDRESS_KIND_UNIX:
404             info->host = g_strdup("");
405             info->service = g_strdup(addr->u.q_unix.data->path);
406             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
407             break;
408 
409         default:
410             error_setg(errp, "Unsupported socket kind %d",
411                        addr->type);
412             goto out_error;
413         }
414 
415         info->has_host = true;
416         info->has_service = true;
417         info->has_family = true;
418 
419         info->has_auth = true;
420         info->auth = g_strdup(vnc_auth_name(vd));
421     }
422 
423     qapi_free_SocketAddress(addr);
424     return info;
425 
426 out_error:
427     qapi_free_SocketAddress(addr);
428     qapi_free_VncInfo(info);
429     return NULL;
430 }
431 
432 static VncBasicInfoList *qmp_query_server_entry(QIOChannelSocket *ioc,
433                                                 bool websocket,
434                                                 VncBasicInfoList *prev)
435 {
436     VncBasicInfoList *list;
437     VncBasicInfo *info;
438     Error *err = NULL;
439     SocketAddress *addr;
440 
441     addr = qio_channel_socket_get_local_address(ioc, &err);
442     if (!addr) {
443         error_free(err);
444         return prev;
445     }
446 
447     info = g_new0(VncBasicInfo, 1);
448     vnc_init_basic_info(addr, info, &err);
449     qapi_free_SocketAddress(addr);
450     if (err) {
451         qapi_free_VncBasicInfo(info);
452         error_free(err);
453         return prev;
454     }
455     info->websocket = websocket;
456 
457     list = g_new0(VncBasicInfoList, 1);
458     list->value = info;
459     list->next = prev;
460     return list;
461 }
462 
463 static void qmp_query_auth(VncDisplay *vd, VncInfo2 *info)
464 {
465     switch (vd->auth) {
466     case VNC_AUTH_VNC:
467         info->auth = VNC_PRIMARY_AUTH_VNC;
468         break;
469     case VNC_AUTH_RA2:
470         info->auth = VNC_PRIMARY_AUTH_RA2;
471         break;
472     case VNC_AUTH_RA2NE:
473         info->auth = VNC_PRIMARY_AUTH_RA2NE;
474         break;
475     case VNC_AUTH_TIGHT:
476         info->auth = VNC_PRIMARY_AUTH_TIGHT;
477         break;
478     case VNC_AUTH_ULTRA:
479         info->auth = VNC_PRIMARY_AUTH_ULTRA;
480         break;
481     case VNC_AUTH_TLS:
482         info->auth = VNC_PRIMARY_AUTH_TLS;
483         break;
484     case VNC_AUTH_VENCRYPT:
485         info->auth = VNC_PRIMARY_AUTH_VENCRYPT;
486         info->has_vencrypt = true;
487         switch (vd->subauth) {
488         case VNC_AUTH_VENCRYPT_PLAIN:
489             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
490             break;
491         case VNC_AUTH_VENCRYPT_TLSNONE:
492             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
493             break;
494         case VNC_AUTH_VENCRYPT_TLSVNC:
495             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
496             break;
497         case VNC_AUTH_VENCRYPT_TLSPLAIN:
498             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
499             break;
500         case VNC_AUTH_VENCRYPT_X509NONE:
501             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
502             break;
503         case VNC_AUTH_VENCRYPT_X509VNC:
504             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
505             break;
506         case VNC_AUTH_VENCRYPT_X509PLAIN:
507             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
508             break;
509         case VNC_AUTH_VENCRYPT_TLSSASL:
510             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
511             break;
512         case VNC_AUTH_VENCRYPT_X509SASL:
513             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
514             break;
515         default:
516             info->has_vencrypt = false;
517             break;
518         }
519         break;
520     case VNC_AUTH_SASL:
521         info->auth = VNC_PRIMARY_AUTH_SASL;
522         break;
523     case VNC_AUTH_NONE:
524     default:
525         info->auth = VNC_PRIMARY_AUTH_NONE;
526         break;
527     }
528 }
529 
530 VncInfo2List *qmp_query_vnc_servers(Error **errp)
531 {
532     VncInfo2List *item, *prev = NULL;
533     VncInfo2 *info;
534     VncDisplay *vd;
535     DeviceState *dev;
536 
537     QTAILQ_FOREACH(vd, &vnc_displays, next) {
538         info = g_new0(VncInfo2, 1);
539         info->id = g_strdup(vd->id);
540         info->clients = qmp_query_client_list(vd);
541         qmp_query_auth(vd, info);
542         if (vd->dcl.con) {
543             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
544                                                   "device", NULL));
545             info->has_display = true;
546             info->display = g_strdup(dev->id);
547         }
548         if (vd->lsock != NULL) {
549             info->server = qmp_query_server_entry(
550                 vd->lsock, false, info->server);
551         }
552         if (vd->lwebsock != NULL) {
553             info->server = qmp_query_server_entry(
554                 vd->lwebsock, true, info->server);
555         }
556 
557         item = g_new0(VncInfo2List, 1);
558         item->value = info;
559         item->next = prev;
560         prev = item;
561     }
562     return prev;
563 }
564 
565 /* TODO
566    1) Get the queue working for IO.
567    2) there is some weirdness when using the -S option (the screen is grey
568       and not totally invalidated
569    3) resolutions > 1024
570 */
571 
572 static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
573 static void vnc_disconnect_start(VncState *vs);
574 
575 static void vnc_colordepth(VncState *vs);
576 static void framebuffer_update_request(VncState *vs, int incremental,
577                                        int x_position, int y_position,
578                                        int w, int h);
579 static void vnc_refresh(DisplayChangeListener *dcl);
580 static int vnc_refresh_server_surface(VncDisplay *vd);
581 
582 static int vnc_width(VncDisplay *vd)
583 {
584     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
585                                        VNC_DIRTY_PIXELS_PER_BIT));
586 }
587 
588 static int vnc_height(VncDisplay *vd)
589 {
590     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
591 }
592 
593 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
594                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
595                                VncDisplay *vd,
596                                int x, int y, int w, int h)
597 {
598     int width = vnc_width(vd);
599     int height = vnc_height(vd);
600 
601     /* this is needed this to ensure we updated all affected
602      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
603     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
604     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
605 
606     x = MIN(x, width);
607     y = MIN(y, height);
608     w = MIN(x + w, width) - x;
609     h = MIN(y + h, height);
610 
611     for (; y < h; y++) {
612         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
613                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
614     }
615 }
616 
617 static void vnc_dpy_update(DisplayChangeListener *dcl,
618                            int x, int y, int w, int h)
619 {
620     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
621     struct VncSurface *s = &vd->guest;
622 
623     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
624 }
625 
626 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
627                             int32_t encoding)
628 {
629     vnc_write_u16(vs, x);
630     vnc_write_u16(vs, y);
631     vnc_write_u16(vs, w);
632     vnc_write_u16(vs, h);
633 
634     vnc_write_s32(vs, encoding);
635 }
636 
637 
638 static void vnc_desktop_resize(VncState *vs)
639 {
640     if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
641         return;
642     }
643     if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
644         vs->client_height == pixman_image_get_height(vs->vd->server)) {
645         return;
646     }
647     vs->client_width = pixman_image_get_width(vs->vd->server);
648     vs->client_height = pixman_image_get_height(vs->vd->server);
649     vnc_lock_output(vs);
650     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
651     vnc_write_u8(vs, 0);
652     vnc_write_u16(vs, 1); /* number of rects */
653     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
654                            VNC_ENCODING_DESKTOPRESIZE);
655     vnc_unlock_output(vs);
656     vnc_flush(vs);
657 }
658 
659 static void vnc_abort_display_jobs(VncDisplay *vd)
660 {
661     VncState *vs;
662 
663     QTAILQ_FOREACH(vs, &vd->clients, next) {
664         vnc_lock_output(vs);
665         vs->abort = true;
666         vnc_unlock_output(vs);
667     }
668     QTAILQ_FOREACH(vs, &vd->clients, next) {
669         vnc_jobs_join(vs);
670     }
671     QTAILQ_FOREACH(vs, &vd->clients, next) {
672         vnc_lock_output(vs);
673         vs->abort = false;
674         vnc_unlock_output(vs);
675     }
676 }
677 
678 int vnc_server_fb_stride(VncDisplay *vd)
679 {
680     return pixman_image_get_stride(vd->server);
681 }
682 
683 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
684 {
685     uint8_t *ptr;
686 
687     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
688     ptr += y * vnc_server_fb_stride(vd);
689     ptr += x * VNC_SERVER_FB_BYTES;
690     return ptr;
691 }
692 
693 static void vnc_update_server_surface(VncDisplay *vd)
694 {
695     int width, height;
696 
697     qemu_pixman_image_unref(vd->server);
698     vd->server = NULL;
699 
700     if (QTAILQ_EMPTY(&vd->clients)) {
701         return;
702     }
703 
704     width = vnc_width(vd);
705     height = vnc_height(vd);
706     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
707                                           width, height,
708                                           NULL, 0);
709 
710     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
711     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
712                        width, height);
713 }
714 
715 static void vnc_dpy_switch(DisplayChangeListener *dcl,
716                            DisplaySurface *surface)
717 {
718     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
719     VncState *vs;
720 
721     vnc_abort_display_jobs(vd);
722     vd->ds = surface;
723 
724     /* server surface */
725     vnc_update_server_surface(vd);
726 
727     /* guest surface */
728     qemu_pixman_image_unref(vd->guest.fb);
729     vd->guest.fb = pixman_image_ref(surface->image);
730     vd->guest.format = surface->format;
731 
732     QTAILQ_FOREACH(vs, &vd->clients, next) {
733         vnc_colordepth(vs);
734         vnc_desktop_resize(vs);
735         if (vs->vd->cursor) {
736             vnc_cursor_define(vs);
737         }
738         memset(vs->dirty, 0x00, sizeof(vs->dirty));
739         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
740                            vnc_width(vd),
741                            vnc_height(vd));
742     }
743 }
744 
745 /* fastest code */
746 static void vnc_write_pixels_copy(VncState *vs,
747                                   void *pixels, int size)
748 {
749     vnc_write(vs, pixels, size);
750 }
751 
752 /* slowest but generic code. */
753 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
754 {
755     uint8_t r, g, b;
756 
757 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
758     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
759     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
760     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
761 #else
762 # error need some bits here if you change VNC_SERVER_FB_FORMAT
763 #endif
764     v = (r << vs->client_pf.rshift) |
765         (g << vs->client_pf.gshift) |
766         (b << vs->client_pf.bshift);
767     switch (vs->client_pf.bytes_per_pixel) {
768     case 1:
769         buf[0] = v;
770         break;
771     case 2:
772         if (vs->client_be) {
773             buf[0] = v >> 8;
774             buf[1] = v;
775         } else {
776             buf[1] = v >> 8;
777             buf[0] = v;
778         }
779         break;
780     default:
781     case 4:
782         if (vs->client_be) {
783             buf[0] = v >> 24;
784             buf[1] = v >> 16;
785             buf[2] = v >> 8;
786             buf[3] = v;
787         } else {
788             buf[3] = v >> 24;
789             buf[2] = v >> 16;
790             buf[1] = v >> 8;
791             buf[0] = v;
792         }
793         break;
794     }
795 }
796 
797 static void vnc_write_pixels_generic(VncState *vs,
798                                      void *pixels1, int size)
799 {
800     uint8_t buf[4];
801 
802     if (VNC_SERVER_FB_BYTES == 4) {
803         uint32_t *pixels = pixels1;
804         int n, i;
805         n = size >> 2;
806         for (i = 0; i < n; i++) {
807             vnc_convert_pixel(vs, buf, pixels[i]);
808             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
809         }
810     }
811 }
812 
813 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
814 {
815     int i;
816     uint8_t *row;
817     VncDisplay *vd = vs->vd;
818 
819     row = vnc_server_fb_ptr(vd, x, y);
820     for (i = 0; i < h; i++) {
821         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
822         row += vnc_server_fb_stride(vd);
823     }
824     return 1;
825 }
826 
827 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
828 {
829     int n = 0;
830     bool encode_raw = false;
831     size_t saved_offs = vs->output.offset;
832 
833     switch(vs->vnc_encoding) {
834         case VNC_ENCODING_ZLIB:
835             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
836             break;
837         case VNC_ENCODING_HEXTILE:
838             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
839             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
840             break;
841         case VNC_ENCODING_TIGHT:
842             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
843             break;
844         case VNC_ENCODING_TIGHT_PNG:
845             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
846             break;
847         case VNC_ENCODING_ZRLE:
848             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
849             break;
850         case VNC_ENCODING_ZYWRLE:
851             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
852             break;
853         default:
854             encode_raw = true;
855             break;
856     }
857 
858     /* If the client has the same pixel format as our internal buffer and
859      * a RAW encoding would need less space fall back to RAW encoding to
860      * save bandwidth and processing power in the client. */
861     if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
862         12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
863         vs->output.offset = saved_offs;
864         encode_raw = true;
865     }
866 
867     if (encode_raw) {
868         vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
869         n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
870     }
871 
872     return n;
873 }
874 
875 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
876 {
877     /* send bitblit op to the vnc client */
878     vnc_lock_output(vs);
879     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
880     vnc_write_u8(vs, 0);
881     vnc_write_u16(vs, 1); /* number of rects */
882     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
883     vnc_write_u16(vs, src_x);
884     vnc_write_u16(vs, src_y);
885     vnc_unlock_output(vs);
886     vnc_flush(vs);
887 }
888 
889 static void vnc_dpy_copy(DisplayChangeListener *dcl,
890                          int src_x, int src_y,
891                          int dst_x, int dst_y, int w, int h)
892 {
893     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
894     VncState *vs, *vn;
895     uint8_t *src_row;
896     uint8_t *dst_row;
897     int i, x, y, pitch, inc, w_lim, s;
898     int cmp_bytes;
899 
900     if (!vd->server) {
901         /* no client connected */
902         return;
903     }
904 
905     vnc_refresh_server_surface(vd);
906     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
907         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
908             vs->force_update = 1;
909             vnc_update_client(vs, 1, true);
910             /* vs might be free()ed here */
911         }
912     }
913 
914     if (!vd->server) {
915         /* no client connected */
916         return;
917     }
918     /* do bitblit op on the local surface too */
919     pitch = vnc_server_fb_stride(vd);
920     src_row = vnc_server_fb_ptr(vd, src_x, src_y);
921     dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
922     y = dst_y;
923     inc = 1;
924     if (dst_y > src_y) {
925         /* copy backwards */
926         src_row += pitch * (h-1);
927         dst_row += pitch * (h-1);
928         pitch = -pitch;
929         y = dst_y + h - 1;
930         inc = -1;
931     }
932     w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
933     if (w_lim < 0) {
934         w_lim = w;
935     } else {
936         w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
937     }
938     for (i = 0; i < h; i++) {
939         for (x = 0; x <= w_lim;
940                 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
941             if (x == w_lim) {
942                 if ((s = w - w_lim) == 0)
943                     break;
944             } else if (!x) {
945                 s = (VNC_DIRTY_PIXELS_PER_BIT -
946                     (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
947                 s = MIN(s, w_lim);
948             } else {
949                 s = VNC_DIRTY_PIXELS_PER_BIT;
950             }
951             cmp_bytes = s * VNC_SERVER_FB_BYTES;
952             if (memcmp(src_row, dst_row, cmp_bytes) == 0)
953                 continue;
954             memmove(dst_row, src_row, cmp_bytes);
955             QTAILQ_FOREACH(vs, &vd->clients, next) {
956                 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
957                     set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
958                             vs->dirty[y]);
959                 }
960             }
961         }
962         src_row += pitch - w * VNC_SERVER_FB_BYTES;
963         dst_row += pitch - w * VNC_SERVER_FB_BYTES;
964         y += inc;
965     }
966 
967     QTAILQ_FOREACH(vs, &vd->clients, next) {
968         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
969             vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
970         }
971     }
972 }
973 
974 static void vnc_mouse_set(DisplayChangeListener *dcl,
975                           int x, int y, int visible)
976 {
977     /* can we ask the client(s) to move the pointer ??? */
978 }
979 
980 static int vnc_cursor_define(VncState *vs)
981 {
982     QEMUCursor *c = vs->vd->cursor;
983     int isize;
984 
985     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
986         vnc_lock_output(vs);
987         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
988         vnc_write_u8(vs,  0);  /*  padding     */
989         vnc_write_u16(vs, 1);  /*  # of rects  */
990         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
991                                VNC_ENCODING_RICH_CURSOR);
992         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
993         vnc_write_pixels_generic(vs, c->data, isize);
994         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
995         vnc_unlock_output(vs);
996         return 0;
997     }
998     return -1;
999 }
1000 
1001 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
1002                                   QEMUCursor *c)
1003 {
1004     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
1005     VncState *vs;
1006 
1007     cursor_put(vd->cursor);
1008     g_free(vd->cursor_mask);
1009 
1010     vd->cursor = c;
1011     cursor_get(vd->cursor);
1012     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
1013     vd->cursor_mask = g_malloc0(vd->cursor_msize);
1014     cursor_get_mono_mask(c, 0, vd->cursor_mask);
1015 
1016     QTAILQ_FOREACH(vs, &vd->clients, next) {
1017         vnc_cursor_define(vs);
1018     }
1019 }
1020 
1021 static int find_and_clear_dirty_height(VncState *vs,
1022                                        int y, int last_x, int x, int height)
1023 {
1024     int h;
1025 
1026     for (h = 1; h < (height - y); h++) {
1027         if (!test_bit(last_x, vs->dirty[y + h])) {
1028             break;
1029         }
1030         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1031     }
1032 
1033     return h;
1034 }
1035 
1036 static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
1037 {
1038     if (vs->disconnecting) {
1039         vnc_disconnect_finish(vs);
1040         return 0;
1041     }
1042 
1043     vs->has_dirty += has_dirty;
1044     if (vs->need_update && !vs->disconnecting) {
1045         VncDisplay *vd = vs->vd;
1046         VncJob *job;
1047         int y;
1048         int height, width;
1049         int n = 0;
1050 
1051         if (vs->output.offset && !vs->audio_cap && !vs->force_update)
1052             /* kernel send buffers are full -> drop frames to throttle */
1053             return 0;
1054 
1055         if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)
1056             return 0;
1057 
1058         /*
1059          * Send screen updates to the vnc client using the server
1060          * surface and server dirty map.  guest surface updates
1061          * happening in parallel don't disturb us, the next pass will
1062          * send them to the client.
1063          */
1064         job = vnc_job_new(vs);
1065 
1066         height = pixman_image_get_height(vd->server);
1067         width = pixman_image_get_width(vd->server);
1068 
1069         y = 0;
1070         for (;;) {
1071             int x, h;
1072             unsigned long x2;
1073             unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1074                                                  height * VNC_DIRTY_BPL(vs),
1075                                                  y * VNC_DIRTY_BPL(vs));
1076             if (offset == height * VNC_DIRTY_BPL(vs)) {
1077                 /* no more dirty bits */
1078                 break;
1079             }
1080             y = offset / VNC_DIRTY_BPL(vs);
1081             x = offset % VNC_DIRTY_BPL(vs);
1082             x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1083                                     VNC_DIRTY_BPL(vs), x);
1084             bitmap_clear(vs->dirty[y], x, x2 - x);
1085             h = find_and_clear_dirty_height(vs, y, x, x2, height);
1086             x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1087             if (x2 > x) {
1088                 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1089                                       (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1090             }
1091             if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1092                 y += h;
1093                 if (y == height) {
1094                     break;
1095                 }
1096             }
1097         }
1098 
1099         vnc_job_push(job);
1100         if (sync) {
1101             vnc_jobs_join(vs);
1102         }
1103         vs->force_update = 0;
1104         vs->has_dirty = 0;
1105         return n;
1106     }
1107 
1108     if (vs->disconnecting) {
1109         vnc_disconnect_finish(vs);
1110     } else if (sync) {
1111         vnc_jobs_join(vs);
1112     }
1113 
1114     return 0;
1115 }
1116 
1117 /* audio */
1118 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1119 {
1120     VncState *vs = opaque;
1121 
1122     switch (cmd) {
1123     case AUD_CNOTIFY_DISABLE:
1124         vnc_lock_output(vs);
1125         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1126         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1127         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1128         vnc_unlock_output(vs);
1129         vnc_flush(vs);
1130         break;
1131 
1132     case AUD_CNOTIFY_ENABLE:
1133         vnc_lock_output(vs);
1134         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1135         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1136         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1137         vnc_unlock_output(vs);
1138         vnc_flush(vs);
1139         break;
1140     }
1141 }
1142 
1143 static void audio_capture_destroy(void *opaque)
1144 {
1145 }
1146 
1147 static void audio_capture(void *opaque, void *buf, int size)
1148 {
1149     VncState *vs = opaque;
1150 
1151     vnc_lock_output(vs);
1152     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1153     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1154     vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1155     vnc_write_u32(vs, size);
1156     vnc_write(vs, buf, size);
1157     vnc_unlock_output(vs);
1158     vnc_flush(vs);
1159 }
1160 
1161 static void audio_add(VncState *vs)
1162 {
1163     struct audio_capture_ops ops;
1164 
1165     if (vs->audio_cap) {
1166         error_report("audio already running");
1167         return;
1168     }
1169 
1170     ops.notify = audio_capture_notify;
1171     ops.destroy = audio_capture_destroy;
1172     ops.capture = audio_capture;
1173 
1174     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1175     if (!vs->audio_cap) {
1176         error_report("Failed to add audio capture");
1177     }
1178 }
1179 
1180 static void audio_del(VncState *vs)
1181 {
1182     if (vs->audio_cap) {
1183         AUD_del_capture(vs->audio_cap, vs);
1184         vs->audio_cap = NULL;
1185     }
1186 }
1187 
1188 static void vnc_disconnect_start(VncState *vs)
1189 {
1190     if (vs->disconnecting) {
1191         return;
1192     }
1193     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1194     if (vs->ioc_tag) {
1195         g_source_remove(vs->ioc_tag);
1196     }
1197     qio_channel_close(vs->ioc, NULL);
1198     vs->disconnecting = TRUE;
1199 }
1200 
1201 void vnc_disconnect_finish(VncState *vs)
1202 {
1203     int i;
1204 
1205     vnc_jobs_join(vs); /* Wait encoding jobs */
1206 
1207     vnc_lock_output(vs);
1208     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1209 
1210     buffer_free(&vs->input);
1211     buffer_free(&vs->output);
1212 
1213     qapi_free_VncClientInfo(vs->info);
1214 
1215     vnc_zlib_clear(vs);
1216     vnc_tight_clear(vs);
1217     vnc_zrle_clear(vs);
1218 
1219 #ifdef CONFIG_VNC_SASL
1220     vnc_sasl_client_cleanup(vs);
1221 #endif /* CONFIG_VNC_SASL */
1222     audio_del(vs);
1223     vnc_release_modifiers(vs);
1224 
1225     if (vs->initialized) {
1226         QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1227         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1228         if (QTAILQ_EMPTY(&vs->vd->clients)) {
1229             /* last client gone */
1230             vnc_update_server_surface(vs->vd);
1231         }
1232     }
1233 
1234     if (vs->vd->lock_key_sync)
1235         qemu_remove_led_event_handler(vs->led);
1236     vnc_unlock_output(vs);
1237 
1238     qemu_mutex_destroy(&vs->output_mutex);
1239     if (vs->bh != NULL) {
1240         qemu_bh_delete(vs->bh);
1241     }
1242     buffer_free(&vs->jobs_buffer);
1243 
1244     for (i = 0; i < VNC_STAT_ROWS; ++i) {
1245         g_free(vs->lossy_rect[i]);
1246     }
1247     g_free(vs->lossy_rect);
1248 
1249     object_unref(OBJECT(vs->ioc));
1250     vs->ioc = NULL;
1251     object_unref(OBJECT(vs->sioc));
1252     vs->sioc = NULL;
1253     g_free(vs);
1254 }
1255 
1256 ssize_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
1257 {
1258     if (ret <= 0) {
1259         if (ret == 0) {
1260             VNC_DEBUG("Closing down client sock: EOF\n");
1261         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1262             VNC_DEBUG("Closing down client sock: ret %d (%s)\n",
1263                       ret, errp ? error_get_pretty(*errp) : "Unknown");
1264         }
1265 
1266         vnc_disconnect_start(vs);
1267         if (errp) {
1268             error_free(*errp);
1269             *errp = NULL;
1270         }
1271         return 0;
1272     }
1273     return ret;
1274 }
1275 
1276 
1277 void vnc_client_error(VncState *vs)
1278 {
1279     VNC_DEBUG("Closing down client sock: protocol error\n");
1280     vnc_disconnect_start(vs);
1281 }
1282 
1283 
1284 /*
1285  * Called to write a chunk of data to the client socket. The data may
1286  * be the raw data, or may have already been encoded by SASL.
1287  * The data will be written either straight onto the socket, or
1288  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1289  *
1290  * NB, it is theoretically possible to have 2 layers of encryption,
1291  * both SASL, and this TLS layer. It is highly unlikely in practice
1292  * though, since SASL encryption will typically be a no-op if TLS
1293  * is active
1294  *
1295  * Returns the number of bytes written, which may be less than
1296  * the requested 'datalen' if the socket would block. Returns
1297  * -1 on error, and disconnects the client socket.
1298  */
1299 ssize_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1300 {
1301     Error *err = NULL;
1302     ssize_t ret;
1303     ret = qio_channel_write(
1304         vs->ioc, (const char *)data, datalen, &err);
1305     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1306     return vnc_client_io_error(vs, ret, &err);
1307 }
1308 
1309 
1310 /*
1311  * Called to write buffered data to the client socket, when not
1312  * using any SASL SSF encryption layers. Will write as much data
1313  * as possible without blocking. If all buffered data is written,
1314  * will switch the FD poll() handler back to read monitoring.
1315  *
1316  * Returns the number of bytes written, which may be less than
1317  * the buffered output data if the socket would block. Returns
1318  * -1 on error, and disconnects the client socket.
1319  */
1320 static ssize_t vnc_client_write_plain(VncState *vs)
1321 {
1322     ssize_t ret;
1323 
1324 #ifdef CONFIG_VNC_SASL
1325     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1326               vs->output.buffer, vs->output.capacity, vs->output.offset,
1327               vs->sasl.waitWriteSSF);
1328 
1329     if (vs->sasl.conn &&
1330         vs->sasl.runSSF &&
1331         vs->sasl.waitWriteSSF) {
1332         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1333         if (ret)
1334             vs->sasl.waitWriteSSF -= ret;
1335     } else
1336 #endif /* CONFIG_VNC_SASL */
1337         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1338     if (!ret)
1339         return 0;
1340 
1341     buffer_advance(&vs->output, ret);
1342 
1343     if (vs->output.offset == 0) {
1344         if (vs->ioc_tag) {
1345             g_source_remove(vs->ioc_tag);
1346         }
1347         vs->ioc_tag = qio_channel_add_watch(
1348             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1349     }
1350 
1351     return ret;
1352 }
1353 
1354 
1355 /*
1356  * First function called whenever there is data to be written to
1357  * the client socket. Will delegate actual work according to whether
1358  * SASL SSF layers are enabled (thus requiring encryption calls)
1359  */
1360 static void vnc_client_write_locked(VncState *vs)
1361 {
1362 #ifdef CONFIG_VNC_SASL
1363     if (vs->sasl.conn &&
1364         vs->sasl.runSSF &&
1365         !vs->sasl.waitWriteSSF) {
1366         vnc_client_write_sasl(vs);
1367     } else
1368 #endif /* CONFIG_VNC_SASL */
1369     {
1370         vnc_client_write_plain(vs);
1371     }
1372 }
1373 
1374 static void vnc_client_write(VncState *vs)
1375 {
1376 
1377     vnc_lock_output(vs);
1378     if (vs->output.offset) {
1379         vnc_client_write_locked(vs);
1380     } else if (vs->ioc != NULL) {
1381         if (vs->ioc_tag) {
1382             g_source_remove(vs->ioc_tag);
1383         }
1384         vs->ioc_tag = qio_channel_add_watch(
1385             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1386     }
1387     vnc_unlock_output(vs);
1388 }
1389 
1390 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1391 {
1392     vs->read_handler = func;
1393     vs->read_handler_expect = expecting;
1394 }
1395 
1396 
1397 /*
1398  * Called to read a chunk of data from the client socket. The data may
1399  * be the raw data, or may need to be further decoded by SASL.
1400  * The data will be read either straight from to the socket, or
1401  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1402  *
1403  * NB, it is theoretically possible to have 2 layers of encryption,
1404  * both SASL, and this TLS layer. It is highly unlikely in practice
1405  * though, since SASL encryption will typically be a no-op if TLS
1406  * is active
1407  *
1408  * Returns the number of bytes read, which may be less than
1409  * the requested 'datalen' if the socket would block. Returns
1410  * -1 on error, and disconnects the client socket.
1411  */
1412 ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1413 {
1414     ssize_t ret;
1415     Error *err = NULL;
1416     ret = qio_channel_read(
1417         vs->ioc, (char *)data, datalen, &err);
1418     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1419     return vnc_client_io_error(vs, ret, &err);
1420 }
1421 
1422 
1423 /*
1424  * Called to read data from the client socket to the input buffer,
1425  * when not using any SASL SSF encryption layers. Will read as much
1426  * data as possible without blocking.
1427  *
1428  * Returns the number of bytes read. Returns -1 on error, and
1429  * disconnects the client socket.
1430  */
1431 static ssize_t vnc_client_read_plain(VncState *vs)
1432 {
1433     ssize_t ret;
1434     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1435               vs->input.buffer, vs->input.capacity, vs->input.offset);
1436     buffer_reserve(&vs->input, 4096);
1437     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1438     if (!ret)
1439         return 0;
1440     vs->input.offset += ret;
1441     return ret;
1442 }
1443 
1444 static void vnc_jobs_bh(void *opaque)
1445 {
1446     VncState *vs = opaque;
1447 
1448     vnc_jobs_consume_buffer(vs);
1449 }
1450 
1451 /*
1452  * First function called whenever there is more data to be read from
1453  * the client socket. Will delegate actual work according to whether
1454  * SASL SSF layers are enabled (thus requiring decryption calls)
1455  * Returns 0 on success, -1 if client disconnected
1456  */
1457 static int vnc_client_read(VncState *vs)
1458 {
1459     ssize_t ret;
1460 
1461 #ifdef CONFIG_VNC_SASL
1462     if (vs->sasl.conn && vs->sasl.runSSF)
1463         ret = vnc_client_read_sasl(vs);
1464     else
1465 #endif /* CONFIG_VNC_SASL */
1466         ret = vnc_client_read_plain(vs);
1467     if (!ret) {
1468         if (vs->disconnecting) {
1469             vnc_disconnect_finish(vs);
1470             return -1;
1471         }
1472         return 0;
1473     }
1474 
1475     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1476         size_t len = vs->read_handler_expect;
1477         int ret;
1478 
1479         ret = vs->read_handler(vs, vs->input.buffer, len);
1480         if (vs->disconnecting) {
1481             vnc_disconnect_finish(vs);
1482             return -1;
1483         }
1484 
1485         if (!ret) {
1486             buffer_advance(&vs->input, len);
1487         } else {
1488             vs->read_handler_expect = ret;
1489         }
1490     }
1491     return 0;
1492 }
1493 
1494 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1495                        GIOCondition condition, void *opaque)
1496 {
1497     VncState *vs = opaque;
1498     if (condition & G_IO_IN) {
1499         if (vnc_client_read(vs) < 0) {
1500             return TRUE;
1501         }
1502     }
1503     if (condition & G_IO_OUT) {
1504         vnc_client_write(vs);
1505     }
1506     return TRUE;
1507 }
1508 
1509 
1510 void vnc_write(VncState *vs, const void *data, size_t len)
1511 {
1512     buffer_reserve(&vs->output, len);
1513 
1514     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1515         if (vs->ioc_tag) {
1516             g_source_remove(vs->ioc_tag);
1517         }
1518         vs->ioc_tag = qio_channel_add_watch(
1519             vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1520     }
1521 
1522     buffer_append(&vs->output, data, len);
1523 }
1524 
1525 void vnc_write_s32(VncState *vs, int32_t value)
1526 {
1527     vnc_write_u32(vs, *(uint32_t *)&value);
1528 }
1529 
1530 void vnc_write_u32(VncState *vs, uint32_t value)
1531 {
1532     uint8_t buf[4];
1533 
1534     buf[0] = (value >> 24) & 0xFF;
1535     buf[1] = (value >> 16) & 0xFF;
1536     buf[2] = (value >>  8) & 0xFF;
1537     buf[3] = value & 0xFF;
1538 
1539     vnc_write(vs, buf, 4);
1540 }
1541 
1542 void vnc_write_u16(VncState *vs, uint16_t value)
1543 {
1544     uint8_t buf[2];
1545 
1546     buf[0] = (value >> 8) & 0xFF;
1547     buf[1] = value & 0xFF;
1548 
1549     vnc_write(vs, buf, 2);
1550 }
1551 
1552 void vnc_write_u8(VncState *vs, uint8_t value)
1553 {
1554     vnc_write(vs, (char *)&value, 1);
1555 }
1556 
1557 void vnc_flush(VncState *vs)
1558 {
1559     vnc_lock_output(vs);
1560     if (vs->ioc != NULL && vs->output.offset) {
1561         vnc_client_write_locked(vs);
1562     }
1563     vnc_unlock_output(vs);
1564 }
1565 
1566 static uint8_t read_u8(uint8_t *data, size_t offset)
1567 {
1568     return data[offset];
1569 }
1570 
1571 static uint16_t read_u16(uint8_t *data, size_t offset)
1572 {
1573     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1574 }
1575 
1576 static int32_t read_s32(uint8_t *data, size_t offset)
1577 {
1578     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1579                      (data[offset + 2] << 8) | data[offset + 3]);
1580 }
1581 
1582 uint32_t read_u32(uint8_t *data, size_t offset)
1583 {
1584     return ((data[offset] << 24) | (data[offset + 1] << 16) |
1585             (data[offset + 2] << 8) | data[offset + 3]);
1586 }
1587 
1588 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1589 {
1590 }
1591 
1592 static void check_pointer_type_change(Notifier *notifier, void *data)
1593 {
1594     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1595     int absolute = qemu_input_is_absolute();
1596 
1597     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1598         vnc_lock_output(vs);
1599         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1600         vnc_write_u8(vs, 0);
1601         vnc_write_u16(vs, 1);
1602         vnc_framebuffer_update(vs, absolute, 0,
1603                                pixman_image_get_width(vs->vd->server),
1604                                pixman_image_get_height(vs->vd->server),
1605                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1606         vnc_unlock_output(vs);
1607         vnc_flush(vs);
1608     }
1609     vs->absolute = absolute;
1610 }
1611 
1612 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1613 {
1614     static uint32_t bmap[INPUT_BUTTON__MAX] = {
1615         [INPUT_BUTTON_LEFT]       = 0x01,
1616         [INPUT_BUTTON_MIDDLE]     = 0x02,
1617         [INPUT_BUTTON_RIGHT]      = 0x04,
1618         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1619         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1620     };
1621     QemuConsole *con = vs->vd->dcl.con;
1622     int width = pixman_image_get_width(vs->vd->server);
1623     int height = pixman_image_get_height(vs->vd->server);
1624 
1625     if (vs->last_bmask != button_mask) {
1626         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1627         vs->last_bmask = button_mask;
1628     }
1629 
1630     if (vs->absolute) {
1631         qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
1632         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
1633     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1634         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1635         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1636     } else {
1637         if (vs->last_x != -1) {
1638             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1639             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1640         }
1641         vs->last_x = x;
1642         vs->last_y = y;
1643     }
1644     qemu_input_event_sync();
1645 }
1646 
1647 static void reset_keys(VncState *vs)
1648 {
1649     int i;
1650     for(i = 0; i < 256; i++) {
1651         if (vs->modifiers_state[i]) {
1652             qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1653             qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1654             vs->modifiers_state[i] = 0;
1655         }
1656     }
1657 }
1658 
1659 static void press_key(VncState *vs, int keysym)
1660 {
1661     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1662     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1663     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1664     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1665     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1666 }
1667 
1668 static int current_led_state(VncState *vs)
1669 {
1670     int ledstate = 0;
1671 
1672     if (vs->modifiers_state[0x46]) {
1673         ledstate |= QEMU_SCROLL_LOCK_LED;
1674     }
1675     if (vs->modifiers_state[0x45]) {
1676         ledstate |= QEMU_NUM_LOCK_LED;
1677     }
1678     if (vs->modifiers_state[0x3a]) {
1679         ledstate |= QEMU_CAPS_LOCK_LED;
1680     }
1681 
1682     return ledstate;
1683 }
1684 
1685 static void vnc_led_state_change(VncState *vs)
1686 {
1687     int ledstate = 0;
1688 
1689     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1690         return;
1691     }
1692 
1693     ledstate = current_led_state(vs);
1694     vnc_lock_output(vs);
1695     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1696     vnc_write_u8(vs, 0);
1697     vnc_write_u16(vs, 1);
1698     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1699     vnc_write_u8(vs, ledstate);
1700     vnc_unlock_output(vs);
1701     vnc_flush(vs);
1702 }
1703 
1704 static void kbd_leds(void *opaque, int ledstate)
1705 {
1706     VncState *vs = opaque;
1707     int caps, num, scr;
1708     bool has_changed = (ledstate != current_led_state(vs));
1709 
1710     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1711                              (ledstate & QEMU_NUM_LOCK_LED),
1712                              (ledstate & QEMU_SCROLL_LOCK_LED));
1713 
1714     caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1715     num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
1716     scr  = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
1717 
1718     if (vs->modifiers_state[0x3a] != caps) {
1719         vs->modifiers_state[0x3a] = caps;
1720     }
1721     if (vs->modifiers_state[0x45] != num) {
1722         vs->modifiers_state[0x45] = num;
1723     }
1724     if (vs->modifiers_state[0x46] != scr) {
1725         vs->modifiers_state[0x46] = scr;
1726     }
1727 
1728     /* Sending the current led state message to the client */
1729     if (has_changed) {
1730         vnc_led_state_change(vs);
1731     }
1732 }
1733 
1734 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1735 {
1736     /* QEMU console switch */
1737     switch(keycode) {
1738     case 0x2a:                          /* Left Shift */
1739     case 0x36:                          /* Right Shift */
1740     case 0x1d:                          /* Left CTRL */
1741     case 0x9d:                          /* Right CTRL */
1742     case 0x38:                          /* Left ALT */
1743     case 0xb8:                          /* Right ALT */
1744         if (down)
1745             vs->modifiers_state[keycode] = 1;
1746         else
1747             vs->modifiers_state[keycode] = 0;
1748         break;
1749     case 0x02 ... 0x0a: /* '1' to '9' keys */
1750         if (vs->vd->dcl.con == NULL &&
1751             down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1752             /* Reset the modifiers sent to the current console */
1753             reset_keys(vs);
1754             console_select(keycode - 0x02);
1755             return;
1756         }
1757         break;
1758     case 0x3a:                        /* CapsLock */
1759     case 0x45:                        /* NumLock */
1760         if (down)
1761             vs->modifiers_state[keycode] ^= 1;
1762         break;
1763     }
1764 
1765     /* Turn off the lock state sync logic if the client support the led
1766        state extension.
1767     */
1768     if (down && vs->vd->lock_key_sync &&
1769         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1770         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1771         /* If the numlock state needs to change then simulate an additional
1772            keypress before sending this one.  This will happen if the user
1773            toggles numlock away from the VNC window.
1774         */
1775         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1776             if (!vs->modifiers_state[0x45]) {
1777                 trace_vnc_key_sync_numlock(true);
1778                 vs->modifiers_state[0x45] = 1;
1779                 press_key(vs, 0xff7f);
1780             }
1781         } else {
1782             if (vs->modifiers_state[0x45]) {
1783                 trace_vnc_key_sync_numlock(false);
1784                 vs->modifiers_state[0x45] = 0;
1785                 press_key(vs, 0xff7f);
1786             }
1787         }
1788     }
1789 
1790     if (down && vs->vd->lock_key_sync &&
1791         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1792         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1793         /* If the capslock state needs to change then simulate an additional
1794            keypress before sending this one.  This will happen if the user
1795            toggles capslock away from the VNC window.
1796         */
1797         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1798         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1799         int capslock = !!(vs->modifiers_state[0x3a]);
1800         if (capslock) {
1801             if (uppercase == shift) {
1802                 trace_vnc_key_sync_capslock(false);
1803                 vs->modifiers_state[0x3a] = 0;
1804                 press_key(vs, 0xffe5);
1805             }
1806         } else {
1807             if (uppercase != shift) {
1808                 trace_vnc_key_sync_capslock(true);
1809                 vs->modifiers_state[0x3a] = 1;
1810                 press_key(vs, 0xffe5);
1811             }
1812         }
1813     }
1814 
1815     if (qemu_console_is_graphic(NULL)) {
1816         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1817         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1818     } else {
1819         bool numlock = vs->modifiers_state[0x45];
1820         bool control = (vs->modifiers_state[0x1d] ||
1821                         vs->modifiers_state[0x9d]);
1822         /* QEMU console emulation */
1823         if (down) {
1824             switch (keycode) {
1825             case 0x2a:                          /* Left Shift */
1826             case 0x36:                          /* Right Shift */
1827             case 0x1d:                          /* Left CTRL */
1828             case 0x9d:                          /* Right CTRL */
1829             case 0x38:                          /* Left ALT */
1830             case 0xb8:                          /* Right ALT */
1831                 break;
1832             case 0xc8:
1833                 kbd_put_keysym(QEMU_KEY_UP);
1834                 break;
1835             case 0xd0:
1836                 kbd_put_keysym(QEMU_KEY_DOWN);
1837                 break;
1838             case 0xcb:
1839                 kbd_put_keysym(QEMU_KEY_LEFT);
1840                 break;
1841             case 0xcd:
1842                 kbd_put_keysym(QEMU_KEY_RIGHT);
1843                 break;
1844             case 0xd3:
1845                 kbd_put_keysym(QEMU_KEY_DELETE);
1846                 break;
1847             case 0xc7:
1848                 kbd_put_keysym(QEMU_KEY_HOME);
1849                 break;
1850             case 0xcf:
1851                 kbd_put_keysym(QEMU_KEY_END);
1852                 break;
1853             case 0xc9:
1854                 kbd_put_keysym(QEMU_KEY_PAGEUP);
1855                 break;
1856             case 0xd1:
1857                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1858                 break;
1859 
1860             case 0x47:
1861                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1862                 break;
1863             case 0x48:
1864                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1865                 break;
1866             case 0x49:
1867                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1868                 break;
1869             case 0x4b:
1870                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1871                 break;
1872             case 0x4c:
1873                 kbd_put_keysym('5');
1874                 break;
1875             case 0x4d:
1876                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1877                 break;
1878             case 0x4f:
1879                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1880                 break;
1881             case 0x50:
1882                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1883                 break;
1884             case 0x51:
1885                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1886                 break;
1887             case 0x52:
1888                 kbd_put_keysym('0');
1889                 break;
1890             case 0x53:
1891                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1892                 break;
1893 
1894             case 0xb5:
1895                 kbd_put_keysym('/');
1896                 break;
1897             case 0x37:
1898                 kbd_put_keysym('*');
1899                 break;
1900             case 0x4a:
1901                 kbd_put_keysym('-');
1902                 break;
1903             case 0x4e:
1904                 kbd_put_keysym('+');
1905                 break;
1906             case 0x9c:
1907                 kbd_put_keysym('\n');
1908                 break;
1909 
1910             default:
1911                 if (control) {
1912                     kbd_put_keysym(sym & 0x1f);
1913                 } else {
1914                     kbd_put_keysym(sym);
1915                 }
1916                 break;
1917             }
1918         }
1919     }
1920 }
1921 
1922 static void vnc_release_modifiers(VncState *vs)
1923 {
1924     static const int keycodes[] = {
1925         /* shift, control, alt keys, both left & right */
1926         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1927     };
1928     int i, keycode;
1929 
1930     if (!qemu_console_is_graphic(NULL)) {
1931         return;
1932     }
1933     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1934         keycode = keycodes[i];
1935         if (!vs->modifiers_state[keycode]) {
1936             continue;
1937         }
1938         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1939         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1940     }
1941 }
1942 
1943 static const char *code2name(int keycode)
1944 {
1945     return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
1946 }
1947 
1948 static void key_event(VncState *vs, int down, uint32_t sym)
1949 {
1950     int keycode;
1951     int lsym = sym;
1952 
1953     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1954         lsym = lsym - 'A' + 'a';
1955     }
1956 
1957     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1958     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1959     do_key_event(vs, down, keycode, sym);
1960 }
1961 
1962 static void ext_key_event(VncState *vs, int down,
1963                           uint32_t sym, uint16_t keycode)
1964 {
1965     /* if the user specifies a keyboard layout, always use it */
1966     if (keyboard_layout) {
1967         key_event(vs, down, sym);
1968     } else {
1969         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
1970         do_key_event(vs, down, keycode, sym);
1971     }
1972 }
1973 
1974 static void framebuffer_update_request(VncState *vs, int incremental,
1975                                        int x, int y, int w, int h)
1976 {
1977     vs->need_update = 1;
1978 
1979     if (incremental) {
1980         return;
1981     }
1982 
1983     vs->force_update = 1;
1984     vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
1985 }
1986 
1987 static void send_ext_key_event_ack(VncState *vs)
1988 {
1989     vnc_lock_output(vs);
1990     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1991     vnc_write_u8(vs, 0);
1992     vnc_write_u16(vs, 1);
1993     vnc_framebuffer_update(vs, 0, 0,
1994                            pixman_image_get_width(vs->vd->server),
1995                            pixman_image_get_height(vs->vd->server),
1996                            VNC_ENCODING_EXT_KEY_EVENT);
1997     vnc_unlock_output(vs);
1998     vnc_flush(vs);
1999 }
2000 
2001 static void send_ext_audio_ack(VncState *vs)
2002 {
2003     vnc_lock_output(vs);
2004     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2005     vnc_write_u8(vs, 0);
2006     vnc_write_u16(vs, 1);
2007     vnc_framebuffer_update(vs, 0, 0,
2008                            pixman_image_get_width(vs->vd->server),
2009                            pixman_image_get_height(vs->vd->server),
2010                            VNC_ENCODING_AUDIO);
2011     vnc_unlock_output(vs);
2012     vnc_flush(vs);
2013 }
2014 
2015 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2016 {
2017     int i;
2018     unsigned int enc = 0;
2019 
2020     vs->features = 0;
2021     vs->vnc_encoding = 0;
2022     vs->tight.compression = 9;
2023     vs->tight.quality = -1; /* Lossless by default */
2024     vs->absolute = -1;
2025 
2026     /*
2027      * Start from the end because the encodings are sent in order of preference.
2028      * This way the preferred encoding (first encoding defined in the array)
2029      * will be set at the end of the loop.
2030      */
2031     for (i = n_encodings - 1; i >= 0; i--) {
2032         enc = encodings[i];
2033         switch (enc) {
2034         case VNC_ENCODING_RAW:
2035             vs->vnc_encoding = enc;
2036             break;
2037         case VNC_ENCODING_COPYRECT:
2038             vs->features |= VNC_FEATURE_COPYRECT_MASK;
2039             break;
2040         case VNC_ENCODING_HEXTILE:
2041             vs->features |= VNC_FEATURE_HEXTILE_MASK;
2042             vs->vnc_encoding = enc;
2043             break;
2044         case VNC_ENCODING_TIGHT:
2045             vs->features |= VNC_FEATURE_TIGHT_MASK;
2046             vs->vnc_encoding = enc;
2047             break;
2048 #ifdef CONFIG_VNC_PNG
2049         case VNC_ENCODING_TIGHT_PNG:
2050             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2051             vs->vnc_encoding = enc;
2052             break;
2053 #endif
2054         case VNC_ENCODING_ZLIB:
2055             vs->features |= VNC_FEATURE_ZLIB_MASK;
2056             vs->vnc_encoding = enc;
2057             break;
2058         case VNC_ENCODING_ZRLE:
2059             vs->features |= VNC_FEATURE_ZRLE_MASK;
2060             vs->vnc_encoding = enc;
2061             break;
2062         case VNC_ENCODING_ZYWRLE:
2063             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2064             vs->vnc_encoding = enc;
2065             break;
2066         case VNC_ENCODING_DESKTOPRESIZE:
2067             vs->features |= VNC_FEATURE_RESIZE_MASK;
2068             break;
2069         case VNC_ENCODING_POINTER_TYPE_CHANGE:
2070             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2071             break;
2072         case VNC_ENCODING_RICH_CURSOR:
2073             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2074             if (vs->vd->cursor) {
2075                 vnc_cursor_define(vs);
2076             }
2077             break;
2078         case VNC_ENCODING_EXT_KEY_EVENT:
2079             send_ext_key_event_ack(vs);
2080             break;
2081         case VNC_ENCODING_AUDIO:
2082             send_ext_audio_ack(vs);
2083             break;
2084         case VNC_ENCODING_WMVi:
2085             vs->features |= VNC_FEATURE_WMVI_MASK;
2086             break;
2087         case VNC_ENCODING_LED_STATE:
2088             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2089             break;
2090         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2091             vs->tight.compression = (enc & 0x0F);
2092             break;
2093         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2094             if (vs->vd->lossy) {
2095                 vs->tight.quality = (enc & 0x0F);
2096             }
2097             break;
2098         default:
2099             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2100             break;
2101         }
2102     }
2103     vnc_desktop_resize(vs);
2104     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2105     vnc_led_state_change(vs);
2106 }
2107 
2108 static void set_pixel_conversion(VncState *vs)
2109 {
2110     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2111 
2112     if (fmt == VNC_SERVER_FB_FORMAT) {
2113         vs->write_pixels = vnc_write_pixels_copy;
2114         vnc_hextile_set_pixel_conversion(vs, 0);
2115     } else {
2116         vs->write_pixels = vnc_write_pixels_generic;
2117         vnc_hextile_set_pixel_conversion(vs, 1);
2118     }
2119 }
2120 
2121 static void send_color_map(VncState *vs)
2122 {
2123     int i;
2124 
2125     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2126     vnc_write_u8(vs,  0);    /* padding     */
2127     vnc_write_u16(vs, 0);    /* first color */
2128     vnc_write_u16(vs, 256);  /* # of colors */
2129 
2130     for (i = 0; i < 256; i++) {
2131         PixelFormat *pf = &vs->client_pf;
2132 
2133         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2134         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2135         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2136     }
2137 }
2138 
2139 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2140                              int big_endian_flag, int true_color_flag,
2141                              int red_max, int green_max, int blue_max,
2142                              int red_shift, int green_shift, int blue_shift)
2143 {
2144     if (!true_color_flag) {
2145         /* Expose a reasonable default 256 color map */
2146         bits_per_pixel = 8;
2147         red_max = 7;
2148         green_max = 7;
2149         blue_max = 3;
2150         red_shift = 0;
2151         green_shift = 3;
2152         blue_shift = 6;
2153     }
2154 
2155     switch (bits_per_pixel) {
2156     case 8:
2157     case 16:
2158     case 32:
2159         break;
2160     default:
2161         vnc_client_error(vs);
2162         return;
2163     }
2164 
2165     vs->client_pf.rmax = red_max ? red_max : 0xFF;
2166     vs->client_pf.rbits = hweight_long(red_max);
2167     vs->client_pf.rshift = red_shift;
2168     vs->client_pf.rmask = red_max << red_shift;
2169     vs->client_pf.gmax = green_max ? green_max : 0xFF;
2170     vs->client_pf.gbits = hweight_long(green_max);
2171     vs->client_pf.gshift = green_shift;
2172     vs->client_pf.gmask = green_max << green_shift;
2173     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2174     vs->client_pf.bbits = hweight_long(blue_max);
2175     vs->client_pf.bshift = blue_shift;
2176     vs->client_pf.bmask = blue_max << blue_shift;
2177     vs->client_pf.bits_per_pixel = bits_per_pixel;
2178     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2179     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2180     vs->client_be = big_endian_flag;
2181 
2182     if (!true_color_flag) {
2183         send_color_map(vs);
2184     }
2185 
2186     set_pixel_conversion(vs);
2187 
2188     graphic_hw_invalidate(vs->vd->dcl.con);
2189     graphic_hw_update(vs->vd->dcl.con);
2190 }
2191 
2192 static void pixel_format_message (VncState *vs) {
2193     char pad[3] = { 0, 0, 0 };
2194 
2195     vs->client_pf = qemu_default_pixelformat(32);
2196 
2197     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2198     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2199 
2200 #ifdef HOST_WORDS_BIGENDIAN
2201     vnc_write_u8(vs, 1);             /* big-endian-flag */
2202 #else
2203     vnc_write_u8(vs, 0);             /* big-endian-flag */
2204 #endif
2205     vnc_write_u8(vs, 1);             /* true-color-flag */
2206     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
2207     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
2208     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
2209     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
2210     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
2211     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
2212     vnc_write(vs, pad, 3);           /* padding */
2213 
2214     vnc_hextile_set_pixel_conversion(vs, 0);
2215     vs->write_pixels = vnc_write_pixels_copy;
2216 }
2217 
2218 static void vnc_colordepth(VncState *vs)
2219 {
2220     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2221         /* Sending a WMVi message to notify the client*/
2222         vnc_lock_output(vs);
2223         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2224         vnc_write_u8(vs, 0);
2225         vnc_write_u16(vs, 1); /* number of rects */
2226         vnc_framebuffer_update(vs, 0, 0,
2227                                pixman_image_get_width(vs->vd->server),
2228                                pixman_image_get_height(vs->vd->server),
2229                                VNC_ENCODING_WMVi);
2230         pixel_format_message(vs);
2231         vnc_unlock_output(vs);
2232         vnc_flush(vs);
2233     } else {
2234         set_pixel_conversion(vs);
2235     }
2236 }
2237 
2238 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2239 {
2240     int i;
2241     uint16_t limit;
2242     VncDisplay *vd = vs->vd;
2243 
2244     if (data[0] > 3) {
2245         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2246     }
2247 
2248     switch (data[0]) {
2249     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2250         if (len == 1)
2251             return 20;
2252 
2253         set_pixel_format(vs, read_u8(data, 4),
2254                          read_u8(data, 6), read_u8(data, 7),
2255                          read_u16(data, 8), read_u16(data, 10),
2256                          read_u16(data, 12), read_u8(data, 14),
2257                          read_u8(data, 15), read_u8(data, 16));
2258         break;
2259     case VNC_MSG_CLIENT_SET_ENCODINGS:
2260         if (len == 1)
2261             return 4;
2262 
2263         if (len == 4) {
2264             limit = read_u16(data, 2);
2265             if (limit > 0)
2266                 return 4 + (limit * 4);
2267         } else
2268             limit = read_u16(data, 2);
2269 
2270         for (i = 0; i < limit; i++) {
2271             int32_t val = read_s32(data, 4 + (i * 4));
2272             memcpy(data + 4 + (i * 4), &val, sizeof(val));
2273         }
2274 
2275         set_encodings(vs, (int32_t *)(data + 4), limit);
2276         break;
2277     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2278         if (len == 1)
2279             return 10;
2280 
2281         framebuffer_update_request(vs,
2282                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2283                                    read_u16(data, 6), read_u16(data, 8));
2284         break;
2285     case VNC_MSG_CLIENT_KEY_EVENT:
2286         if (len == 1)
2287             return 8;
2288 
2289         key_event(vs, read_u8(data, 1), read_u32(data, 4));
2290         break;
2291     case VNC_MSG_CLIENT_POINTER_EVENT:
2292         if (len == 1)
2293             return 6;
2294 
2295         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2296         break;
2297     case VNC_MSG_CLIENT_CUT_TEXT:
2298         if (len == 1) {
2299             return 8;
2300         }
2301         if (len == 8) {
2302             uint32_t dlen = read_u32(data, 4);
2303             if (dlen > (1 << 20)) {
2304                 error_report("vnc: client_cut_text msg payload has %u bytes"
2305                              " which exceeds our limit of 1MB.", dlen);
2306                 vnc_client_error(vs);
2307                 break;
2308             }
2309             if (dlen > 0) {
2310                 return 8 + dlen;
2311             }
2312         }
2313 
2314         client_cut_text(vs, read_u32(data, 4), data + 8);
2315         break;
2316     case VNC_MSG_CLIENT_QEMU:
2317         if (len == 1)
2318             return 2;
2319 
2320         switch (read_u8(data, 1)) {
2321         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2322             if (len == 2)
2323                 return 12;
2324 
2325             ext_key_event(vs, read_u16(data, 2),
2326                           read_u32(data, 4), read_u32(data, 8));
2327             break;
2328         case VNC_MSG_CLIENT_QEMU_AUDIO:
2329             if (len == 2)
2330                 return 4;
2331 
2332             switch (read_u16 (data, 2)) {
2333             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2334                 audio_add(vs);
2335                 break;
2336             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2337                 audio_del(vs);
2338                 break;
2339             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2340                 if (len == 4)
2341                     return 10;
2342                 switch (read_u8(data, 4)) {
2343                 case 0: vs->as.fmt = AUD_FMT_U8; break;
2344                 case 1: vs->as.fmt = AUD_FMT_S8; break;
2345                 case 2: vs->as.fmt = AUD_FMT_U16; break;
2346                 case 3: vs->as.fmt = AUD_FMT_S16; break;
2347                 case 4: vs->as.fmt = AUD_FMT_U32; break;
2348                 case 5: vs->as.fmt = AUD_FMT_S32; break;
2349                 default:
2350                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2351                     vnc_client_error(vs);
2352                     break;
2353                 }
2354                 vs->as.nchannels = read_u8(data, 5);
2355                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2356                     VNC_DEBUG("Invalid audio channel coount %d\n",
2357                               read_u8(data, 5));
2358                     vnc_client_error(vs);
2359                     break;
2360                 }
2361                 vs->as.freq = read_u32(data, 6);
2362                 break;
2363             default:
2364                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2365                 vnc_client_error(vs);
2366                 break;
2367             }
2368             break;
2369 
2370         default:
2371             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2372             vnc_client_error(vs);
2373             break;
2374         }
2375         break;
2376     default:
2377         VNC_DEBUG("Msg: %d\n", data[0]);
2378         vnc_client_error(vs);
2379         break;
2380     }
2381 
2382     vnc_read_when(vs, protocol_client_msg, 1);
2383     return 0;
2384 }
2385 
2386 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2387 {
2388     char buf[1024];
2389     VncShareMode mode;
2390     int size;
2391 
2392     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2393     switch (vs->vd->share_policy) {
2394     case VNC_SHARE_POLICY_IGNORE:
2395         /*
2396          * Ignore the shared flag.  Nothing to do here.
2397          *
2398          * Doesn't conform to the rfb spec but is traditional qemu
2399          * behavior, thus left here as option for compatibility
2400          * reasons.
2401          */
2402         break;
2403     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2404         /*
2405          * Policy: Allow clients ask for exclusive access.
2406          *
2407          * Implementation: When a client asks for exclusive access,
2408          * disconnect all others. Shared connects are allowed as long
2409          * as no exclusive connection exists.
2410          *
2411          * This is how the rfb spec suggests to handle the shared flag.
2412          */
2413         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2414             VncState *client;
2415             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2416                 if (vs == client) {
2417                     continue;
2418                 }
2419                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2420                     client->share_mode != VNC_SHARE_MODE_SHARED) {
2421                     continue;
2422                 }
2423                 vnc_disconnect_start(client);
2424             }
2425         }
2426         if (mode == VNC_SHARE_MODE_SHARED) {
2427             if (vs->vd->num_exclusive > 0) {
2428                 vnc_disconnect_start(vs);
2429                 return 0;
2430             }
2431         }
2432         break;
2433     case VNC_SHARE_POLICY_FORCE_SHARED:
2434         /*
2435          * Policy: Shared connects only.
2436          * Implementation: Disallow clients asking for exclusive access.
2437          *
2438          * Useful for shared desktop sessions where you don't want
2439          * someone forgetting to say -shared when running the vnc
2440          * client disconnect everybody else.
2441          */
2442         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2443             vnc_disconnect_start(vs);
2444             return 0;
2445         }
2446         break;
2447     }
2448     vnc_set_share_mode(vs, mode);
2449 
2450     if (vs->vd->num_shared > vs->vd->connections_limit) {
2451         vnc_disconnect_start(vs);
2452         return 0;
2453     }
2454 
2455     vs->client_width = pixman_image_get_width(vs->vd->server);
2456     vs->client_height = pixman_image_get_height(vs->vd->server);
2457     vnc_write_u16(vs, vs->client_width);
2458     vnc_write_u16(vs, vs->client_height);
2459 
2460     pixel_format_message(vs);
2461 
2462     if (qemu_name)
2463         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2464     else
2465         size = snprintf(buf, sizeof(buf), "QEMU");
2466 
2467     vnc_write_u32(vs, size);
2468     vnc_write(vs, buf, size);
2469     vnc_flush(vs);
2470 
2471     vnc_client_cache_auth(vs);
2472     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2473 
2474     vnc_read_when(vs, protocol_client_msg, 1);
2475 
2476     return 0;
2477 }
2478 
2479 void start_client_init(VncState *vs)
2480 {
2481     vnc_read_when(vs, protocol_client_init, 1);
2482 }
2483 
2484 static void make_challenge(VncState *vs)
2485 {
2486     int i;
2487 
2488     srand(time(NULL)+getpid()+getpid()*987654+rand());
2489 
2490     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2491         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2492 }
2493 
2494 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2495 {
2496     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2497     size_t i, pwlen;
2498     unsigned char key[8];
2499     time_t now = time(NULL);
2500     QCryptoCipher *cipher = NULL;
2501     Error *err = NULL;
2502 
2503     if (!vs->vd->password) {
2504         VNC_DEBUG("No password configured on server");
2505         goto reject;
2506     }
2507     if (vs->vd->expires < now) {
2508         VNC_DEBUG("Password is expired");
2509         goto reject;
2510     }
2511 
2512     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2513 
2514     /* Calculate the expected challenge response */
2515     pwlen = strlen(vs->vd->password);
2516     for (i=0; i<sizeof(key); i++)
2517         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2518 
2519     cipher = qcrypto_cipher_new(
2520         QCRYPTO_CIPHER_ALG_DES_RFB,
2521         QCRYPTO_CIPHER_MODE_ECB,
2522         key, G_N_ELEMENTS(key),
2523         &err);
2524     if (!cipher) {
2525         VNC_DEBUG("Cannot initialize cipher %s",
2526                   error_get_pretty(err));
2527         error_free(err);
2528         goto reject;
2529     }
2530 
2531     if (qcrypto_cipher_encrypt(cipher,
2532                                vs->challenge,
2533                                response,
2534                                VNC_AUTH_CHALLENGE_SIZE,
2535                                &err) < 0) {
2536         VNC_DEBUG("Cannot encrypt challenge %s",
2537                   error_get_pretty(err));
2538         error_free(err);
2539         goto reject;
2540     }
2541 
2542     /* Compare expected vs actual challenge response */
2543     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2544         VNC_DEBUG("Client challenge response did not match\n");
2545         goto reject;
2546     } else {
2547         VNC_DEBUG("Accepting VNC challenge response\n");
2548         vnc_write_u32(vs, 0); /* Accept auth */
2549         vnc_flush(vs);
2550 
2551         start_client_init(vs);
2552     }
2553 
2554     qcrypto_cipher_free(cipher);
2555     return 0;
2556 
2557 reject:
2558     vnc_write_u32(vs, 1); /* Reject auth */
2559     if (vs->minor >= 8) {
2560         static const char err[] = "Authentication failed";
2561         vnc_write_u32(vs, sizeof(err));
2562         vnc_write(vs, err, sizeof(err));
2563     }
2564     vnc_flush(vs);
2565     vnc_client_error(vs);
2566     qcrypto_cipher_free(cipher);
2567     return 0;
2568 }
2569 
2570 void start_auth_vnc(VncState *vs)
2571 {
2572     make_challenge(vs);
2573     /* Send client a 'random' challenge */
2574     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2575     vnc_flush(vs);
2576 
2577     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2578 }
2579 
2580 
2581 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2582 {
2583     /* We only advertise 1 auth scheme at a time, so client
2584      * must pick the one we sent. Verify this */
2585     if (data[0] != vs->auth) { /* Reject auth */
2586        VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2587        vnc_write_u32(vs, 1);
2588        if (vs->minor >= 8) {
2589            static const char err[] = "Authentication failed";
2590            vnc_write_u32(vs, sizeof(err));
2591            vnc_write(vs, err, sizeof(err));
2592        }
2593        vnc_client_error(vs);
2594     } else { /* Accept requested auth */
2595        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2596        switch (vs->auth) {
2597        case VNC_AUTH_NONE:
2598            VNC_DEBUG("Accept auth none\n");
2599            if (vs->minor >= 8) {
2600                vnc_write_u32(vs, 0); /* Accept auth completion */
2601                vnc_flush(vs);
2602            }
2603            start_client_init(vs);
2604            break;
2605 
2606        case VNC_AUTH_VNC:
2607            VNC_DEBUG("Start VNC auth\n");
2608            start_auth_vnc(vs);
2609            break;
2610 
2611        case VNC_AUTH_VENCRYPT:
2612            VNC_DEBUG("Accept VeNCrypt auth\n");
2613            start_auth_vencrypt(vs);
2614            break;
2615 
2616 #ifdef CONFIG_VNC_SASL
2617        case VNC_AUTH_SASL:
2618            VNC_DEBUG("Accept SASL auth\n");
2619            start_auth_sasl(vs);
2620            break;
2621 #endif /* CONFIG_VNC_SASL */
2622 
2623        default: /* Should not be possible, but just in case */
2624            VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2625            vnc_write_u8(vs, 1);
2626            if (vs->minor >= 8) {
2627                static const char err[] = "Authentication failed";
2628                vnc_write_u32(vs, sizeof(err));
2629                vnc_write(vs, err, sizeof(err));
2630            }
2631            vnc_client_error(vs);
2632        }
2633     }
2634     return 0;
2635 }
2636 
2637 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2638 {
2639     char local[13];
2640 
2641     memcpy(local, version, 12);
2642     local[12] = 0;
2643 
2644     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2645         VNC_DEBUG("Malformed protocol version %s\n", local);
2646         vnc_client_error(vs);
2647         return 0;
2648     }
2649     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2650     if (vs->major != 3 ||
2651         (vs->minor != 3 &&
2652          vs->minor != 4 &&
2653          vs->minor != 5 &&
2654          vs->minor != 7 &&
2655          vs->minor != 8)) {
2656         VNC_DEBUG("Unsupported client version\n");
2657         vnc_write_u32(vs, VNC_AUTH_INVALID);
2658         vnc_flush(vs);
2659         vnc_client_error(vs);
2660         return 0;
2661     }
2662     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2663      * as equivalent to v3.3 by servers
2664      */
2665     if (vs->minor == 4 || vs->minor == 5)
2666         vs->minor = 3;
2667 
2668     if (vs->minor == 3) {
2669         if (vs->auth == VNC_AUTH_NONE) {
2670             VNC_DEBUG("Tell client auth none\n");
2671             vnc_write_u32(vs, vs->auth);
2672             vnc_flush(vs);
2673             start_client_init(vs);
2674        } else if (vs->auth == VNC_AUTH_VNC) {
2675             VNC_DEBUG("Tell client VNC auth\n");
2676             vnc_write_u32(vs, vs->auth);
2677             vnc_flush(vs);
2678             start_auth_vnc(vs);
2679        } else {
2680             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2681             vnc_write_u32(vs, VNC_AUTH_INVALID);
2682             vnc_flush(vs);
2683             vnc_client_error(vs);
2684        }
2685     } else {
2686         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2687         vnc_write_u8(vs, 1); /* num auth */
2688         vnc_write_u8(vs, vs->auth);
2689         vnc_read_when(vs, protocol_client_auth, 1);
2690         vnc_flush(vs);
2691     }
2692 
2693     return 0;
2694 }
2695 
2696 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2697 {
2698     struct VncSurface *vs = &vd->guest;
2699 
2700     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2701 }
2702 
2703 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2704 {
2705     int i, j;
2706 
2707     w = (x + w) / VNC_STAT_RECT;
2708     h = (y + h) / VNC_STAT_RECT;
2709     x /= VNC_STAT_RECT;
2710     y /= VNC_STAT_RECT;
2711 
2712     for (j = y; j <= h; j++) {
2713         for (i = x; i <= w; i++) {
2714             vs->lossy_rect[j][i] = 1;
2715         }
2716     }
2717 }
2718 
2719 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2720 {
2721     VncState *vs;
2722     int sty = y / VNC_STAT_RECT;
2723     int stx = x / VNC_STAT_RECT;
2724     int has_dirty = 0;
2725 
2726     y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2727     x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2728 
2729     QTAILQ_FOREACH(vs, &vd->clients, next) {
2730         int j;
2731 
2732         /* kernel send buffers are full -> refresh later */
2733         if (vs->output.offset) {
2734             continue;
2735         }
2736 
2737         if (!vs->lossy_rect[sty][stx]) {
2738             continue;
2739         }
2740 
2741         vs->lossy_rect[sty][stx] = 0;
2742         for (j = 0; j < VNC_STAT_RECT; ++j) {
2743             bitmap_set(vs->dirty[y + j],
2744                        x / VNC_DIRTY_PIXELS_PER_BIT,
2745                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2746         }
2747         has_dirty++;
2748     }
2749 
2750     return has_dirty;
2751 }
2752 
2753 static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2754 {
2755     int width = pixman_image_get_width(vd->guest.fb);
2756     int height = pixman_image_get_height(vd->guest.fb);
2757     int x, y;
2758     struct timeval res;
2759     int has_dirty = 0;
2760 
2761     for (y = 0; y < height; y += VNC_STAT_RECT) {
2762         for (x = 0; x < width; x += VNC_STAT_RECT) {
2763             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2764 
2765             rect->updated = false;
2766         }
2767     }
2768 
2769     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2770 
2771     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2772         return has_dirty;
2773     }
2774     vd->guest.last_freq_check = *tv;
2775 
2776     for (y = 0; y < height; y += VNC_STAT_RECT) {
2777         for (x = 0; x < width; x += VNC_STAT_RECT) {
2778             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2779             int count = ARRAY_SIZE(rect->times);
2780             struct timeval min, max;
2781 
2782             if (!timerisset(&rect->times[count - 1])) {
2783                 continue ;
2784             }
2785 
2786             max = rect->times[(rect->idx + count - 1) % count];
2787             qemu_timersub(tv, &max, &res);
2788 
2789             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2790                 rect->freq = 0;
2791                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2792                 memset(rect->times, 0, sizeof (rect->times));
2793                 continue ;
2794             }
2795 
2796             min = rect->times[rect->idx];
2797             max = rect->times[(rect->idx + count - 1) % count];
2798             qemu_timersub(&max, &min, &res);
2799 
2800             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2801             rect->freq /= count;
2802             rect->freq = 1. / rect->freq;
2803         }
2804     }
2805     return has_dirty;
2806 }
2807 
2808 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2809 {
2810     int i, j;
2811     double total = 0;
2812     int num = 0;
2813 
2814     x =  (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2815     y =  (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2816 
2817     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2818         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2819             total += vnc_stat_rect(vs->vd, i, j)->freq;
2820             num++;
2821         }
2822     }
2823 
2824     if (num) {
2825         return total / num;
2826     } else {
2827         return 0;
2828     }
2829 }
2830 
2831 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2832 {
2833     VncRectStat *rect;
2834 
2835     rect = vnc_stat_rect(vd, x, y);
2836     if (rect->updated) {
2837         return ;
2838     }
2839     rect->times[rect->idx] = *tv;
2840     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2841     rect->updated = true;
2842 }
2843 
2844 static int vnc_refresh_server_surface(VncDisplay *vd)
2845 {
2846     int width = MIN(pixman_image_get_width(vd->guest.fb),
2847                     pixman_image_get_width(vd->server));
2848     int height = MIN(pixman_image_get_height(vd->guest.fb),
2849                      pixman_image_get_height(vd->server));
2850     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2851     uint8_t *guest_row0 = NULL, *server_row0;
2852     VncState *vs;
2853     int has_dirty = 0;
2854     pixman_image_t *tmpbuf = NULL;
2855 
2856     struct timeval tv = { 0, 0 };
2857 
2858     if (!vd->non_adaptive) {
2859         gettimeofday(&tv, NULL);
2860         has_dirty = vnc_update_stats(vd, &tv);
2861     }
2862 
2863     /*
2864      * Walk through the guest dirty map.
2865      * Check and copy modified bits from guest to server surface.
2866      * Update server dirty map.
2867      */
2868     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2869     server_stride = guest_stride = guest_ll =
2870         pixman_image_get_stride(vd->server);
2871     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2872                     server_stride);
2873     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2874         int width = pixman_image_get_width(vd->server);
2875         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2876     } else {
2877         int guest_bpp =
2878             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2879         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2880         guest_stride = pixman_image_get_stride(vd->guest.fb);
2881         guest_ll = pixman_image_get_width(vd->guest.fb) * ((guest_bpp + 7) / 8);
2882     }
2883     line_bytes = MIN(server_stride, guest_ll);
2884 
2885     for (;;) {
2886         int x;
2887         uint8_t *guest_ptr, *server_ptr;
2888         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2889                                              height * VNC_DIRTY_BPL(&vd->guest),
2890                                              y * VNC_DIRTY_BPL(&vd->guest));
2891         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2892             /* no more dirty bits */
2893             break;
2894         }
2895         y = offset / VNC_DIRTY_BPL(&vd->guest);
2896         x = offset % VNC_DIRTY_BPL(&vd->guest);
2897 
2898         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2899 
2900         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2901             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2902             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2903         } else {
2904             guest_ptr = guest_row0 + y * guest_stride;
2905         }
2906         guest_ptr += x * cmp_bytes;
2907 
2908         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2909              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2910             int _cmp_bytes = cmp_bytes;
2911             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2912                 continue;
2913             }
2914             if ((x + 1) * cmp_bytes > line_bytes) {
2915                 _cmp_bytes = line_bytes - x * cmp_bytes;
2916             }
2917             assert(_cmp_bytes >= 0);
2918             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2919                 continue;
2920             }
2921             memcpy(server_ptr, guest_ptr, _cmp_bytes);
2922             if (!vd->non_adaptive) {
2923                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2924                                  y, &tv);
2925             }
2926             QTAILQ_FOREACH(vs, &vd->clients, next) {
2927                 set_bit(x, vs->dirty[y]);
2928             }
2929             has_dirty++;
2930         }
2931 
2932         y++;
2933     }
2934     qemu_pixman_image_unref(tmpbuf);
2935     return has_dirty;
2936 }
2937 
2938 static void vnc_refresh(DisplayChangeListener *dcl)
2939 {
2940     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2941     VncState *vs, *vn;
2942     int has_dirty, rects = 0;
2943 
2944     if (QTAILQ_EMPTY(&vd->clients)) {
2945         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2946         return;
2947     }
2948 
2949     graphic_hw_update(vd->dcl.con);
2950 
2951     if (vnc_trylock_display(vd)) {
2952         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2953         return;
2954     }
2955 
2956     has_dirty = vnc_refresh_server_surface(vd);
2957     vnc_unlock_display(vd);
2958 
2959     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2960         rects += vnc_update_client(vs, has_dirty, false);
2961         /* vs might be free()ed here */
2962     }
2963 
2964     if (has_dirty && rects) {
2965         vd->dcl.update_interval /= 2;
2966         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
2967             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
2968         }
2969     } else {
2970         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
2971         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
2972             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
2973         }
2974     }
2975 }
2976 
2977 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
2978                         bool skipauth, bool websocket)
2979 {
2980     VncState *vs = g_new0(VncState, 1);
2981     int i;
2982 
2983     vs->sioc = sioc;
2984     object_ref(OBJECT(vs->sioc));
2985     vs->ioc = QIO_CHANNEL(sioc);
2986     object_ref(OBJECT(vs->ioc));
2987     vs->vd = vd;
2988 
2989     buffer_init(&vs->input,          "vnc-input/%p", sioc);
2990     buffer_init(&vs->output,         "vnc-output/%p", sioc);
2991     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
2992 
2993     buffer_init(&vs->tight.tight,    "vnc-tight/%p", sioc);
2994     buffer_init(&vs->tight.zlib,     "vnc-tight-zlib/%p", sioc);
2995     buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
2996 #ifdef CONFIG_VNC_JPEG
2997     buffer_init(&vs->tight.jpeg,     "vnc-tight-jpeg/%p", sioc);
2998 #endif
2999 #ifdef CONFIG_VNC_PNG
3000     buffer_init(&vs->tight.png,      "vnc-tight-png/%p", sioc);
3001 #endif
3002     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
3003     buffer_init(&vs->zrle.zrle,      "vnc-zrle/%p", sioc);
3004     buffer_init(&vs->zrle.fb,        "vnc-zrle-fb/%p", sioc);
3005     buffer_init(&vs->zrle.zlib,      "vnc-zrle-zlib/%p", sioc);
3006 
3007     if (skipauth) {
3008 	vs->auth = VNC_AUTH_NONE;
3009 	vs->subauth = VNC_AUTH_INVALID;
3010     } else {
3011         if (websocket) {
3012             vs->auth = vd->ws_auth;
3013             vs->subauth = VNC_AUTH_INVALID;
3014         } else {
3015             vs->auth = vd->auth;
3016             vs->subauth = vd->subauth;
3017         }
3018     }
3019     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3020               sioc, websocket, vs->auth, vs->subauth);
3021 
3022     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3023     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3024         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3025     }
3026 
3027     VNC_DEBUG("New client on socket %p\n", vs->sioc);
3028     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3029     qio_channel_set_blocking(vs->ioc, false, NULL);
3030     if (websocket) {
3031         vs->websocket = 1;
3032         if (vd->ws_tls) {
3033             vs->ioc_tag = qio_channel_add_watch(
3034                 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
3035         } else {
3036             vs->ioc_tag = qio_channel_add_watch(
3037                 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
3038         }
3039     } else {
3040         vs->ioc_tag = qio_channel_add_watch(
3041             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
3042     }
3043 
3044     vnc_client_cache_addr(vs);
3045     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3046     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3047 
3048     if (!vs->websocket) {
3049         vnc_init_state(vs);
3050     }
3051 
3052     if (vd->num_connecting > vd->connections_limit) {
3053         QTAILQ_FOREACH(vs, &vd->clients, next) {
3054             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3055                 vnc_disconnect_start(vs);
3056                 return;
3057             }
3058         }
3059     }
3060 }
3061 
3062 void vnc_init_state(VncState *vs)
3063 {
3064     vs->initialized = true;
3065     VncDisplay *vd = vs->vd;
3066     bool first_client = QTAILQ_EMPTY(&vd->clients);
3067 
3068     vs->last_x = -1;
3069     vs->last_y = -1;
3070 
3071     vs->as.freq = 44100;
3072     vs->as.nchannels = 2;
3073     vs->as.fmt = AUD_FMT_S16;
3074     vs->as.endianness = 0;
3075 
3076     qemu_mutex_init(&vs->output_mutex);
3077     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3078 
3079     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3080     if (first_client) {
3081         vnc_update_server_surface(vd);
3082     }
3083 
3084     graphic_hw_update(vd->dcl.con);
3085 
3086     vnc_write(vs, "RFB 003.008\n", 12);
3087     vnc_flush(vs);
3088     vnc_read_when(vs, protocol_version, 12);
3089     reset_keys(vs);
3090     if (vs->vd->lock_key_sync)
3091         vs->led = qemu_add_led_event_handler(kbd_leds, vs);
3092 
3093     vs->mouse_mode_notifier.notify = check_pointer_type_change;
3094     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3095 
3096     /* vs might be free()ed here */
3097 }
3098 
3099 static gboolean vnc_listen_io(QIOChannel *ioc,
3100                               GIOCondition condition,
3101                               void *opaque)
3102 {
3103     VncDisplay *vs = opaque;
3104     QIOChannelSocket *sioc = NULL;
3105     Error *err = NULL;
3106 
3107     /* Catch-up */
3108     graphic_hw_update(vs->dcl.con);
3109     sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), &err);
3110     if (sioc != NULL) {
3111         qio_channel_set_delay(QIO_CHANNEL(sioc), false);
3112         vnc_connect(vs, sioc, false,
3113                     ioc != QIO_CHANNEL(vs->lsock));
3114         object_unref(OBJECT(sioc));
3115     } else {
3116         /* client probably closed connection before we got there */
3117         error_free(err);
3118     }
3119 
3120     return TRUE;
3121 }
3122 
3123 static const DisplayChangeListenerOps dcl_ops = {
3124     .dpy_name             = "vnc",
3125     .dpy_refresh          = vnc_refresh,
3126     .dpy_gfx_copy         = vnc_dpy_copy,
3127     .dpy_gfx_update       = vnc_dpy_update,
3128     .dpy_gfx_switch       = vnc_dpy_switch,
3129     .dpy_gfx_check_format = qemu_pixman_check_format,
3130     .dpy_mouse_set        = vnc_mouse_set,
3131     .dpy_cursor_define    = vnc_dpy_cursor_define,
3132 };
3133 
3134 void vnc_display_init(const char *id)
3135 {
3136     VncDisplay *vs;
3137 
3138     if (vnc_display_find(id) != NULL) {
3139         return;
3140     }
3141     vs = g_malloc0(sizeof(*vs));
3142 
3143     vs->id = strdup(id);
3144     QTAILQ_INSERT_TAIL(&vnc_displays, vs, next);
3145 
3146     QTAILQ_INIT(&vs->clients);
3147     vs->expires = TIME_MAX;
3148 
3149     if (keyboard_layout) {
3150         trace_vnc_key_map_init(keyboard_layout);
3151         vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
3152     } else {
3153         vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
3154     }
3155 
3156     if (!vs->kbd_layout)
3157         exit(1);
3158 
3159     vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3160     vs->connections_limit = 32;
3161 
3162     qemu_mutex_init(&vs->mutex);
3163     vnc_start_worker_thread();
3164 
3165     vs->dcl.ops = &dcl_ops;
3166     register_displaychangelistener(&vs->dcl);
3167 }
3168 
3169 
3170 static void vnc_display_close(VncDisplay *vs)
3171 {
3172     if (!vs)
3173         return;
3174     vs->enabled = false;
3175     vs->is_unix = false;
3176     if (vs->lsock != NULL) {
3177         if (vs->lsock_tag) {
3178             g_source_remove(vs->lsock_tag);
3179         }
3180         object_unref(OBJECT(vs->lsock));
3181         vs->lsock = NULL;
3182     }
3183     vs->ws_enabled = false;
3184     if (vs->lwebsock != NULL) {
3185         if (vs->lwebsock_tag) {
3186             g_source_remove(vs->lwebsock_tag);
3187         }
3188         object_unref(OBJECT(vs->lwebsock));
3189         vs->lwebsock = NULL;
3190     }
3191     vs->auth = VNC_AUTH_INVALID;
3192     vs->subauth = VNC_AUTH_INVALID;
3193     if (vs->tlscreds) {
3194         object_unparent(OBJECT(vs->tlscreds));
3195         vs->tlscreds = NULL;
3196     }
3197     g_free(vs->tlsaclname);
3198     vs->tlsaclname = NULL;
3199 }
3200 
3201 int vnc_display_password(const char *id, const char *password)
3202 {
3203     VncDisplay *vs = vnc_display_find(id);
3204 
3205     if (!vs) {
3206         return -EINVAL;
3207     }
3208     if (vs->auth == VNC_AUTH_NONE) {
3209         error_printf_unless_qmp("If you want use passwords please enable "
3210                                 "password auth using '-vnc ${dpy},password'.\n");
3211         return -EINVAL;
3212     }
3213 
3214     g_free(vs->password);
3215     vs->password = g_strdup(password);
3216 
3217     return 0;
3218 }
3219 
3220 int vnc_display_pw_expire(const char *id, time_t expires)
3221 {
3222     VncDisplay *vs = vnc_display_find(id);
3223 
3224     if (!vs) {
3225         return -EINVAL;
3226     }
3227 
3228     vs->expires = expires;
3229     return 0;
3230 }
3231 
3232 static void vnc_display_print_local_addr(VncDisplay *vs)
3233 {
3234     SocketAddress *addr;
3235     Error *err = NULL;
3236 
3237     addr = qio_channel_socket_get_local_address(vs->lsock, &err);
3238     if (!addr) {
3239         return;
3240     }
3241 
3242     if (addr->type != SOCKET_ADDRESS_KIND_INET) {
3243         qapi_free_SocketAddress(addr);
3244         return;
3245     }
3246     error_printf_unless_qmp("VNC server running on %s:%s\n",
3247                             addr->u.inet.data->host,
3248                             addr->u.inet.data->port);
3249     qapi_free_SocketAddress(addr);
3250 }
3251 
3252 static QemuOptsList qemu_vnc_opts = {
3253     .name = "vnc",
3254     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3255     .implied_opt_name = "vnc",
3256     .desc = {
3257         {
3258             .name = "vnc",
3259             .type = QEMU_OPT_STRING,
3260         },{
3261             .name = "websocket",
3262             .type = QEMU_OPT_STRING,
3263         },{
3264             .name = "tls-creds",
3265             .type = QEMU_OPT_STRING,
3266         },{
3267             /* Deprecated in favour of tls-creds */
3268             .name = "x509",
3269             .type = QEMU_OPT_STRING,
3270         },{
3271             .name = "share",
3272             .type = QEMU_OPT_STRING,
3273         },{
3274             .name = "display",
3275             .type = QEMU_OPT_STRING,
3276         },{
3277             .name = "head",
3278             .type = QEMU_OPT_NUMBER,
3279         },{
3280             .name = "connections",
3281             .type = QEMU_OPT_NUMBER,
3282         },{
3283             .name = "to",
3284             .type = QEMU_OPT_NUMBER,
3285         },{
3286             .name = "ipv4",
3287             .type = QEMU_OPT_BOOL,
3288         },{
3289             .name = "ipv6",
3290             .type = QEMU_OPT_BOOL,
3291         },{
3292             .name = "password",
3293             .type = QEMU_OPT_BOOL,
3294         },{
3295             .name = "reverse",
3296             .type = QEMU_OPT_BOOL,
3297         },{
3298             .name = "lock-key-sync",
3299             .type = QEMU_OPT_BOOL,
3300         },{
3301             .name = "key-delay-ms",
3302             .type = QEMU_OPT_NUMBER,
3303         },{
3304             .name = "sasl",
3305             .type = QEMU_OPT_BOOL,
3306         },{
3307             /* Deprecated in favour of tls-creds */
3308             .name = "tls",
3309             .type = QEMU_OPT_BOOL,
3310         },{
3311             /* Deprecated in favour of tls-creds */
3312             .name = "x509verify",
3313             .type = QEMU_OPT_STRING,
3314         },{
3315             .name = "acl",
3316             .type = QEMU_OPT_BOOL,
3317         },{
3318             .name = "lossy",
3319             .type = QEMU_OPT_BOOL,
3320         },{
3321             .name = "non-adaptive",
3322             .type = QEMU_OPT_BOOL,
3323         },
3324         { /* end of list */ }
3325     },
3326 };
3327 
3328 
3329 static int
3330 vnc_display_setup_auth(VncDisplay *vs,
3331                        bool password,
3332                        bool sasl,
3333                        bool websocket,
3334                        Error **errp)
3335 {
3336     /*
3337      * We have a choice of 3 authentication options
3338      *
3339      *   1. none
3340      *   2. vnc
3341      *   3. sasl
3342      *
3343      * The channel can be run in 2 modes
3344      *
3345      *   1. clear
3346      *   2. tls
3347      *
3348      * And TLS can use 2 types of credentials
3349      *
3350      *   1. anon
3351      *   2. x509
3352      *
3353      * We thus have 9 possible logical combinations
3354      *
3355      *   1. clear + none
3356      *   2. clear + vnc
3357      *   3. clear + sasl
3358      *   4. tls + anon + none
3359      *   5. tls + anon + vnc
3360      *   6. tls + anon + sasl
3361      *   7. tls + x509 + none
3362      *   8. tls + x509 + vnc
3363      *   9. tls + x509 + sasl
3364      *
3365      * These need to be mapped into the VNC auth schemes
3366      * in an appropriate manner. In regular VNC, all the
3367      * TLS options get mapped into VNC_AUTH_VENCRYPT
3368      * sub-auth types.
3369      *
3370      * In websockets, the https:// protocol already provides
3371      * TLS support, so there is no need to make use of the
3372      * VeNCrypt extension. Furthermore, websockets browser
3373      * clients could not use VeNCrypt even if they wanted to,
3374      * as they cannot control when the TLS handshake takes
3375      * place. Thus there is no option but to rely on https://,
3376      * meaning combinations 4->6 and 7->9 will be mapped to
3377      * VNC auth schemes in the same way as combos 1->3.
3378      *
3379      * Regardless of fact that we have a different mapping to
3380      * VNC auth mechs for plain VNC vs websockets VNC, the end
3381      * result has the same security characteristics.
3382      */
3383     if (password) {
3384         if (vs->tlscreds) {
3385             vs->auth = VNC_AUTH_VENCRYPT;
3386             if (websocket) {
3387                 vs->ws_tls = true;
3388             }
3389             if (object_dynamic_cast(OBJECT(vs->tlscreds),
3390                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
3391                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3392                 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
3393             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
3394                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
3395                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3396                 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3397             } else {
3398                 error_setg(errp,
3399                            "Unsupported TLS cred type %s",
3400                            object_get_typename(OBJECT(vs->tlscreds)));
3401                 return -1;
3402             }
3403         } else {
3404             VNC_DEBUG("Initializing VNC server with password auth\n");
3405             vs->auth = VNC_AUTH_VNC;
3406             vs->subauth = VNC_AUTH_INVALID;
3407         }
3408         if (websocket) {
3409             vs->ws_auth = VNC_AUTH_VNC;
3410         } else {
3411             vs->ws_auth = VNC_AUTH_INVALID;
3412         }
3413     } else if (sasl) {
3414         if (vs->tlscreds) {
3415             vs->auth = VNC_AUTH_VENCRYPT;
3416             if (websocket) {
3417                 vs->ws_tls = true;
3418             }
3419             if (object_dynamic_cast(OBJECT(vs->tlscreds),
3420                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
3421                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3422                 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3423             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
3424                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
3425                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3426                 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3427             } else {
3428                 error_setg(errp,
3429                            "Unsupported TLS cred type %s",
3430                            object_get_typename(OBJECT(vs->tlscreds)));
3431                 return -1;
3432             }
3433         } else {
3434             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3435             vs->auth = VNC_AUTH_SASL;
3436             vs->subauth = VNC_AUTH_INVALID;
3437         }
3438         if (websocket) {
3439             vs->ws_auth = VNC_AUTH_SASL;
3440         } else {
3441             vs->ws_auth = VNC_AUTH_INVALID;
3442         }
3443     } else {
3444         if (vs->tlscreds) {
3445             vs->auth = VNC_AUTH_VENCRYPT;
3446             if (websocket) {
3447                 vs->ws_tls = true;
3448             }
3449             if (object_dynamic_cast(OBJECT(vs->tlscreds),
3450                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
3451                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3452                 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3453             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
3454                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
3455                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3456                 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3457             } else {
3458                 error_setg(errp,
3459                            "Unsupported TLS cred type %s",
3460                            object_get_typename(OBJECT(vs->tlscreds)));
3461                 return -1;
3462             }
3463         } else {
3464             VNC_DEBUG("Initializing VNC server with no auth\n");
3465             vs->auth = VNC_AUTH_NONE;
3466             vs->subauth = VNC_AUTH_INVALID;
3467         }
3468         if (websocket) {
3469             vs->ws_auth = VNC_AUTH_NONE;
3470         } else {
3471             vs->ws_auth = VNC_AUTH_INVALID;
3472         }
3473     }
3474     return 0;
3475 }
3476 
3477 
3478 /*
3479  * Handle back compat with old CLI syntax by creating some
3480  * suitable QCryptoTLSCreds objects
3481  */
3482 static QCryptoTLSCreds *
3483 vnc_display_create_creds(bool x509,
3484                          bool x509verify,
3485                          const char *dir,
3486                          const char *id,
3487                          Error **errp)
3488 {
3489     gchar *credsid = g_strdup_printf("tlsvnc%s", id);
3490     Object *parent = object_get_objects_root();
3491     Object *creds;
3492     Error *err = NULL;
3493 
3494     if (x509) {
3495         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
3496                                       parent,
3497                                       credsid,
3498                                       &err,
3499                                       "endpoint", "server",
3500                                       "dir", dir,
3501                                       "verify-peer", x509verify ? "yes" : "no",
3502                                       NULL);
3503     } else {
3504         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
3505                                       parent,
3506                                       credsid,
3507                                       &err,
3508                                       "endpoint", "server",
3509                                       NULL);
3510     }
3511 
3512     g_free(credsid);
3513 
3514     if (err) {
3515         error_propagate(errp, err);
3516         return NULL;
3517     }
3518 
3519     return QCRYPTO_TLS_CREDS(creds);
3520 }
3521 
3522 
3523 void vnc_display_open(const char *id, Error **errp)
3524 {
3525     VncDisplay *vs = vnc_display_find(id);
3526     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3527     SocketAddress *saddr = NULL, *wsaddr = NULL;
3528     const char *share, *device_id;
3529     QemuConsole *con;
3530     bool password = false;
3531     bool reverse = false;
3532     const char *vnc;
3533     char *h;
3534     const char *credid;
3535     int show_vnc_port = 0;
3536     bool sasl = false;
3537 #ifdef CONFIG_VNC_SASL
3538     int saslErr;
3539 #endif
3540     int acl = 0;
3541     int lock_key_sync = 1;
3542     int key_delay_ms;
3543 
3544     if (!vs) {
3545         error_setg(errp, "VNC display not active");
3546         return;
3547     }
3548     vnc_display_close(vs);
3549 
3550     if (!opts) {
3551         return;
3552     }
3553     vnc = qemu_opt_get(opts, "vnc");
3554     if (!vnc || strcmp(vnc, "none") == 0) {
3555         return;
3556     }
3557 
3558     h = strrchr(vnc, ':');
3559     if (h) {
3560         size_t hlen = h - vnc;
3561 
3562         const char *websocket = qemu_opt_get(opts, "websocket");
3563         int to = qemu_opt_get_number(opts, "to", 0);
3564         bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3565         bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3566         bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3567         bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3568 
3569         saddr = g_new0(SocketAddress, 1);
3570         if (websocket) {
3571             if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3572                 error_setg(errp,
3573                            "SHA1 hash support is required for websockets");
3574                 goto fail;
3575             }
3576 
3577             wsaddr = g_new0(SocketAddress, 1);
3578             vs->ws_enabled = true;
3579         }
3580 
3581         if (strncmp(vnc, "unix:", 5) == 0) {
3582             saddr->type = SOCKET_ADDRESS_KIND_UNIX;
3583             saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3584             saddr->u.q_unix.data->path = g_strdup(vnc + 5);
3585 
3586             if (vs->ws_enabled) {
3587                 error_setg(errp, "UNIX sockets not supported with websock");
3588                 goto fail;
3589             }
3590         } else {
3591             unsigned long long baseport;
3592             InetSocketAddress *inet;
3593             saddr->type = SOCKET_ADDRESS_KIND_INET;
3594             inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
3595             if (vnc[0] == '[' && vnc[hlen - 1] == ']') {
3596                 inet->host = g_strndup(vnc + 1, hlen - 2);
3597             } else {
3598                 inet->host = g_strndup(vnc, hlen);
3599             }
3600             if (parse_uint_full(h + 1, &baseport, 10) < 0) {
3601                 error_setg(errp, "can't convert to a number: %s", h + 1);
3602                 goto fail;
3603             }
3604             if (baseport > 65535 ||
3605                 baseport + 5900 > 65535) {
3606                 error_setg(errp, "port %s out of range", h + 1);
3607                 goto fail;
3608             }
3609             inet->port = g_strdup_printf(
3610                 "%d", (int)baseport + 5900);
3611 
3612             if (to) {
3613                 inet->has_to = true;
3614                 inet->to = to + 5900;
3615                 show_vnc_port = 1;
3616             }
3617             inet->ipv4 = ipv4;
3618             inet->has_ipv4 = has_ipv4;
3619             inet->ipv6 = ipv6;
3620             inet->has_ipv6 = has_ipv6;
3621 
3622             if (vs->ws_enabled) {
3623                 wsaddr->type = SOCKET_ADDRESS_KIND_INET;
3624                 inet = wsaddr->u.inet.data = g_new0(InetSocketAddress, 1);
3625                 inet->host = g_strdup(saddr->u.inet.data->host);
3626                 inet->port = g_strdup(websocket);
3627 
3628                 if (to) {
3629                     inet->has_to = true;
3630                     inet->to = to;
3631                 }
3632                 inet->ipv4 = ipv4;
3633                 inet->has_ipv4 = has_ipv4;
3634                 inet->ipv6 = ipv6;
3635                 inet->has_ipv6 = has_ipv6;
3636             }
3637         }
3638     } else {
3639         error_setg(errp, "no vnc port specified");
3640         goto fail;
3641     }
3642 
3643     password = qemu_opt_get_bool(opts, "password", false);
3644     if (password) {
3645         if (fips_get_state()) {
3646             error_setg(errp,
3647                        "VNC password auth disabled due to FIPS mode, "
3648                        "consider using the VeNCrypt or SASL authentication "
3649                        "methods as an alternative");
3650             goto fail;
3651         }
3652         if (!qcrypto_cipher_supports(
3653                 QCRYPTO_CIPHER_ALG_DES_RFB)) {
3654             error_setg(errp,
3655                        "Cipher backend does not support DES RFB algorithm");
3656             goto fail;
3657         }
3658     }
3659 
3660     reverse = qemu_opt_get_bool(opts, "reverse", false);
3661     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3662     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 1);
3663     sasl = qemu_opt_get_bool(opts, "sasl", false);
3664 #ifndef CONFIG_VNC_SASL
3665     if (sasl) {
3666         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3667         goto fail;
3668     }
3669 #endif /* CONFIG_VNC_SASL */
3670     credid = qemu_opt_get(opts, "tls-creds");
3671     if (credid) {
3672         Object *creds;
3673         if (qemu_opt_get(opts, "tls") ||
3674             qemu_opt_get(opts, "x509") ||
3675             qemu_opt_get(opts, "x509verify")) {
3676             error_setg(errp,
3677                        "'tls-creds' parameter is mutually exclusive with "
3678                        "'tls', 'x509' and 'x509verify' parameters");
3679             goto fail;
3680         }
3681 
3682         creds = object_resolve_path_component(
3683             object_get_objects_root(), credid);
3684         if (!creds) {
3685             error_setg(errp, "No TLS credentials with id '%s'",
3686                        credid);
3687             goto fail;
3688         }
3689         vs->tlscreds = (QCryptoTLSCreds *)
3690             object_dynamic_cast(creds,
3691                                 TYPE_QCRYPTO_TLS_CREDS);
3692         if (!vs->tlscreds) {
3693             error_setg(errp, "Object with id '%s' is not TLS credentials",
3694                        credid);
3695             goto fail;
3696         }
3697         object_ref(OBJECT(vs->tlscreds));
3698 
3699         if (vs->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3700             error_setg(errp,
3701                        "Expecting TLS credentials with a server endpoint");
3702             goto fail;
3703         }
3704     } else {
3705         const char *path;
3706         bool tls = false, x509 = false, x509verify = false;
3707         tls  = qemu_opt_get_bool(opts, "tls", false);
3708         if (tls) {
3709             path = qemu_opt_get(opts, "x509");
3710 
3711             if (path) {
3712                 x509 = true;
3713             } else {
3714                 path = qemu_opt_get(opts, "x509verify");
3715                 if (path) {
3716                     x509 = true;
3717                     x509verify = true;
3718                 }
3719             }
3720             vs->tlscreds = vnc_display_create_creds(x509,
3721                                                     x509verify,
3722                                                     path,
3723                                                     vs->id,
3724                                                     errp);
3725             if (!vs->tlscreds) {
3726                 goto fail;
3727             }
3728         }
3729     }
3730     acl = qemu_opt_get_bool(opts, "acl", false);
3731 
3732     share = qemu_opt_get(opts, "share");
3733     if (share) {
3734         if (strcmp(share, "ignore") == 0) {
3735             vs->share_policy = VNC_SHARE_POLICY_IGNORE;
3736         } else if (strcmp(share, "allow-exclusive") == 0) {
3737             vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3738         } else if (strcmp(share, "force-shared") == 0) {
3739             vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3740         } else {
3741             error_setg(errp, "unknown vnc share= option");
3742             goto fail;
3743         }
3744     } else {
3745         vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3746     }
3747     vs->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3748 
3749 #ifdef CONFIG_VNC_JPEG
3750     vs->lossy = qemu_opt_get_bool(opts, "lossy", false);
3751 #endif
3752     vs->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3753     /* adaptive updates are only used with tight encoding and
3754      * if lossy updates are enabled so we can disable all the
3755      * calculations otherwise */
3756     if (!vs->lossy) {
3757         vs->non_adaptive = true;
3758     }
3759 
3760     if (acl) {
3761         if (strcmp(vs->id, "default") == 0) {
3762             vs->tlsaclname = g_strdup("vnc.x509dname");
3763         } else {
3764             vs->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vs->id);
3765         }
3766         qemu_acl_init(vs->tlsaclname);
3767     }
3768 #ifdef CONFIG_VNC_SASL
3769     if (acl && sasl) {
3770         char *aclname;
3771 
3772         if (strcmp(vs->id, "default") == 0) {
3773             aclname = g_strdup("vnc.username");
3774         } else {
3775             aclname = g_strdup_printf("vnc.%s.username", vs->id);
3776         }
3777         vs->sasl.acl = qemu_acl_init(aclname);
3778         g_free(aclname);
3779     }
3780 #endif
3781 
3782     if (vnc_display_setup_auth(vs, password, sasl, vs->ws_enabled, errp) < 0) {
3783         goto fail;
3784     }
3785 
3786 #ifdef CONFIG_VNC_SASL
3787     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3788         error_setg(errp, "Failed to initialize SASL auth: %s",
3789                    sasl_errstring(saslErr, NULL, NULL));
3790         goto fail;
3791     }
3792 #endif
3793     vs->lock_key_sync = lock_key_sync;
3794     vs->key_delay_ms = key_delay_ms;
3795 
3796     device_id = qemu_opt_get(opts, "display");
3797     if (device_id) {
3798         int head = qemu_opt_get_number(opts, "head", 0);
3799         Error *err = NULL;
3800 
3801         con = qemu_console_lookup_by_device_name(device_id, head, &err);
3802         if (err) {
3803             error_propagate(errp, err);
3804             goto fail;
3805         }
3806     } else {
3807         con = NULL;
3808     }
3809 
3810     if (con != vs->dcl.con) {
3811         unregister_displaychangelistener(&vs->dcl);
3812         vs->dcl.con = con;
3813         register_displaychangelistener(&vs->dcl);
3814     }
3815 
3816     if (reverse) {
3817         /* connect to viewer */
3818         QIOChannelSocket *sioc = NULL;
3819         vs->lsock = NULL;
3820         vs->lwebsock = NULL;
3821         if (vs->ws_enabled) {
3822             error_setg(errp, "Cannot use websockets in reverse mode");
3823             goto fail;
3824         }
3825         vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
3826         sioc = qio_channel_socket_new();
3827         if (qio_channel_socket_connect_sync(sioc, saddr, errp) < 0) {
3828             goto fail;
3829         }
3830         vnc_connect(vs, sioc, false, false);
3831         object_unref(OBJECT(sioc));
3832     } else {
3833         vs->lsock = qio_channel_socket_new();
3834         if (qio_channel_socket_listen_sync(vs->lsock, saddr, errp) < 0) {
3835             goto fail;
3836         }
3837         vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
3838         vs->enabled = true;
3839 
3840         if (vs->ws_enabled) {
3841             vs->lwebsock = qio_channel_socket_new();
3842             if (qio_channel_socket_listen_sync(vs->lwebsock,
3843                                                wsaddr, errp) < 0) {
3844                 object_unref(OBJECT(vs->lsock));
3845                 vs->lsock = NULL;
3846                 goto fail;
3847             }
3848         }
3849 
3850         vs->lsock_tag = qio_channel_add_watch(
3851             QIO_CHANNEL(vs->lsock),
3852             G_IO_IN, vnc_listen_io, vs, NULL);
3853         if (vs->ws_enabled) {
3854             vs->lwebsock_tag = qio_channel_add_watch(
3855                 QIO_CHANNEL(vs->lwebsock),
3856                 G_IO_IN, vnc_listen_io, vs, NULL);
3857         }
3858     }
3859 
3860     if (show_vnc_port) {
3861         vnc_display_print_local_addr(vs);
3862     }
3863 
3864     qapi_free_SocketAddress(saddr);
3865     qapi_free_SocketAddress(wsaddr);
3866     return;
3867 
3868 fail:
3869     qapi_free_SocketAddress(saddr);
3870     qapi_free_SocketAddress(wsaddr);
3871     vs->enabled = false;
3872     vs->ws_enabled = false;
3873 }
3874 
3875 void vnc_display_add_client(const char *id, int csock, bool skipauth)
3876 {
3877     VncDisplay *vs = vnc_display_find(id);
3878     QIOChannelSocket *sioc;
3879 
3880     if (!vs) {
3881         return;
3882     }
3883 
3884     sioc = qio_channel_socket_new_fd(csock, NULL);
3885     if (sioc) {
3886         vnc_connect(vs, sioc, skipauth, false);
3887         object_unref(OBJECT(sioc));
3888     }
3889 }
3890 
3891 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
3892 {
3893     int i = 2;
3894     char *id;
3895 
3896     id = g_strdup("default");
3897     while (qemu_opts_find(olist, id)) {
3898         g_free(id);
3899         id = g_strdup_printf("vnc%d", i++);
3900     }
3901     qemu_opts_set_id(opts, id);
3902 }
3903 
3904 QemuOpts *vnc_parse(const char *str, Error **errp)
3905 {
3906     QemuOptsList *olist = qemu_find_opts("vnc");
3907     QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
3908     const char *id;
3909 
3910     if (!opts) {
3911         return NULL;
3912     }
3913 
3914     id = qemu_opts_id(opts);
3915     if (!id) {
3916         /* auto-assign id if not present */
3917         vnc_auto_assign_id(olist, opts);
3918     }
3919     return opts;
3920 }
3921 
3922 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
3923 {
3924     Error *local_err = NULL;
3925     char *id = (char *)qemu_opts_id(opts);
3926 
3927     assert(id);
3928     vnc_display_init(id);
3929     vnc_display_open(id, &local_err);
3930     if (local_err != NULL) {
3931         error_reportf_err(local_err, "Failed to start VNC server: ");
3932         exit(1);
3933     }
3934     return 0;
3935 }
3936 
3937 static void vnc_register_config(void)
3938 {
3939     qemu_add_opts(&qemu_vnc_opts);
3940 }
3941 opts_init(vnc_register_config);
3942