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