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