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