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