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