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