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