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