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