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