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