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