xref: /openbmc/qemu/ui/vnc.c (revision ed75658a)
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(surface);
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 = qemu_console_get_cursor(vs->vd->dcl.con);
992     int isize;
993 
994     if (!c) {
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     g_free(vd->cursor_mask);
1033     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
1034     vd->cursor_mask = g_malloc0(vd->cursor_msize);
1035     cursor_get_mono_mask(c, 0, vd->cursor_mask);
1036 
1037     QTAILQ_FOREACH(vs, &vd->clients, next) {
1038         vnc_cursor_define(vs);
1039     }
1040 }
1041 
1042 static int find_and_clear_dirty_height(VncState *vs,
1043                                        int y, int last_x, int x, int height)
1044 {
1045     int h;
1046 
1047     for (h = 1; h < (height - y); h++) {
1048         if (!test_bit(last_x, vs->dirty[y + h])) {
1049             break;
1050         }
1051         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1052     }
1053 
1054     return h;
1055 }
1056 
1057 /*
1058  * Figure out how much pending data we should allow in the output
1059  * buffer before we throttle incremental display updates, and/or
1060  * drop audio samples.
1061  *
1062  * We allow for equiv of 1 full display's worth of FB updates,
1063  * and 1 second of audio samples. If audio backlog was larger
1064  * than that the client would already suffering awful audio
1065  * glitches, so dropping samples is no worse really).
1066  */
1067 static void vnc_update_throttle_offset(VncState *vs)
1068 {
1069     size_t offset =
1070         vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1071 
1072     if (vs->audio_cap) {
1073         int bps;
1074         switch (vs->as.fmt) {
1075         default:
1076         case  AUDIO_FORMAT_U8:
1077         case  AUDIO_FORMAT_S8:
1078             bps = 1;
1079             break;
1080         case  AUDIO_FORMAT_U16:
1081         case  AUDIO_FORMAT_S16:
1082             bps = 2;
1083             break;
1084         case  AUDIO_FORMAT_U32:
1085         case  AUDIO_FORMAT_S32:
1086             bps = 4;
1087             break;
1088         }
1089         offset += vs->as.freq * bps * vs->as.nchannels;
1090     }
1091 
1092     /* Put a floor of 1MB on offset, so that if we have a large pending
1093      * buffer and the display is resized to a small size & back again
1094      * we don't suddenly apply a tiny send limit
1095      */
1096     offset = MAX(offset, 1024 * 1024);
1097 
1098     if (vs->throttle_output_offset != offset) {
1099         trace_vnc_client_throttle_threshold(
1100             vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1101             vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1102     }
1103 
1104     vs->throttle_output_offset = offset;
1105 }
1106 
1107 static bool vnc_should_update(VncState *vs)
1108 {
1109     switch (vs->update) {
1110     case VNC_STATE_UPDATE_NONE:
1111         break;
1112     case VNC_STATE_UPDATE_INCREMENTAL:
1113         /* Only allow incremental updates if the pending send queue
1114          * is less than the permitted threshold, and the job worker
1115          * is completely idle.
1116          */
1117         if (vs->output.offset < vs->throttle_output_offset &&
1118             vs->job_update == VNC_STATE_UPDATE_NONE) {
1119             return true;
1120         }
1121         trace_vnc_client_throttle_incremental(
1122             vs, vs->ioc, vs->job_update, vs->output.offset);
1123         break;
1124     case VNC_STATE_UPDATE_FORCE:
1125         /* Only allow forced updates if the pending send queue
1126          * does not contain a previous forced update, and the
1127          * job worker is completely idle.
1128          *
1129          * Note this means we'll queue a forced update, even if
1130          * the output buffer size is otherwise over the throttle
1131          * output limit.
1132          */
1133         if (vs->force_update_offset == 0 &&
1134             vs->job_update == VNC_STATE_UPDATE_NONE) {
1135             return true;
1136         }
1137         trace_vnc_client_throttle_forced(
1138             vs, vs->ioc, vs->job_update, vs->force_update_offset);
1139         break;
1140     }
1141     return false;
1142 }
1143 
1144 static int vnc_update_client(VncState *vs, int has_dirty)
1145 {
1146     VncDisplay *vd = vs->vd;
1147     VncJob *job;
1148     int y;
1149     int height, width;
1150     int n = 0;
1151 
1152     if (vs->disconnecting) {
1153         vnc_disconnect_finish(vs);
1154         return 0;
1155     }
1156 
1157     vs->has_dirty += has_dirty;
1158     if (!vnc_should_update(vs)) {
1159         return 0;
1160     }
1161 
1162     if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1163         return 0;
1164     }
1165 
1166     /*
1167      * Send screen updates to the vnc client using the server
1168      * surface and server dirty map.  guest surface updates
1169      * happening in parallel don't disturb us, the next pass will
1170      * send them to the client.
1171      */
1172     job = vnc_job_new(vs);
1173 
1174     height = pixman_image_get_height(vd->server);
1175     width = pixman_image_get_width(vd->server);
1176 
1177     y = 0;
1178     for (;;) {
1179         int x, h;
1180         unsigned long x2;
1181         unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1182                                              height * VNC_DIRTY_BPL(vs),
1183                                              y * VNC_DIRTY_BPL(vs));
1184         if (offset == height * VNC_DIRTY_BPL(vs)) {
1185             /* no more dirty bits */
1186             break;
1187         }
1188         y = offset / VNC_DIRTY_BPL(vs);
1189         x = offset % VNC_DIRTY_BPL(vs);
1190         x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1191                                 VNC_DIRTY_BPL(vs), x);
1192         bitmap_clear(vs->dirty[y], x, x2 - x);
1193         h = find_and_clear_dirty_height(vs, y, x, x2, height);
1194         x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1195         if (x2 > x) {
1196             n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1197                                   (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1198         }
1199         if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1200             y += h;
1201             if (y == height) {
1202                 break;
1203             }
1204         }
1205     }
1206 
1207     vs->job_update = vs->update;
1208     vs->update = VNC_STATE_UPDATE_NONE;
1209     vnc_job_push(job);
1210     vs->has_dirty = 0;
1211     return n;
1212 }
1213 
1214 /* audio */
1215 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1216 {
1217     VncState *vs = opaque;
1218 
1219     assert(vs->magic == VNC_MAGIC);
1220     switch (cmd) {
1221     case AUD_CNOTIFY_DISABLE:
1222         trace_vnc_msg_server_audio_end(vs, vs->ioc);
1223         vnc_lock_output(vs);
1224         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1225         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1226         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1227         vnc_unlock_output(vs);
1228         vnc_flush(vs);
1229         break;
1230 
1231     case AUD_CNOTIFY_ENABLE:
1232         trace_vnc_msg_server_audio_begin(vs, vs->ioc);
1233         vnc_lock_output(vs);
1234         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1235         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1236         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1237         vnc_unlock_output(vs);
1238         vnc_flush(vs);
1239         break;
1240     }
1241 }
1242 
1243 static void audio_capture_destroy(void *opaque)
1244 {
1245 }
1246 
1247 static void audio_capture(void *opaque, const void *buf, int size)
1248 {
1249     VncState *vs = opaque;
1250 
1251     assert(vs->magic == VNC_MAGIC);
1252     trace_vnc_msg_server_audio_data(vs, vs->ioc, buf, size);
1253     vnc_lock_output(vs);
1254     if (vs->output.offset < vs->throttle_output_offset) {
1255         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1256         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1257         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1258         vnc_write_u32(vs, size);
1259         vnc_write(vs, buf, size);
1260     } else {
1261         trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1262     }
1263     vnc_unlock_output(vs);
1264     vnc_flush(vs);
1265 }
1266 
1267 static void audio_add(VncState *vs)
1268 {
1269     struct audio_capture_ops ops;
1270 
1271     if (vs->audio_cap) {
1272         error_report("audio already running");
1273         return;
1274     }
1275 
1276     ops.notify = audio_capture_notify;
1277     ops.destroy = audio_capture_destroy;
1278     ops.capture = audio_capture;
1279 
1280     vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
1281     if (!vs->audio_cap) {
1282         error_report("Failed to add audio capture");
1283     }
1284 }
1285 
1286 static void audio_del(VncState *vs)
1287 {
1288     if (vs->audio_cap) {
1289         AUD_del_capture(vs->audio_cap, vs);
1290         vs->audio_cap = NULL;
1291     }
1292 }
1293 
1294 static void vnc_disconnect_start(VncState *vs)
1295 {
1296     if (vs->disconnecting) {
1297         return;
1298     }
1299     trace_vnc_client_disconnect_start(vs, vs->ioc);
1300     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1301     if (vs->ioc_tag) {
1302         g_source_remove(vs->ioc_tag);
1303         vs->ioc_tag = 0;
1304     }
1305     qio_channel_close(vs->ioc, NULL);
1306     vs->disconnecting = TRUE;
1307 }
1308 
1309 void vnc_disconnect_finish(VncState *vs)
1310 {
1311     int i;
1312 
1313     trace_vnc_client_disconnect_finish(vs, vs->ioc);
1314 
1315     vnc_jobs_join(vs); /* Wait encoding jobs */
1316 
1317     vnc_lock_output(vs);
1318     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1319 
1320     buffer_free(&vs->input);
1321     buffer_free(&vs->output);
1322 
1323     qapi_free_VncClientInfo(vs->info);
1324 
1325     vnc_zlib_clear(vs);
1326     vnc_tight_clear(vs);
1327     vnc_zrle_clear(vs);
1328 
1329 #ifdef CONFIG_VNC_SASL
1330     vnc_sasl_client_cleanup(vs);
1331 #endif /* CONFIG_VNC_SASL */
1332     audio_del(vs);
1333     qkbd_state_lift_all_keys(vs->vd->kbd);
1334 
1335     if (vs->mouse_mode_notifier.notify != NULL) {
1336         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1337     }
1338     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1339     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1340         /* last client gone */
1341         vnc_update_server_surface(vs->vd);
1342     }
1343     vnc_unlock_output(vs);
1344 
1345     if (vs->cbpeer.notifier.notify) {
1346         qemu_clipboard_peer_unregister(&vs->cbpeer);
1347     }
1348 
1349     qemu_mutex_destroy(&vs->output_mutex);
1350     if (vs->bh != NULL) {
1351         qemu_bh_delete(vs->bh);
1352     }
1353     buffer_free(&vs->jobs_buffer);
1354 
1355     for (i = 0; i < VNC_STAT_ROWS; ++i) {
1356         g_free(vs->lossy_rect[i]);
1357     }
1358     g_free(vs->lossy_rect);
1359 
1360     object_unref(OBJECT(vs->ioc));
1361     vs->ioc = NULL;
1362     object_unref(OBJECT(vs->sioc));
1363     vs->sioc = NULL;
1364     vs->magic = 0;
1365     g_free(vs->zrle);
1366     g_free(vs->tight);
1367     g_free(vs);
1368 }
1369 
1370 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
1371 {
1372     if (ret <= 0) {
1373         if (ret == 0) {
1374             trace_vnc_client_eof(vs, vs->ioc);
1375             vnc_disconnect_start(vs);
1376         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1377             trace_vnc_client_io_error(vs, vs->ioc,
1378                                       err ? error_get_pretty(err) : "Unknown");
1379             vnc_disconnect_start(vs);
1380         }
1381 
1382         error_free(err);
1383         return 0;
1384     }
1385     return ret;
1386 }
1387 
1388 
1389 void vnc_client_error(VncState *vs)
1390 {
1391     VNC_DEBUG("Closing down client sock: protocol error\n");
1392     vnc_disconnect_start(vs);
1393 }
1394 
1395 
1396 /*
1397  * Called to write a chunk of data to the client socket. The data may
1398  * be the raw data, or may have already been encoded by SASL.
1399  * The data will be written either straight onto the socket, or
1400  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1401  *
1402  * NB, it is theoretically possible to have 2 layers of encryption,
1403  * both SASL, and this TLS layer. It is highly unlikely in practice
1404  * though, since SASL encryption will typically be a no-op if TLS
1405  * is active
1406  *
1407  * Returns the number of bytes written, which may be less than
1408  * the requested 'datalen' if the socket would block. Returns
1409  * 0 on I/O error, and disconnects the client socket.
1410  */
1411 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1412 {
1413     Error *err = NULL;
1414     ssize_t ret;
1415     ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
1416     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1417     return vnc_client_io_error(vs, ret, err);
1418 }
1419 
1420 
1421 /*
1422  * Called to write buffered data to the client socket, when not
1423  * using any SASL SSF encryption layers. Will write as much data
1424  * as possible without blocking. If all buffered data is written,
1425  * will switch the FD poll() handler back to read monitoring.
1426  *
1427  * Returns the number of bytes written, which may be less than
1428  * the buffered output data if the socket would block.  Returns
1429  * 0 on I/O error, and disconnects the client socket.
1430  */
1431 static size_t vnc_client_write_plain(VncState *vs)
1432 {
1433     size_t offset;
1434     size_t ret;
1435 
1436 #ifdef CONFIG_VNC_SASL
1437     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1438               vs->output.buffer, vs->output.capacity, vs->output.offset,
1439               vs->sasl.waitWriteSSF);
1440 
1441     if (vs->sasl.conn &&
1442         vs->sasl.runSSF &&
1443         vs->sasl.waitWriteSSF) {
1444         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1445         if (ret)
1446             vs->sasl.waitWriteSSF -= ret;
1447     } else
1448 #endif /* CONFIG_VNC_SASL */
1449         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1450     if (!ret)
1451         return 0;
1452 
1453     if (ret >= vs->force_update_offset) {
1454         if (vs->force_update_offset != 0) {
1455             trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1456         }
1457         vs->force_update_offset = 0;
1458     } else {
1459         vs->force_update_offset -= ret;
1460     }
1461     offset = vs->output.offset;
1462     buffer_advance(&vs->output, ret);
1463     if (offset >= vs->throttle_output_offset &&
1464         vs->output.offset < vs->throttle_output_offset) {
1465         trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1466     }
1467 
1468     if (vs->output.offset == 0) {
1469         if (vs->ioc_tag) {
1470             g_source_remove(vs->ioc_tag);
1471         }
1472         vs->ioc_tag = qio_channel_add_watch(
1473             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1474             vnc_client_io, vs, NULL);
1475     }
1476 
1477     return ret;
1478 }
1479 
1480 
1481 /*
1482  * First function called whenever there is data to be written to
1483  * the client socket. Will delegate actual work according to whether
1484  * SASL SSF layers are enabled (thus requiring encryption calls)
1485  */
1486 static void vnc_client_write_locked(VncState *vs)
1487 {
1488 #ifdef CONFIG_VNC_SASL
1489     if (vs->sasl.conn &&
1490         vs->sasl.runSSF &&
1491         !vs->sasl.waitWriteSSF) {
1492         vnc_client_write_sasl(vs);
1493     } else
1494 #endif /* CONFIG_VNC_SASL */
1495     {
1496         vnc_client_write_plain(vs);
1497     }
1498 }
1499 
1500 static void vnc_client_write(VncState *vs)
1501 {
1502     assert(vs->magic == VNC_MAGIC);
1503     vnc_lock_output(vs);
1504     if (vs->output.offset) {
1505         vnc_client_write_locked(vs);
1506     } else if (vs->ioc != NULL) {
1507         if (vs->ioc_tag) {
1508             g_source_remove(vs->ioc_tag);
1509         }
1510         vs->ioc_tag = qio_channel_add_watch(
1511             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1512             vnc_client_io, vs, NULL);
1513     }
1514     vnc_unlock_output(vs);
1515 }
1516 
1517 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1518 {
1519     vs->read_handler = func;
1520     vs->read_handler_expect = expecting;
1521 }
1522 
1523 
1524 /*
1525  * Called to read a chunk of data from the client socket. The data may
1526  * be the raw data, or may need to be further decoded by SASL.
1527  * The data will be read either straight from to the socket, or
1528  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1529  *
1530  * NB, it is theoretically possible to have 2 layers of encryption,
1531  * both SASL, and this TLS layer. It is highly unlikely in practice
1532  * though, since SASL encryption will typically be a no-op if TLS
1533  * is active
1534  *
1535  * Returns the number of bytes read, which may be less than
1536  * the requested 'datalen' if the socket would block. Returns
1537  * 0 on I/O error or EOF, and disconnects the client socket.
1538  */
1539 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1540 {
1541     ssize_t ret;
1542     Error *err = NULL;
1543     ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
1544     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1545     return vnc_client_io_error(vs, ret, err);
1546 }
1547 
1548 
1549 /*
1550  * Called to read data from the client socket to the input buffer,
1551  * when not using any SASL SSF encryption layers. Will read as much
1552  * data as possible without blocking.
1553  *
1554  * Returns the number of bytes read, which may be less than
1555  * the requested 'datalen' if the socket would block. Returns
1556  * 0 on I/O error or EOF, and disconnects the client socket.
1557  */
1558 static size_t vnc_client_read_plain(VncState *vs)
1559 {
1560     size_t ret;
1561     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1562               vs->input.buffer, vs->input.capacity, vs->input.offset);
1563     buffer_reserve(&vs->input, 4096);
1564     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1565     if (!ret)
1566         return 0;
1567     vs->input.offset += ret;
1568     return ret;
1569 }
1570 
1571 static void vnc_jobs_bh(void *opaque)
1572 {
1573     VncState *vs = opaque;
1574 
1575     assert(vs->magic == VNC_MAGIC);
1576     vnc_jobs_consume_buffer(vs);
1577 }
1578 
1579 /*
1580  * First function called whenever there is more data to be read from
1581  * the client socket. Will delegate actual work according to whether
1582  * SASL SSF layers are enabled (thus requiring decryption calls)
1583  * Returns 0 on success, -1 if client disconnected
1584  */
1585 static int vnc_client_read(VncState *vs)
1586 {
1587     size_t sz;
1588 
1589 #ifdef CONFIG_VNC_SASL
1590     if (vs->sasl.conn && vs->sasl.runSSF)
1591         sz = vnc_client_read_sasl(vs);
1592     else
1593 #endif /* CONFIG_VNC_SASL */
1594         sz = vnc_client_read_plain(vs);
1595     if (!sz) {
1596         if (vs->disconnecting) {
1597             vnc_disconnect_finish(vs);
1598             return -1;
1599         }
1600         return 0;
1601     }
1602 
1603     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1604         size_t len = vs->read_handler_expect;
1605         int ret;
1606 
1607         ret = vs->read_handler(vs, vs->input.buffer, len);
1608         if (vs->disconnecting) {
1609             vnc_disconnect_finish(vs);
1610             return -1;
1611         }
1612 
1613         if (!ret) {
1614             buffer_advance(&vs->input, len);
1615         } else {
1616             vs->read_handler_expect = ret;
1617         }
1618     }
1619     return 0;
1620 }
1621 
1622 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1623                        GIOCondition condition, void *opaque)
1624 {
1625     VncState *vs = opaque;
1626 
1627     assert(vs->magic == VNC_MAGIC);
1628 
1629     if (condition & (G_IO_HUP | G_IO_ERR)) {
1630         vnc_disconnect_start(vs);
1631         return TRUE;
1632     }
1633 
1634     if (condition & G_IO_IN) {
1635         if (vnc_client_read(vs) < 0) {
1636             /* vs is free()ed here */
1637             return TRUE;
1638         }
1639     }
1640     if (condition & G_IO_OUT) {
1641         vnc_client_write(vs);
1642     }
1643 
1644     if (vs->disconnecting) {
1645         if (vs->ioc_tag != 0) {
1646             g_source_remove(vs->ioc_tag);
1647         }
1648         vs->ioc_tag = 0;
1649     }
1650     return TRUE;
1651 }
1652 
1653 
1654 /*
1655  * Scale factor to apply to vs->throttle_output_offset when checking for
1656  * hard limit. Worst case normal usage could be x2, if we have a complete
1657  * incremental update and complete forced update in the output buffer.
1658  * So x3 should be good enough, but we pick x5 to be conservative and thus
1659  * (hopefully) never trigger incorrectly.
1660  */
1661 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1662 
1663 void vnc_write(VncState *vs, const void *data, size_t len)
1664 {
1665     assert(vs->magic == VNC_MAGIC);
1666     if (vs->disconnecting) {
1667         return;
1668     }
1669     /* Protection against malicious client/guest to prevent our output
1670      * buffer growing without bound if client stops reading data. This
1671      * should rarely trigger, because we have earlier throttling code
1672      * which stops issuing framebuffer updates and drops audio data
1673      * if the throttle_output_offset value is exceeded. So we only reach
1674      * this higher level if a huge number of pseudo-encodings get
1675      * triggered while data can't be sent on the socket.
1676      *
1677      * NB throttle_output_offset can be zero during early protocol
1678      * handshake, or from the job thread's VncState clone
1679      */
1680     if (vs->throttle_output_offset != 0 &&
1681         (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1682         vs->throttle_output_offset) {
1683         trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1684                                       vs->throttle_output_offset);
1685         vnc_disconnect_start(vs);
1686         return;
1687     }
1688     buffer_reserve(&vs->output, len);
1689 
1690     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1691         if (vs->ioc_tag) {
1692             g_source_remove(vs->ioc_tag);
1693         }
1694         vs->ioc_tag = qio_channel_add_watch(
1695             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
1696             vnc_client_io, vs, NULL);
1697     }
1698 
1699     buffer_append(&vs->output, data, len);
1700 }
1701 
1702 void vnc_write_s32(VncState *vs, int32_t value)
1703 {
1704     vnc_write_u32(vs, *(uint32_t *)&value);
1705 }
1706 
1707 void vnc_write_u32(VncState *vs, uint32_t value)
1708 {
1709     uint8_t buf[4];
1710 
1711     buf[0] = (value >> 24) & 0xFF;
1712     buf[1] = (value >> 16) & 0xFF;
1713     buf[2] = (value >>  8) & 0xFF;
1714     buf[3] = value & 0xFF;
1715 
1716     vnc_write(vs, buf, 4);
1717 }
1718 
1719 void vnc_write_u16(VncState *vs, uint16_t value)
1720 {
1721     uint8_t buf[2];
1722 
1723     buf[0] = (value >> 8) & 0xFF;
1724     buf[1] = value & 0xFF;
1725 
1726     vnc_write(vs, buf, 2);
1727 }
1728 
1729 void vnc_write_u8(VncState *vs, uint8_t value)
1730 {
1731     vnc_write(vs, (char *)&value, 1);
1732 }
1733 
1734 void vnc_flush(VncState *vs)
1735 {
1736     vnc_lock_output(vs);
1737     if (vs->ioc != NULL && vs->output.offset) {
1738         vnc_client_write_locked(vs);
1739     }
1740     if (vs->disconnecting) {
1741         if (vs->ioc_tag != 0) {
1742             g_source_remove(vs->ioc_tag);
1743         }
1744         vs->ioc_tag = 0;
1745     }
1746     vnc_unlock_output(vs);
1747 }
1748 
1749 static uint8_t read_u8(uint8_t *data, size_t offset)
1750 {
1751     return data[offset];
1752 }
1753 
1754 static uint16_t read_u16(uint8_t *data, size_t offset)
1755 {
1756     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1757 }
1758 
1759 static int32_t read_s32(uint8_t *data, size_t offset)
1760 {
1761     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1762                      (data[offset + 2] << 8) | data[offset + 3]);
1763 }
1764 
1765 uint32_t read_u32(uint8_t *data, size_t offset)
1766 {
1767     return ((data[offset] << 24) | (data[offset + 1] << 16) |
1768             (data[offset + 2] << 8) | data[offset + 3]);
1769 }
1770 
1771 static void check_pointer_type_change(Notifier *notifier, void *data)
1772 {
1773     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1774     int absolute = qemu_input_is_absolute(vs->vd->dcl.con);
1775 
1776     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1777         vnc_lock_output(vs);
1778         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1779         vnc_write_u8(vs, 0);
1780         vnc_write_u16(vs, 1);
1781         vnc_framebuffer_update(vs, absolute, 0,
1782                                pixman_image_get_width(vs->vd->server),
1783                                pixman_image_get_height(vs->vd->server),
1784                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1785         vnc_unlock_output(vs);
1786         vnc_flush(vs);
1787     }
1788     vs->absolute = absolute;
1789 }
1790 
1791 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1792 {
1793     static uint32_t bmap[INPUT_BUTTON__MAX] = {
1794         [INPUT_BUTTON_LEFT]       = 0x01,
1795         [INPUT_BUTTON_MIDDLE]     = 0x02,
1796         [INPUT_BUTTON_RIGHT]      = 0x04,
1797         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1798         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1799     };
1800     QemuConsole *con = vs->vd->dcl.con;
1801     int width = pixman_image_get_width(vs->vd->server);
1802     int height = pixman_image_get_height(vs->vd->server);
1803 
1804     if (vs->last_bmask != button_mask) {
1805         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1806         vs->last_bmask = button_mask;
1807     }
1808 
1809     if (vs->absolute) {
1810         qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1811         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1812     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1813         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1814         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1815     } else {
1816         if (vs->last_x != -1) {
1817             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1818             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1819         }
1820         vs->last_x = x;
1821         vs->last_y = y;
1822     }
1823     qemu_input_event_sync();
1824 }
1825 
1826 static void press_key(VncState *vs, QKeyCode qcode)
1827 {
1828     qkbd_state_key_event(vs->vd->kbd, qcode, true);
1829     qkbd_state_key_event(vs->vd->kbd, qcode, false);
1830 }
1831 
1832 static void vnc_led_state_change(VncState *vs)
1833 {
1834     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1835         return;
1836     }
1837 
1838     vnc_lock_output(vs);
1839     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1840     vnc_write_u8(vs, 0);
1841     vnc_write_u16(vs, 1);
1842     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1843     vnc_write_u8(vs, vs->vd->ledstate);
1844     vnc_unlock_output(vs);
1845     vnc_flush(vs);
1846 }
1847 
1848 static void kbd_leds(void *opaque, int ledstate)
1849 {
1850     VncDisplay *vd = opaque;
1851     VncState *client;
1852 
1853     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1854                              (ledstate & QEMU_NUM_LOCK_LED),
1855                              (ledstate & QEMU_SCROLL_LOCK_LED));
1856 
1857     if (ledstate == vd->ledstate) {
1858         return;
1859     }
1860 
1861     vd->ledstate = ledstate;
1862 
1863     QTAILQ_FOREACH(client, &vd->clients, next) {
1864         vnc_led_state_change(client);
1865     }
1866 }
1867 
1868 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1869 {
1870     QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1871 
1872     /* QEMU console switch */
1873     switch (qcode) {
1874     case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1875         if (vs->vd->dcl.con == NULL && down &&
1876             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1877             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1878             /* Reset the modifiers sent to the current console */
1879             qkbd_state_lift_all_keys(vs->vd->kbd);
1880             console_select(qcode - Q_KEY_CODE_1);
1881             return;
1882         }
1883     default:
1884         break;
1885     }
1886 
1887     /* Turn off the lock state sync logic if the client support the led
1888        state extension.
1889     */
1890     if (down && vs->vd->lock_key_sync &&
1891         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1892         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1893         /* If the numlock state needs to change then simulate an additional
1894            keypress before sending this one.  This will happen if the user
1895            toggles numlock away from the VNC window.
1896         */
1897         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1898             if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1899                 trace_vnc_key_sync_numlock(true);
1900                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1901             }
1902         } else {
1903             if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1904                 trace_vnc_key_sync_numlock(false);
1905                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1906             }
1907         }
1908     }
1909 
1910     if (down && vs->vd->lock_key_sync &&
1911         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1912         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1913         /* If the capslock state needs to change then simulate an additional
1914            keypress before sending this one.  This will happen if the user
1915            toggles capslock away from the VNC window.
1916         */
1917         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1918         bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1919         bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1920         if (capslock) {
1921             if (uppercase == shift) {
1922                 trace_vnc_key_sync_capslock(false);
1923                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1924             }
1925         } else {
1926             if (uppercase != shift) {
1927                 trace_vnc_key_sync_capslock(true);
1928                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1929             }
1930         }
1931     }
1932 
1933     qkbd_state_key_event(vs->vd->kbd, qcode, down);
1934     if (!qemu_console_is_graphic(vs->vd->dcl.con)) {
1935         QemuTextConsole *con = QEMU_TEXT_CONSOLE(vs->vd->dcl.con);
1936         bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1937         bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1938         /* QEMU console emulation */
1939         if (down) {
1940             switch (keycode) {
1941             case 0x2a:                          /* Left Shift */
1942             case 0x36:                          /* Right Shift */
1943             case 0x1d:                          /* Left CTRL */
1944             case 0x9d:                          /* Right CTRL */
1945             case 0x38:                          /* Left ALT */
1946             case 0xb8:                          /* Right ALT */
1947                 break;
1948             case 0xc8:
1949                 qemu_text_console_put_keysym(con, QEMU_KEY_UP);
1950                 break;
1951             case 0xd0:
1952                 qemu_text_console_put_keysym(con, QEMU_KEY_DOWN);
1953                 break;
1954             case 0xcb:
1955                 qemu_text_console_put_keysym(con, QEMU_KEY_LEFT);
1956                 break;
1957             case 0xcd:
1958                 qemu_text_console_put_keysym(con, QEMU_KEY_RIGHT);
1959                 break;
1960             case 0xd3:
1961                 qemu_text_console_put_keysym(con, QEMU_KEY_DELETE);
1962                 break;
1963             case 0xc7:
1964                 qemu_text_console_put_keysym(con, QEMU_KEY_HOME);
1965                 break;
1966             case 0xcf:
1967                 qemu_text_console_put_keysym(con, QEMU_KEY_END);
1968                 break;
1969             case 0xc9:
1970                 qemu_text_console_put_keysym(con, QEMU_KEY_PAGEUP);
1971                 break;
1972             case 0xd1:
1973                 qemu_text_console_put_keysym(con, QEMU_KEY_PAGEDOWN);
1974                 break;
1975 
1976             case 0x47:
1977                 qemu_text_console_put_keysym(con, numlock ? '7' : QEMU_KEY_HOME);
1978                 break;
1979             case 0x48:
1980                 qemu_text_console_put_keysym(con, numlock ? '8' : QEMU_KEY_UP);
1981                 break;
1982             case 0x49:
1983                 qemu_text_console_put_keysym(con, numlock ? '9' : QEMU_KEY_PAGEUP);
1984                 break;
1985             case 0x4b:
1986                 qemu_text_console_put_keysym(con, numlock ? '4' : QEMU_KEY_LEFT);
1987                 break;
1988             case 0x4c:
1989                 qemu_text_console_put_keysym(con, '5');
1990                 break;
1991             case 0x4d:
1992                 qemu_text_console_put_keysym(con, numlock ? '6' : QEMU_KEY_RIGHT);
1993                 break;
1994             case 0x4f:
1995                 qemu_text_console_put_keysym(con, numlock ? '1' : QEMU_KEY_END);
1996                 break;
1997             case 0x50:
1998                 qemu_text_console_put_keysym(con, numlock ? '2' : QEMU_KEY_DOWN);
1999                 break;
2000             case 0x51:
2001                 qemu_text_console_put_keysym(con, numlock ? '3' : QEMU_KEY_PAGEDOWN);
2002                 break;
2003             case 0x52:
2004                 qemu_text_console_put_keysym(con, '0');
2005                 break;
2006             case 0x53:
2007                 qemu_text_console_put_keysym(con, numlock ? '.' : QEMU_KEY_DELETE);
2008                 break;
2009 
2010             case 0xb5:
2011                 qemu_text_console_put_keysym(con, '/');
2012                 break;
2013             case 0x37:
2014                 qemu_text_console_put_keysym(con, '*');
2015                 break;
2016             case 0x4a:
2017                 qemu_text_console_put_keysym(con, '-');
2018                 break;
2019             case 0x4e:
2020                 qemu_text_console_put_keysym(con, '+');
2021                 break;
2022             case 0x9c:
2023                 qemu_text_console_put_keysym(con, '\n');
2024                 break;
2025 
2026             default:
2027                 if (control) {
2028                     qemu_text_console_put_keysym(con, sym & 0x1f);
2029                 } else {
2030                     qemu_text_console_put_keysym(con, sym);
2031                 }
2032                 break;
2033             }
2034         }
2035     }
2036 }
2037 
2038 static const char *code2name(int keycode)
2039 {
2040     return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
2041 }
2042 
2043 static void key_event(VncState *vs, int down, uint32_t sym)
2044 {
2045     int keycode;
2046     int lsym = sym;
2047 
2048     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(vs->vd->dcl.con)) {
2049         lsym = lsym - 'A' + 'a';
2050     }
2051 
2052     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
2053                               vs->vd->kbd, down) & SCANCODE_KEYMASK;
2054     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
2055     do_key_event(vs, down, keycode, sym);
2056 }
2057 
2058 static void ext_key_event(VncState *vs, int down,
2059                           uint32_t sym, uint16_t keycode)
2060 {
2061     /* if the user specifies a keyboard layout, always use it */
2062     if (keyboard_layout) {
2063         key_event(vs, down, sym);
2064     } else {
2065         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2066         do_key_event(vs, down, keycode, sym);
2067     }
2068 }
2069 
2070 static void framebuffer_update_request(VncState *vs, int incremental,
2071                                        int x, int y, int w, int h)
2072 {
2073     if (incremental) {
2074         if (vs->update != VNC_STATE_UPDATE_FORCE) {
2075             vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2076         }
2077     } else {
2078         vs->update = VNC_STATE_UPDATE_FORCE;
2079         vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2080         if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
2081             vnc_desktop_resize_ext(vs, 0);
2082         }
2083     }
2084 }
2085 
2086 static void send_ext_key_event_ack(VncState *vs)
2087 {
2088     vnc_lock_output(vs);
2089     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2090     vnc_write_u8(vs, 0);
2091     vnc_write_u16(vs, 1);
2092     vnc_framebuffer_update(vs, 0, 0,
2093                            pixman_image_get_width(vs->vd->server),
2094                            pixman_image_get_height(vs->vd->server),
2095                            VNC_ENCODING_EXT_KEY_EVENT);
2096     vnc_unlock_output(vs);
2097     vnc_flush(vs);
2098 }
2099 
2100 static void send_ext_audio_ack(VncState *vs)
2101 {
2102     vnc_lock_output(vs);
2103     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2104     vnc_write_u8(vs, 0);
2105     vnc_write_u16(vs, 1);
2106     vnc_framebuffer_update(vs, 0, 0,
2107                            pixman_image_get_width(vs->vd->server),
2108                            pixman_image_get_height(vs->vd->server),
2109                            VNC_ENCODING_AUDIO);
2110     vnc_unlock_output(vs);
2111     vnc_flush(vs);
2112 }
2113 
2114 static void send_xvp_message(VncState *vs, int code)
2115 {
2116     vnc_lock_output(vs);
2117     vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
2118     vnc_write_u8(vs, 0); /* pad */
2119     vnc_write_u8(vs, 1); /* version */
2120     vnc_write_u8(vs, code);
2121     vnc_unlock_output(vs);
2122     vnc_flush(vs);
2123 }
2124 
2125 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2126 {
2127     int i;
2128     unsigned int enc = 0;
2129 
2130     vs->features = 0;
2131     vs->vnc_encoding = 0;
2132     vs->tight->compression = 9;
2133     vs->tight->quality = -1; /* Lossless by default */
2134     vs->absolute = -1;
2135 
2136     /*
2137      * Start from the end because the encodings are sent in order of preference.
2138      * This way the preferred encoding (first encoding defined in the array)
2139      * will be set at the end of the loop.
2140      */
2141     for (i = n_encodings - 1; i >= 0; i--) {
2142         enc = encodings[i];
2143         switch (enc) {
2144         case VNC_ENCODING_RAW:
2145             vs->vnc_encoding = enc;
2146             break;
2147         case VNC_ENCODING_HEXTILE:
2148             vnc_set_feature(vs, VNC_FEATURE_HEXTILE);
2149             vs->vnc_encoding = enc;
2150             break;
2151         case VNC_ENCODING_TIGHT:
2152             vnc_set_feature(vs, VNC_FEATURE_TIGHT);
2153             vs->vnc_encoding = enc;
2154             break;
2155 #ifdef CONFIG_PNG
2156         case VNC_ENCODING_TIGHT_PNG:
2157             vnc_set_feature(vs, VNC_FEATURE_TIGHT_PNG);
2158             vs->vnc_encoding = enc;
2159             break;
2160 #endif
2161         case VNC_ENCODING_ZLIB:
2162             /*
2163              * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2164              * So prioritize ZRLE, even if the client hints that it prefers
2165              * ZLIB.
2166              */
2167             if (!vnc_has_feature(vs, VNC_FEATURE_ZRLE)) {
2168                 vnc_set_feature(vs, VNC_FEATURE_ZLIB);
2169                 vs->vnc_encoding = enc;
2170             }
2171             break;
2172         case VNC_ENCODING_ZRLE:
2173             vnc_set_feature(vs, VNC_FEATURE_ZRLE);
2174             vs->vnc_encoding = enc;
2175             break;
2176         case VNC_ENCODING_ZYWRLE:
2177             vnc_set_feature(vs, VNC_FEATURE_ZYWRLE);
2178             vs->vnc_encoding = enc;
2179             break;
2180         case VNC_ENCODING_DESKTOPRESIZE:
2181             vnc_set_feature(vs, VNC_FEATURE_RESIZE);
2182             break;
2183         case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2184             vnc_set_feature(vs, VNC_FEATURE_RESIZE_EXT);
2185             break;
2186         case VNC_ENCODING_POINTER_TYPE_CHANGE:
2187             vnc_set_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE);
2188             break;
2189         case VNC_ENCODING_RICH_CURSOR:
2190             vnc_set_feature(vs, VNC_FEATURE_RICH_CURSOR);
2191             break;
2192         case VNC_ENCODING_ALPHA_CURSOR:
2193             vnc_set_feature(vs, VNC_FEATURE_ALPHA_CURSOR);
2194             break;
2195         case VNC_ENCODING_EXT_KEY_EVENT:
2196             send_ext_key_event_ack(vs);
2197             break;
2198         case VNC_ENCODING_AUDIO:
2199             if (vs->vd->audio_state) {
2200                 vnc_set_feature(vs, VNC_FEATURE_AUDIO);
2201                 send_ext_audio_ack(vs);
2202             }
2203             break;
2204         case VNC_ENCODING_WMVi:
2205             vnc_set_feature(vs, VNC_FEATURE_WMVI);
2206             break;
2207         case VNC_ENCODING_LED_STATE:
2208             vnc_set_feature(vs, VNC_FEATURE_LED_STATE);
2209             break;
2210         case VNC_ENCODING_XVP:
2211             if (vs->vd->power_control) {
2212                 vnc_set_feature(vs, VNC_FEATURE_XVP);
2213                 send_xvp_message(vs, VNC_XVP_CODE_INIT);
2214             }
2215             break;
2216         case VNC_ENCODING_CLIPBOARD_EXT:
2217             vnc_set_feature(vs, VNC_FEATURE_CLIPBOARD_EXT);
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 (!vnc_has_feature(vs, VNC_FEATURE_CLIPBOARD_EXT)) {
2450                 error_report("vnc: extended clipboard message while disabled");
2451                 vnc_client_error(vs);
2452                 break;
2453             }
2454             if (dlen < 4) {
2455                 error_report("vnc: malformed payload (header less than 4 bytes)"
2456                              " in extended clipboard pseudo-encoding.");
2457                 vnc_client_error(vs);
2458                 break;
2459             }
2460             vnc_client_cut_text_ext(vs, dlen, read_u32(data, 8), data + 12);
2461             break;
2462         }
2463         vnc_client_cut_text(vs, read_u32(data, 4), data + 8);
2464         break;
2465     case VNC_MSG_CLIENT_XVP:
2466         if (!vnc_has_feature(vs, VNC_FEATURE_XVP)) {
2467             error_report("vnc: xvp client message while disabled");
2468             vnc_client_error(vs);
2469             break;
2470         }
2471         if (len == 1) {
2472             return 4;
2473         }
2474         if (len == 4) {
2475             uint8_t version = read_u8(data, 2);
2476             uint8_t action = read_u8(data, 3);
2477 
2478             if (version != 1) {
2479                 error_report("vnc: xvp client message version %d != 1",
2480                              version);
2481                 vnc_client_error(vs);
2482                 break;
2483             }
2484 
2485             switch (action) {
2486             case VNC_XVP_ACTION_SHUTDOWN:
2487                 qemu_system_powerdown_request();
2488                 break;
2489             case VNC_XVP_ACTION_REBOOT:
2490                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2491                 break;
2492             case VNC_XVP_ACTION_RESET:
2493                 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
2494                 break;
2495             default:
2496                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2497                 break;
2498             }
2499         }
2500         break;
2501     case VNC_MSG_CLIENT_QEMU:
2502         if (len == 1)
2503             return 2;
2504 
2505         switch (read_u8(data, 1)) {
2506         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2507             if (len == 2)
2508                 return 12;
2509 
2510             ext_key_event(vs, read_u16(data, 2),
2511                           read_u32(data, 4), read_u32(data, 8));
2512             break;
2513         case VNC_MSG_CLIENT_QEMU_AUDIO:
2514             if (!vnc_has_feature(vs, VNC_FEATURE_AUDIO)) {
2515                 error_report("Audio message %d with audio disabled", read_u8(data, 2));
2516                 vnc_client_error(vs);
2517                 break;
2518             }
2519 
2520             if (len == 2)
2521                 return 4;
2522 
2523             switch (read_u16 (data, 2)) {
2524             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2525                 trace_vnc_msg_client_audio_enable(vs, vs->ioc);
2526                 audio_add(vs);
2527                 break;
2528             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2529                 trace_vnc_msg_client_audio_disable(vs, vs->ioc);
2530                 audio_del(vs);
2531                 break;
2532             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2533                 if (len == 4)
2534                     return 10;
2535                 switch (read_u8(data, 4)) {
2536                 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
2537                 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
2538                 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
2539                 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
2540                 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
2541                 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
2542                 default:
2543                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2544                     vnc_client_error(vs);
2545                     break;
2546                 }
2547                 vs->as.nchannels = read_u8(data, 5);
2548                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2549                     VNC_DEBUG("Invalid audio channel count %d\n",
2550                               read_u8(data, 5));
2551                     vnc_client_error(vs);
2552                     break;
2553                 }
2554                 freq = read_u32(data, 6);
2555                 /* No official limit for protocol, but 48khz is a sensible
2556                  * upper bound for trustworthy clients, and this limit
2557                  * protects calculations involving 'vs->as.freq' later.
2558                  */
2559                 if (freq > 48000) {
2560                     VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2561                     vnc_client_error(vs);
2562                     break;
2563                 }
2564                 vs->as.freq = freq;
2565                 trace_vnc_msg_client_audio_format(
2566                     vs, vs->ioc, vs->as.fmt, vs->as.nchannels, vs->as.freq);
2567                 break;
2568             default:
2569                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 2));
2570                 vnc_client_error(vs);
2571                 break;
2572             }
2573             break;
2574 
2575         default:
2576             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2577             vnc_client_error(vs);
2578             break;
2579         }
2580         break;
2581     case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2582     {
2583         size_t size;
2584         uint8_t screens;
2585         int w, h;
2586 
2587         if (len < 8) {
2588             return 8;
2589         }
2590 
2591         screens = read_u8(data, 6);
2592         size    = 8 + screens * 16;
2593         if (len < size) {
2594             return size;
2595         }
2596         w = read_u16(data, 2);
2597         h = read_u16(data, 4);
2598 
2599         trace_vnc_msg_client_set_desktop_size(vs, vs->ioc, w, h, screens);
2600         if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2601             QemuUIInfo info;
2602             memset(&info, 0, sizeof(info));
2603             info.width = w;
2604             info.height = h;
2605             dpy_set_ui_info(vs->vd->dcl.con, &info, false);
2606             vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2607         } else {
2608             vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2609         }
2610 
2611         break;
2612     }
2613     default:
2614         VNC_DEBUG("Msg: %d\n", data[0]);
2615         vnc_client_error(vs);
2616         break;
2617     }
2618 
2619     vnc_update_throttle_offset(vs);
2620     vnc_read_when(vs, protocol_client_msg, 1);
2621     return 0;
2622 }
2623 
2624 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2625 {
2626     char buf[1024];
2627     VncShareMode mode;
2628     int size;
2629 
2630     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2631     switch (vs->vd->share_policy) {
2632     case VNC_SHARE_POLICY_IGNORE:
2633         /*
2634          * Ignore the shared flag.  Nothing to do here.
2635          *
2636          * Doesn't conform to the rfb spec but is traditional qemu
2637          * behavior, thus left here as option for compatibility
2638          * reasons.
2639          */
2640         break;
2641     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2642         /*
2643          * Policy: Allow clients ask for exclusive access.
2644          *
2645          * Implementation: When a client asks for exclusive access,
2646          * disconnect all others. Shared connects are allowed as long
2647          * as no exclusive connection exists.
2648          *
2649          * This is how the rfb spec suggests to handle the shared flag.
2650          */
2651         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2652             VncState *client;
2653             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2654                 if (vs == client) {
2655                     continue;
2656                 }
2657                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2658                     client->share_mode != VNC_SHARE_MODE_SHARED) {
2659                     continue;
2660                 }
2661                 vnc_disconnect_start(client);
2662             }
2663         }
2664         if (mode == VNC_SHARE_MODE_SHARED) {
2665             if (vs->vd->num_exclusive > 0) {
2666                 vnc_disconnect_start(vs);
2667                 return 0;
2668             }
2669         }
2670         break;
2671     case VNC_SHARE_POLICY_FORCE_SHARED:
2672         /*
2673          * Policy: Shared connects only.
2674          * Implementation: Disallow clients asking for exclusive access.
2675          *
2676          * Useful for shared desktop sessions where you don't want
2677          * someone forgetting to say -shared when running the vnc
2678          * client disconnect everybody else.
2679          */
2680         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2681             vnc_disconnect_start(vs);
2682             return 0;
2683         }
2684         break;
2685     }
2686     vnc_set_share_mode(vs, mode);
2687 
2688     if (vs->vd->num_shared > vs->vd->connections_limit) {
2689         vnc_disconnect_start(vs);
2690         return 0;
2691     }
2692 
2693     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2694            pixman_image_get_width(vs->vd->server) >= 0);
2695     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2696            pixman_image_get_height(vs->vd->server) >= 0);
2697     vs->client_width = pixman_image_get_width(vs->vd->server);
2698     vs->client_height = pixman_image_get_height(vs->vd->server);
2699     vnc_write_u16(vs, vs->client_width);
2700     vnc_write_u16(vs, vs->client_height);
2701 
2702     pixel_format_message(vs);
2703 
2704     if (qemu_name) {
2705         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2706         if (size > sizeof(buf)) {
2707             size = sizeof(buf);
2708         }
2709     } else {
2710         size = snprintf(buf, sizeof(buf), "QEMU");
2711     }
2712 
2713     vnc_write_u32(vs, size);
2714     vnc_write(vs, buf, size);
2715     vnc_flush(vs);
2716 
2717     vnc_client_cache_auth(vs);
2718     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2719 
2720     vnc_read_when(vs, protocol_client_msg, 1);
2721 
2722     return 0;
2723 }
2724 
2725 void start_client_init(VncState *vs)
2726 {
2727     vnc_read_when(vs, protocol_client_init, 1);
2728 }
2729 
2730 static void authentication_failed(VncState *vs)
2731 {
2732     vnc_write_u32(vs, 1); /* Reject auth */
2733     if (vs->minor >= 8) {
2734         static const char err[] = "Authentication failed";
2735         vnc_write_u32(vs, sizeof(err));
2736         vnc_write(vs, err, sizeof(err));
2737     }
2738     vnc_flush(vs);
2739     vnc_client_error(vs);
2740 }
2741 
2742 static void
2743 vnc_munge_des_rfb_key(unsigned char *key, size_t nkey)
2744 {
2745     size_t i;
2746     for (i = 0; i < nkey; i++) {
2747         uint8_t r = key[i];
2748         r = (r & 0xf0) >> 4 | (r & 0x0f) << 4;
2749         r = (r & 0xcc) >> 2 | (r & 0x33) << 2;
2750         r = (r & 0xaa) >> 1 | (r & 0x55) << 1;
2751         key[i] = r;
2752     }
2753 }
2754 
2755 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2756 {
2757     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2758     size_t i, pwlen;
2759     unsigned char key[8];
2760     time_t now = time(NULL);
2761     QCryptoCipher *cipher = NULL;
2762     Error *err = NULL;
2763 
2764     if (!vs->vd->password) {
2765         trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2766         goto reject;
2767     }
2768     if (vs->vd->expires < now) {
2769         trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2770         goto reject;
2771     }
2772 
2773     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2774 
2775     /* Calculate the expected challenge response */
2776     pwlen = strlen(vs->vd->password);
2777     for (i=0; i<sizeof(key); i++)
2778         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2779     vnc_munge_des_rfb_key(key, sizeof(key));
2780 
2781     cipher = qcrypto_cipher_new(
2782         QCRYPTO_CIPHER_ALG_DES,
2783         QCRYPTO_CIPHER_MODE_ECB,
2784         key, G_N_ELEMENTS(key),
2785         &err);
2786     if (!cipher) {
2787         trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2788                             error_get_pretty(err));
2789         error_free(err);
2790         goto reject;
2791     }
2792 
2793     if (qcrypto_cipher_encrypt(cipher,
2794                                vs->challenge,
2795                                response,
2796                                VNC_AUTH_CHALLENGE_SIZE,
2797                                &err) < 0) {
2798         trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2799                             error_get_pretty(err));
2800         error_free(err);
2801         goto reject;
2802     }
2803 
2804     /* Compare expected vs actual challenge response */
2805     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2806         trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2807         goto reject;
2808     } else {
2809         trace_vnc_auth_pass(vs, vs->auth);
2810         vnc_write_u32(vs, 0); /* Accept auth */
2811         vnc_flush(vs);
2812 
2813         start_client_init(vs);
2814     }
2815 
2816     qcrypto_cipher_free(cipher);
2817     return 0;
2818 
2819 reject:
2820     authentication_failed(vs);
2821     qcrypto_cipher_free(cipher);
2822     return 0;
2823 }
2824 
2825 void start_auth_vnc(VncState *vs)
2826 {
2827     Error *err = NULL;
2828 
2829     if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2830         trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2831                             error_get_pretty(err));
2832         error_free(err);
2833         authentication_failed(vs);
2834         return;
2835     }
2836 
2837     /* Send client a 'random' challenge */
2838     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2839     vnc_flush(vs);
2840 
2841     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2842 }
2843 
2844 
2845 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2846 {
2847     /* We only advertise 1 auth scheme at a time, so client
2848      * must pick the one we sent. Verify this */
2849     if (data[0] != vs->auth) { /* Reject auth */
2850        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2851        authentication_failed(vs);
2852     } else { /* Accept requested auth */
2853        trace_vnc_auth_start(vs, vs->auth);
2854        switch (vs->auth) {
2855        case VNC_AUTH_NONE:
2856            if (vs->minor >= 8) {
2857                vnc_write_u32(vs, 0); /* Accept auth completion */
2858                vnc_flush(vs);
2859            }
2860            trace_vnc_auth_pass(vs, vs->auth);
2861            start_client_init(vs);
2862            break;
2863 
2864        case VNC_AUTH_VNC:
2865            start_auth_vnc(vs);
2866            break;
2867 
2868        case VNC_AUTH_VENCRYPT:
2869            start_auth_vencrypt(vs);
2870            break;
2871 
2872 #ifdef CONFIG_VNC_SASL
2873        case VNC_AUTH_SASL:
2874            start_auth_sasl(vs);
2875            break;
2876 #endif /* CONFIG_VNC_SASL */
2877 
2878        default: /* Should not be possible, but just in case */
2879            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2880            authentication_failed(vs);
2881        }
2882     }
2883     return 0;
2884 }
2885 
2886 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2887 {
2888     char local[13];
2889 
2890     memcpy(local, version, 12);
2891     local[12] = 0;
2892 
2893     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2894         VNC_DEBUG("Malformed protocol version %s\n", local);
2895         vnc_client_error(vs);
2896         return 0;
2897     }
2898     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2899     if (vs->major != 3 ||
2900         (vs->minor != 3 &&
2901          vs->minor != 4 &&
2902          vs->minor != 5 &&
2903          vs->minor != 7 &&
2904          vs->minor != 8)) {
2905         VNC_DEBUG("Unsupported client version\n");
2906         vnc_write_u32(vs, VNC_AUTH_INVALID);
2907         vnc_flush(vs);
2908         vnc_client_error(vs);
2909         return 0;
2910     }
2911     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2912      * as equivalent to v3.3 by servers
2913      */
2914     if (vs->minor == 4 || vs->minor == 5)
2915         vs->minor = 3;
2916 
2917     if (vs->minor == 3) {
2918         trace_vnc_auth_start(vs, vs->auth);
2919         if (vs->auth == VNC_AUTH_NONE) {
2920             vnc_write_u32(vs, vs->auth);
2921             vnc_flush(vs);
2922             trace_vnc_auth_pass(vs, vs->auth);
2923             start_client_init(vs);
2924        } else if (vs->auth == VNC_AUTH_VNC) {
2925             VNC_DEBUG("Tell client VNC auth\n");
2926             vnc_write_u32(vs, vs->auth);
2927             vnc_flush(vs);
2928             start_auth_vnc(vs);
2929        } else {
2930             trace_vnc_auth_fail(vs, vs->auth,
2931                                 "Unsupported auth method for v3.3", "");
2932             vnc_write_u32(vs, VNC_AUTH_INVALID);
2933             vnc_flush(vs);
2934             vnc_client_error(vs);
2935        }
2936     } else {
2937         vnc_write_u8(vs, 1); /* num auth */
2938         vnc_write_u8(vs, vs->auth);
2939         vnc_read_when(vs, protocol_client_auth, 1);
2940         vnc_flush(vs);
2941     }
2942 
2943     return 0;
2944 }
2945 
2946 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2947 {
2948     struct VncSurface *vs = &vd->guest;
2949 
2950     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2951 }
2952 
2953 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2954 {
2955     int i, j;
2956 
2957     w = (x + w) / VNC_STAT_RECT;
2958     h = (y + h) / VNC_STAT_RECT;
2959     x /= VNC_STAT_RECT;
2960     y /= VNC_STAT_RECT;
2961 
2962     for (j = y; j <= h; j++) {
2963         for (i = x; i <= w; i++) {
2964             vs->lossy_rect[j][i] = 1;
2965         }
2966     }
2967 }
2968 
2969 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2970 {
2971     VncState *vs;
2972     int sty = y / VNC_STAT_RECT;
2973     int stx = x / VNC_STAT_RECT;
2974     int has_dirty = 0;
2975 
2976     y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2977     x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2978 
2979     QTAILQ_FOREACH(vs, &vd->clients, next) {
2980         int j;
2981 
2982         /* kernel send buffers are full -> refresh later */
2983         if (vs->output.offset) {
2984             continue;
2985         }
2986 
2987         if (!vs->lossy_rect[sty][stx]) {
2988             continue;
2989         }
2990 
2991         vs->lossy_rect[sty][stx] = 0;
2992         for (j = 0; j < VNC_STAT_RECT; ++j) {
2993             bitmap_set(vs->dirty[y + j],
2994                        x / VNC_DIRTY_PIXELS_PER_BIT,
2995                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2996         }
2997         has_dirty++;
2998     }
2999 
3000     return has_dirty;
3001 }
3002 
3003 static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
3004 {
3005     int width = MIN(pixman_image_get_width(vd->guest.fb),
3006                     pixman_image_get_width(vd->server));
3007     int height = MIN(pixman_image_get_height(vd->guest.fb),
3008                      pixman_image_get_height(vd->server));
3009     int x, y;
3010     struct timeval res;
3011     int has_dirty = 0;
3012 
3013     for (y = 0; y < height; y += VNC_STAT_RECT) {
3014         for (x = 0; x < width; x += VNC_STAT_RECT) {
3015             VncRectStat *rect = vnc_stat_rect(vd, x, y);
3016 
3017             rect->updated = false;
3018         }
3019     }
3020 
3021     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
3022 
3023     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
3024         return has_dirty;
3025     }
3026     vd->guest.last_freq_check = *tv;
3027 
3028     for (y = 0; y < height; y += VNC_STAT_RECT) {
3029         for (x = 0; x < width; x += VNC_STAT_RECT) {
3030             VncRectStat *rect= vnc_stat_rect(vd, x, y);
3031             int count = ARRAY_SIZE(rect->times);
3032             struct timeval min, max;
3033 
3034             if (!timerisset(&rect->times[count - 1])) {
3035                 continue ;
3036             }
3037 
3038             max = rect->times[(rect->idx + count - 1) % count];
3039             qemu_timersub(tv, &max, &res);
3040 
3041             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
3042                 rect->freq = 0;
3043                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
3044                 memset(rect->times, 0, sizeof (rect->times));
3045                 continue ;
3046             }
3047 
3048             min = rect->times[rect->idx];
3049             max = rect->times[(rect->idx + count - 1) % count];
3050             qemu_timersub(&max, &min, &res);
3051 
3052             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
3053             rect->freq /= count;
3054             rect->freq = 1. / rect->freq;
3055         }
3056     }
3057     return has_dirty;
3058 }
3059 
3060 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
3061 {
3062     int i, j;
3063     double total = 0;
3064     int num = 0;
3065 
3066     x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
3067     y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
3068 
3069     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
3070         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
3071             total += vnc_stat_rect(vs->vd, i, j)->freq;
3072             num++;
3073         }
3074     }
3075 
3076     if (num) {
3077         return total / num;
3078     } else {
3079         return 0;
3080     }
3081 }
3082 
3083 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
3084 {
3085     VncRectStat *rect;
3086 
3087     rect = vnc_stat_rect(vd, x, y);
3088     if (rect->updated) {
3089         return;
3090     }
3091     rect->times[rect->idx] = *tv;
3092     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3093     rect->updated = true;
3094 }
3095 
3096 static int vnc_refresh_server_surface(VncDisplay *vd)
3097 {
3098     int width = MIN(pixman_image_get_width(vd->guest.fb),
3099                     pixman_image_get_width(vd->server));
3100     int height = MIN(pixman_image_get_height(vd->guest.fb),
3101                      pixman_image_get_height(vd->server));
3102     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
3103     uint8_t *guest_row0 = NULL, *server_row0;
3104     VncState *vs;
3105     int has_dirty = 0;
3106     pixman_image_t *tmpbuf = NULL;
3107     unsigned long offset;
3108     int x;
3109     uint8_t *guest_ptr, *server_ptr;
3110 
3111     struct timeval tv = { 0, 0 };
3112 
3113     if (!vd->non_adaptive) {
3114         gettimeofday(&tv, NULL);
3115         has_dirty = vnc_update_stats(vd, &tv);
3116     }
3117 
3118     offset = find_next_bit((unsigned long *) &vd->guest.dirty,
3119                            height * VNC_DIRTY_BPL(&vd->guest), 0);
3120     if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
3121         /* no dirty bits in guest surface */
3122         return has_dirty;
3123     }
3124 
3125     /*
3126      * Walk through the guest dirty map.
3127      * Check and copy modified bits from guest to server surface.
3128      * Update server dirty map.
3129      */
3130     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3131     server_stride = guest_stride = guest_ll =
3132         pixman_image_get_stride(vd->server);
3133     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3134                     server_stride);
3135     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3136         int w = pixman_image_get_width(vd->server);
3137         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, w);
3138     } else {
3139         int guest_bpp =
3140             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
3141         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
3142         guest_stride = pixman_image_get_stride(vd->guest.fb);
3143         guest_ll = pixman_image_get_width(vd->guest.fb)
3144                    * DIV_ROUND_UP(guest_bpp, 8);
3145     }
3146     line_bytes = MIN(server_stride, guest_ll);
3147 
3148     for (;;) {
3149         y = offset / VNC_DIRTY_BPL(&vd->guest);
3150         x = offset % VNC_DIRTY_BPL(&vd->guest);
3151 
3152         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
3153 
3154         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3155             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
3156             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
3157         } else {
3158             guest_ptr = guest_row0 + y * guest_stride;
3159         }
3160         guest_ptr += x * cmp_bytes;
3161 
3162         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
3163              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3164             int _cmp_bytes = cmp_bytes;
3165             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
3166                 continue;
3167             }
3168             if ((x + 1) * cmp_bytes > line_bytes) {
3169                 _cmp_bytes = line_bytes - x * cmp_bytes;
3170             }
3171             assert(_cmp_bytes >= 0);
3172             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
3173                 continue;
3174             }
3175             memcpy(server_ptr, guest_ptr, _cmp_bytes);
3176             if (!vd->non_adaptive) {
3177                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
3178                                  y, &tv);
3179             }
3180             QTAILQ_FOREACH(vs, &vd->clients, next) {
3181                 set_bit(x, vs->dirty[y]);
3182             }
3183             has_dirty++;
3184         }
3185 
3186         y++;
3187         offset = find_next_bit((unsigned long *) &vd->guest.dirty,
3188                                height * VNC_DIRTY_BPL(&vd->guest),
3189                                y * VNC_DIRTY_BPL(&vd->guest));
3190         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
3191             /* no more dirty bits */
3192             break;
3193         }
3194     }
3195     qemu_pixman_image_unref(tmpbuf);
3196     return has_dirty;
3197 }
3198 
3199 static void vnc_refresh(DisplayChangeListener *dcl)
3200 {
3201     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
3202     VncState *vs, *vn;
3203     int has_dirty, rects = 0;
3204 
3205     if (QTAILQ_EMPTY(&vd->clients)) {
3206         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
3207         return;
3208     }
3209 
3210     graphic_hw_update(vd->dcl.con);
3211 
3212     if (vnc_trylock_display(vd)) {
3213         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3214         return;
3215     }
3216 
3217     has_dirty = vnc_refresh_server_surface(vd);
3218     vnc_unlock_display(vd);
3219 
3220     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3221         rects += vnc_update_client(vs, has_dirty);
3222         /* vs might be free()ed here */
3223     }
3224 
3225     if (has_dirty && rects) {
3226         vd->dcl.update_interval /= 2;
3227         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3228             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3229         }
3230     } else {
3231         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3232         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3233             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3234         }
3235     }
3236 }
3237 
3238 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3239                         bool skipauth, bool websocket)
3240 {
3241     VncState *vs = g_new0(VncState, 1);
3242     bool first_client = QTAILQ_EMPTY(&vd->clients);
3243     int i;
3244 
3245     trace_vnc_client_connect(vs, sioc);
3246     vs->zrle = g_new0(VncZrle, 1);
3247     vs->tight = g_new0(VncTight, 1);
3248     vs->magic = VNC_MAGIC;
3249     vs->sioc = sioc;
3250     object_ref(OBJECT(vs->sioc));
3251     vs->ioc = QIO_CHANNEL(sioc);
3252     object_ref(OBJECT(vs->ioc));
3253     vs->vd = vd;
3254 
3255     buffer_init(&vs->input,          "vnc-input/%p", sioc);
3256     buffer_init(&vs->output,         "vnc-output/%p", sioc);
3257     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3258 
3259     buffer_init(&vs->tight->tight,    "vnc-tight/%p", sioc);
3260     buffer_init(&vs->tight->zlib,     "vnc-tight-zlib/%p", sioc);
3261     buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3262 #ifdef CONFIG_VNC_JPEG
3263     buffer_init(&vs->tight->jpeg,     "vnc-tight-jpeg/%p", sioc);
3264 #endif
3265 #ifdef CONFIG_PNG
3266     buffer_init(&vs->tight->png,      "vnc-tight-png/%p", sioc);
3267 #endif
3268     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
3269     buffer_init(&vs->zrle->zrle,      "vnc-zrle/%p", sioc);
3270     buffer_init(&vs->zrle->fb,        "vnc-zrle-fb/%p", sioc);
3271     buffer_init(&vs->zrle->zlib,      "vnc-zrle-zlib/%p", sioc);
3272 
3273     if (skipauth) {
3274         vs->auth = VNC_AUTH_NONE;
3275         vs->subauth = VNC_AUTH_INVALID;
3276     } else {
3277         if (websocket) {
3278             vs->auth = vd->ws_auth;
3279             vs->subauth = VNC_AUTH_INVALID;
3280         } else {
3281             vs->auth = vd->auth;
3282             vs->subauth = vd->subauth;
3283         }
3284     }
3285     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3286               sioc, websocket, vs->auth, vs->subauth);
3287 
3288     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3289     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3290         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3291     }
3292 
3293     VNC_DEBUG("New client on socket %p\n", vs->sioc);
3294     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3295     qio_channel_set_blocking(vs->ioc, false, NULL);
3296     if (vs->ioc_tag) {
3297         g_source_remove(vs->ioc_tag);
3298     }
3299     if (websocket) {
3300         vs->websocket = 1;
3301         if (vd->tlscreds) {
3302             vs->ioc_tag = qio_channel_add_watch(
3303                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3304                 vncws_tls_handshake_io, vs, NULL);
3305         } else {
3306             vs->ioc_tag = qio_channel_add_watch(
3307                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3308                 vncws_handshake_io, vs, NULL);
3309         }
3310     } else {
3311         vs->ioc_tag = qio_channel_add_watch(
3312             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3313             vnc_client_io, vs, NULL);
3314     }
3315 
3316     vnc_client_cache_addr(vs);
3317     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3318     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3319 
3320     vs->last_x = -1;
3321     vs->last_y = -1;
3322 
3323     vs->as.freq = 44100;
3324     vs->as.nchannels = 2;
3325     vs->as.fmt = AUDIO_FORMAT_S16;
3326     vs->as.endianness = 0;
3327 
3328     qemu_mutex_init(&vs->output_mutex);
3329     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3330 
3331     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3332     if (first_client) {
3333         vnc_update_server_surface(vd);
3334     }
3335 
3336     graphic_hw_update(vd->dcl.con);
3337 
3338     if (!vs->websocket) {
3339         vnc_start_protocol(vs);
3340     }
3341 
3342     if (vd->num_connecting > vd->connections_limit) {
3343         QTAILQ_FOREACH(vs, &vd->clients, next) {
3344             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3345                 vnc_disconnect_start(vs);
3346                 return;
3347             }
3348         }
3349     }
3350 }
3351 
3352 void vnc_start_protocol(VncState *vs)
3353 {
3354     vnc_write(vs, "RFB 003.008\n", 12);
3355     vnc_flush(vs);
3356     vnc_read_when(vs, protocol_version, 12);
3357 
3358     vs->mouse_mode_notifier.notify = check_pointer_type_change;
3359     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3360 }
3361 
3362 static void vnc_listen_io(QIONetListener *listener,
3363                           QIOChannelSocket *cioc,
3364                           void *opaque)
3365 {
3366     VncDisplay *vd = opaque;
3367     bool isWebsock = listener == vd->wslistener;
3368 
3369     qio_channel_set_name(QIO_CHANNEL(cioc),
3370                          isWebsock ? "vnc-ws-server" : "vnc-server");
3371     qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3372     vnc_connect(vd, cioc, false, isWebsock);
3373 }
3374 
3375 static const DisplayChangeListenerOps dcl_ops = {
3376     .dpy_name             = "vnc",
3377     .dpy_refresh          = vnc_refresh,
3378     .dpy_gfx_update       = vnc_dpy_update,
3379     .dpy_gfx_switch       = vnc_dpy_switch,
3380     .dpy_gfx_check_format = qemu_pixman_check_format,
3381     .dpy_mouse_set        = vnc_mouse_set,
3382     .dpy_cursor_define    = vnc_dpy_cursor_define,
3383 };
3384 
3385 void vnc_display_init(const char *id, Error **errp)
3386 {
3387     VncDisplay *vd;
3388 
3389     if (vnc_display_find(id) != NULL) {
3390         return;
3391     }
3392     vd = g_malloc0(sizeof(*vd));
3393 
3394     vd->id = strdup(id);
3395     QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3396 
3397     QTAILQ_INIT(&vd->clients);
3398     vd->expires = TIME_MAX;
3399 
3400     if (keyboard_layout) {
3401         trace_vnc_key_map_init(keyboard_layout);
3402         vd->kbd_layout = init_keyboard_layout(name2keysym,
3403                                               keyboard_layout, errp);
3404     } else {
3405         vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3406     }
3407 
3408     if (!vd->kbd_layout) {
3409         return;
3410     }
3411 
3412     vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3413     vd->connections_limit = 32;
3414 
3415     qemu_mutex_init(&vd->mutex);
3416     vnc_start_worker_thread();
3417 
3418     vd->dcl.ops = &dcl_ops;
3419     register_displaychangelistener(&vd->dcl);
3420     vd->kbd = qkbd_state_init(vd->dcl.con);
3421 }
3422 
3423 
3424 static void vnc_display_close(VncDisplay *vd)
3425 {
3426     if (!vd) {
3427         return;
3428     }
3429     vd->is_unix = false;
3430 
3431     if (vd->listener) {
3432         qio_net_listener_disconnect(vd->listener);
3433         object_unref(OBJECT(vd->listener));
3434     }
3435     vd->listener = NULL;
3436 
3437     if (vd->wslistener) {
3438         qio_net_listener_disconnect(vd->wslistener);
3439         object_unref(OBJECT(vd->wslistener));
3440     }
3441     vd->wslistener = NULL;
3442 
3443     vd->auth = VNC_AUTH_INVALID;
3444     vd->subauth = VNC_AUTH_INVALID;
3445     if (vd->tlscreds) {
3446         object_unref(OBJECT(vd->tlscreds));
3447         vd->tlscreds = NULL;
3448     }
3449     if (vd->tlsauthz) {
3450         object_unparent(OBJECT(vd->tlsauthz));
3451         vd->tlsauthz = NULL;
3452     }
3453     g_free(vd->tlsauthzid);
3454     vd->tlsauthzid = NULL;
3455     if (vd->lock_key_sync) {
3456         qemu_remove_led_event_handler(vd->led);
3457         vd->led = NULL;
3458     }
3459 #ifdef CONFIG_VNC_SASL
3460     if (vd->sasl.authz) {
3461         object_unparent(OBJECT(vd->sasl.authz));
3462         vd->sasl.authz = NULL;
3463     }
3464     g_free(vd->sasl.authzid);
3465     vd->sasl.authzid = NULL;
3466 #endif
3467 }
3468 
3469 int vnc_display_password(const char *id, const char *password)
3470 {
3471     VncDisplay *vd = vnc_display_find(id);
3472 
3473     if (!vd) {
3474         return -EINVAL;
3475     }
3476     if (vd->auth == VNC_AUTH_NONE) {
3477         error_printf_unless_qmp("If you want use passwords please enable "
3478                                 "password auth using '-vnc ${dpy},password'.\n");
3479         return -EINVAL;
3480     }
3481 
3482     g_free(vd->password);
3483     vd->password = g_strdup(password);
3484 
3485     return 0;
3486 }
3487 
3488 int vnc_display_pw_expire(const char *id, time_t expires)
3489 {
3490     VncDisplay *vd = vnc_display_find(id);
3491 
3492     if (!vd) {
3493         return -EINVAL;
3494     }
3495 
3496     vd->expires = expires;
3497     return 0;
3498 }
3499 
3500 static void vnc_display_print_local_addr(VncDisplay *vd)
3501 {
3502     SocketAddress *addr;
3503 
3504     if (!vd->listener || !vd->listener->nsioc) {
3505         return;
3506     }
3507 
3508     addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
3509     if (!addr) {
3510         return;
3511     }
3512 
3513     if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3514         qapi_free_SocketAddress(addr);
3515         return;
3516     }
3517     error_printf_unless_qmp("VNC server running on %s:%s\n",
3518                             addr->u.inet.host,
3519                             addr->u.inet.port);
3520     qapi_free_SocketAddress(addr);
3521 }
3522 
3523 static QemuOptsList qemu_vnc_opts = {
3524     .name = "vnc",
3525     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3526     .implied_opt_name = "vnc",
3527     .desc = {
3528         {
3529             .name = "vnc",
3530             .type = QEMU_OPT_STRING,
3531         },{
3532             .name = "websocket",
3533             .type = QEMU_OPT_STRING,
3534         },{
3535             .name = "tls-creds",
3536             .type = QEMU_OPT_STRING,
3537         },{
3538             .name = "share",
3539             .type = QEMU_OPT_STRING,
3540         },{
3541             .name = "display",
3542             .type = QEMU_OPT_STRING,
3543         },{
3544             .name = "head",
3545             .type = QEMU_OPT_NUMBER,
3546         },{
3547             .name = "connections",
3548             .type = QEMU_OPT_NUMBER,
3549         },{
3550             .name = "to",
3551             .type = QEMU_OPT_NUMBER,
3552         },{
3553             .name = "ipv4",
3554             .type = QEMU_OPT_BOOL,
3555         },{
3556             .name = "ipv6",
3557             .type = QEMU_OPT_BOOL,
3558         },{
3559             .name = "password",
3560             .type = QEMU_OPT_BOOL,
3561         },{
3562             .name = "password-secret",
3563             .type = QEMU_OPT_STRING,
3564         },{
3565             .name = "reverse",
3566             .type = QEMU_OPT_BOOL,
3567         },{
3568             .name = "lock-key-sync",
3569             .type = QEMU_OPT_BOOL,
3570         },{
3571             .name = "key-delay-ms",
3572             .type = QEMU_OPT_NUMBER,
3573         },{
3574             .name = "sasl",
3575             .type = QEMU_OPT_BOOL,
3576         },{
3577             .name = "tls-authz",
3578             .type = QEMU_OPT_STRING,
3579         },{
3580             .name = "sasl-authz",
3581             .type = QEMU_OPT_STRING,
3582         },{
3583             .name = "lossy",
3584             .type = QEMU_OPT_BOOL,
3585         },{
3586             .name = "non-adaptive",
3587             .type = QEMU_OPT_BOOL,
3588         },{
3589             .name = "audiodev",
3590             .type = QEMU_OPT_STRING,
3591         },{
3592             .name = "power-control",
3593             .type = QEMU_OPT_BOOL,
3594         },
3595         { /* end of list */ }
3596     },
3597 };
3598 
3599 
3600 static int
3601 vnc_display_setup_auth(int *auth,
3602                        int *subauth,
3603                        QCryptoTLSCreds *tlscreds,
3604                        bool password,
3605                        bool sasl,
3606                        bool websocket,
3607                        Error **errp)
3608 {
3609     /*
3610      * We have a choice of 3 authentication options
3611      *
3612      *   1. none
3613      *   2. vnc
3614      *   3. sasl
3615      *
3616      * The channel can be run in 2 modes
3617      *
3618      *   1. clear
3619      *   2. tls
3620      *
3621      * And TLS can use 2 types of credentials
3622      *
3623      *   1. anon
3624      *   2. x509
3625      *
3626      * We thus have 9 possible logical combinations
3627      *
3628      *   1. clear + none
3629      *   2. clear + vnc
3630      *   3. clear + sasl
3631      *   4. tls + anon + none
3632      *   5. tls + anon + vnc
3633      *   6. tls + anon + sasl
3634      *   7. tls + x509 + none
3635      *   8. tls + x509 + vnc
3636      *   9. tls + x509 + sasl
3637      *
3638      * These need to be mapped into the VNC auth schemes
3639      * in an appropriate manner. In regular VNC, all the
3640      * TLS options get mapped into VNC_AUTH_VENCRYPT
3641      * sub-auth types.
3642      *
3643      * In websockets, the https:// protocol already provides
3644      * TLS support, so there is no need to make use of the
3645      * VeNCrypt extension. Furthermore, websockets browser
3646      * clients could not use VeNCrypt even if they wanted to,
3647      * as they cannot control when the TLS handshake takes
3648      * place. Thus there is no option but to rely on https://,
3649      * meaning combinations 4->6 and 7->9 will be mapped to
3650      * VNC auth schemes in the same way as combos 1->3.
3651      *
3652      * Regardless of fact that we have a different mapping to
3653      * VNC auth mechs for plain VNC vs websockets VNC, the end
3654      * result has the same security characteristics.
3655      */
3656     if (websocket || !tlscreds) {
3657         if (password) {
3658             VNC_DEBUG("Initializing VNC server with password auth\n");
3659             *auth = VNC_AUTH_VNC;
3660         } else if (sasl) {
3661             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3662             *auth = VNC_AUTH_SASL;
3663         } else {
3664             VNC_DEBUG("Initializing VNC server with no auth\n");
3665             *auth = VNC_AUTH_NONE;
3666         }
3667         *subauth = VNC_AUTH_INVALID;
3668     } else {
3669         bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3670                                            TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3671         bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3672                                            TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3673 
3674         if (!is_x509 && !is_anon) {
3675             error_setg(errp,
3676                        "Unsupported TLS cred type %s",
3677                        object_get_typename(OBJECT(tlscreds)));
3678             return -1;
3679         }
3680         *auth = VNC_AUTH_VENCRYPT;
3681         if (password) {
3682             if (is_x509) {
3683                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3684                 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3685             } else {
3686                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3687                 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3688             }
3689 
3690         } else if (sasl) {
3691             if (is_x509) {
3692                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3693                 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3694             } else {
3695                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3696                 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3697             }
3698         } else {
3699             if (is_x509) {
3700                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3701                 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3702             } else {
3703                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3704                 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3705             }
3706         }
3707     }
3708     return 0;
3709 }
3710 
3711 
3712 static int vnc_display_get_address(const char *addrstr,
3713                                    bool websocket,
3714                                    bool reverse,
3715                                    int displaynum,
3716                                    int to,
3717                                    bool has_ipv4,
3718                                    bool has_ipv6,
3719                                    bool ipv4,
3720                                    bool ipv6,
3721                                    SocketAddress **retaddr,
3722                                    Error **errp)
3723 {
3724     int ret = -1;
3725     SocketAddress *addr = NULL;
3726 
3727     addr = g_new0(SocketAddress, 1);
3728 
3729     if (strncmp(addrstr, "unix:", 5) == 0) {
3730         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3731         addr->u.q_unix.path = g_strdup(addrstr + 5);
3732 
3733         if (websocket) {
3734             error_setg(errp, "UNIX sockets not supported with websock");
3735             goto cleanup;
3736         }
3737 
3738         if (to) {
3739             error_setg(errp, "Port range not support with UNIX socket");
3740             goto cleanup;
3741         }
3742         ret = 0;
3743     } else {
3744         const char *port;
3745         size_t hostlen;
3746         uint64_t baseport = 0;
3747         InetSocketAddress *inet;
3748 
3749         port = strrchr(addrstr, ':');
3750         if (!port) {
3751             if (websocket) {
3752                 hostlen = 0;
3753                 port = addrstr;
3754             } else {
3755                 error_setg(errp, "no vnc port specified");
3756                 goto cleanup;
3757             }
3758         } else {
3759             hostlen = port - addrstr;
3760             port++;
3761             if (*port == '\0') {
3762                 error_setg(errp, "vnc port cannot be empty");
3763                 goto cleanup;
3764             }
3765         }
3766 
3767         addr->type = SOCKET_ADDRESS_TYPE_INET;
3768         inet = &addr->u.inet;
3769         if (hostlen && addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3770             inet->host = g_strndup(addrstr + 1, hostlen - 2);
3771         } else {
3772             inet->host = g_strndup(addrstr, hostlen);
3773         }
3774         /* plain VNC port is just an offset, for websocket
3775          * port is absolute */
3776         if (websocket) {
3777             if (g_str_equal(addrstr, "") ||
3778                 g_str_equal(addrstr, "on")) {
3779                 if (displaynum == -1) {
3780                     error_setg(errp, "explicit websocket port is required");
3781                     goto cleanup;
3782                 }
3783                 inet->port = g_strdup_printf(
3784                     "%d", displaynum + 5700);
3785                 if (to) {
3786                     inet->has_to = true;
3787                     inet->to = to + 5700;
3788                 }
3789             } else {
3790                 inet->port = g_strdup(port);
3791             }
3792         } else {
3793             int offset = reverse ? 0 : 5900;
3794             if (parse_uint_full(port, 10, &baseport) < 0) {
3795                 error_setg(errp, "can't convert to a number: %s", port);
3796                 goto cleanup;
3797             }
3798             if (baseport > 65535 ||
3799                 baseport + offset > 65535) {
3800                 error_setg(errp, "port %s out of range", port);
3801                 goto cleanup;
3802             }
3803             inet->port = g_strdup_printf(
3804                 "%d", (int)baseport + offset);
3805 
3806             if (to) {
3807                 inet->has_to = true;
3808                 inet->to = to + offset;
3809             }
3810         }
3811 
3812         inet->ipv4 = ipv4;
3813         inet->has_ipv4 = has_ipv4;
3814         inet->ipv6 = ipv6;
3815         inet->has_ipv6 = has_ipv6;
3816 
3817         ret = baseport;
3818     }
3819 
3820     *retaddr = addr;
3821 
3822  cleanup:
3823     if (ret < 0) {
3824         qapi_free_SocketAddress(addr);
3825     }
3826     return ret;
3827 }
3828 
3829 static int vnc_display_get_addresses(QemuOpts *opts,
3830                                      bool reverse,
3831                                      SocketAddressList **saddr_list_ret,
3832                                      SocketAddressList **wsaddr_list_ret,
3833                                      Error **errp)
3834 {
3835     SocketAddress *saddr = NULL;
3836     SocketAddress *wsaddr = NULL;
3837     g_autoptr(SocketAddressList) saddr_list = NULL;
3838     SocketAddressList **saddr_tail = &saddr_list;
3839     SocketAddress *single_saddr = NULL;
3840     g_autoptr(SocketAddressList) wsaddr_list = NULL;
3841     SocketAddressList **wsaddr_tail = &wsaddr_list;
3842     QemuOptsIter addriter;
3843     const char *addr;
3844     int to = qemu_opt_get_number(opts, "to", 0);
3845     bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3846     bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3847     bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3848     bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3849     int displaynum = -1;
3850 
3851     addr = qemu_opt_get(opts, "vnc");
3852     if (addr == NULL || g_str_equal(addr, "none")) {
3853         return 0;
3854     }
3855     if (qemu_opt_get(opts, "websocket") &&
3856         !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3857         error_setg(errp,
3858                    "SHA1 hash support is required for websockets");
3859         return -1;
3860     }
3861 
3862     qemu_opt_iter_init(&addriter, opts, "vnc");
3863     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3864         int rv;
3865         rv = vnc_display_get_address(addr, false, reverse, 0, to,
3866                                      has_ipv4, has_ipv6,
3867                                      ipv4, ipv6,
3868                                      &saddr, errp);
3869         if (rv < 0) {
3870             return -1;
3871         }
3872         /* Historical compat - first listen address can be used
3873          * to set the default websocket port
3874          */
3875         if (displaynum == -1) {
3876             displaynum = rv;
3877         }
3878         QAPI_LIST_APPEND(saddr_tail, saddr);
3879     }
3880 
3881     if (saddr_list && !saddr_list->next) {
3882         single_saddr = saddr_list->value;
3883     } else {
3884         /*
3885          * If we had multiple primary displays, we don't do defaults
3886          * for websocket, and require explicit config instead.
3887          */
3888         displaynum = -1;
3889     }
3890 
3891     qemu_opt_iter_init(&addriter, opts, "websocket");
3892     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3893         if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3894                                     has_ipv4, has_ipv6,
3895                                     ipv4, ipv6,
3896                                     &wsaddr, errp) < 0) {
3897             return -1;
3898         }
3899 
3900         /* Historical compat - if only a single listen address was
3901          * provided, then this is used to set the default listen
3902          * address for websocket too
3903          */
3904         if (single_saddr &&
3905             single_saddr->type == SOCKET_ADDRESS_TYPE_INET &&
3906             wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3907             g_str_equal(wsaddr->u.inet.host, "") &&
3908             !g_str_equal(single_saddr->u.inet.host, "")) {
3909             g_free(wsaddr->u.inet.host);
3910             wsaddr->u.inet.host = g_strdup(single_saddr->u.inet.host);
3911         }
3912 
3913         QAPI_LIST_APPEND(wsaddr_tail, wsaddr);
3914     }
3915 
3916     *saddr_list_ret = g_steal_pointer(&saddr_list);
3917     *wsaddr_list_ret = g_steal_pointer(&wsaddr_list);
3918     return 0;
3919 }
3920 
3921 static int vnc_display_connect(VncDisplay *vd,
3922                                SocketAddressList *saddr_list,
3923                                SocketAddressList *wsaddr_list,
3924                                Error **errp)
3925 {
3926     /* connect to viewer */
3927     QIOChannelSocket *sioc = NULL;
3928     if (wsaddr_list) {
3929         error_setg(errp, "Cannot use websockets in reverse mode");
3930         return -1;
3931     }
3932     if (!saddr_list || saddr_list->next) {
3933         error_setg(errp, "Expected a single address in reverse mode");
3934         return -1;
3935     }
3936     /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3937     vd->is_unix = saddr_list->value->type == SOCKET_ADDRESS_TYPE_UNIX;
3938     sioc = qio_channel_socket_new();
3939     qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3940     if (qio_channel_socket_connect_sync(sioc, saddr_list->value, errp) < 0) {
3941         object_unref(OBJECT(sioc));
3942         return -1;
3943     }
3944     vnc_connect(vd, sioc, false, false);
3945     object_unref(OBJECT(sioc));
3946     return 0;
3947 }
3948 
3949 
3950 static int vnc_display_listen(VncDisplay *vd,
3951                               SocketAddressList *saddr_list,
3952                               SocketAddressList *wsaddr_list,
3953                               Error **errp)
3954 {
3955     SocketAddressList *el;
3956 
3957     if (saddr_list) {
3958         vd->listener = qio_net_listener_new();
3959         qio_net_listener_set_name(vd->listener, "vnc-listen");
3960         for (el = saddr_list; el; el = el->next) {
3961             if (qio_net_listener_open_sync(vd->listener,
3962                                            el->value, 1,
3963                                            errp) < 0)  {
3964                 return -1;
3965             }
3966         }
3967 
3968         qio_net_listener_set_client_func(vd->listener,
3969                                          vnc_listen_io, vd, NULL);
3970     }
3971 
3972     if (wsaddr_list) {
3973         vd->wslistener = qio_net_listener_new();
3974         qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3975         for (el = wsaddr_list; el; el = el->next) {
3976             if (qio_net_listener_open_sync(vd->wslistener,
3977                                            el->value, 1,
3978                                            errp) < 0)  {
3979                 return -1;
3980             }
3981         }
3982 
3983         qio_net_listener_set_client_func(vd->wslistener,
3984                                          vnc_listen_io, vd, NULL);
3985     }
3986 
3987     return 0;
3988 }
3989 
3990 bool vnc_display_update(DisplayUpdateOptionsVNC *arg, Error **errp)
3991 {
3992     VncDisplay *vd = vnc_display_find(NULL);
3993 
3994     if (!vd) {
3995         error_setg(errp, "Can not find vnc display");
3996         return false;
3997     }
3998 
3999     if (arg->has_addresses) {
4000         if (vd->listener) {
4001             qio_net_listener_disconnect(vd->listener);
4002             object_unref(OBJECT(vd->listener));
4003             vd->listener = NULL;
4004         }
4005 
4006         if (vnc_display_listen(vd, arg->addresses, NULL, errp) < 0) {
4007             return false;
4008         }
4009     }
4010 
4011     return true;
4012 }
4013 
4014 void vnc_display_open(const char *id, Error **errp)
4015 {
4016     VncDisplay *vd = vnc_display_find(id);
4017     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
4018     g_autoptr(SocketAddressList) saddr_list = NULL;
4019     g_autoptr(SocketAddressList) wsaddr_list = NULL;
4020     const char *share, *device_id;
4021     QemuConsole *con;
4022     bool password = false;
4023     bool reverse = false;
4024     const char *credid;
4025     bool sasl = false;
4026     const char *tlsauthz;
4027     const char *saslauthz;
4028     int lock_key_sync = 1;
4029     int key_delay_ms;
4030     const char *audiodev;
4031     const char *passwordSecret;
4032 
4033     if (!vd) {
4034         error_setg(errp, "VNC display not active");
4035         return;
4036     }
4037     vnc_display_close(vd);
4038 
4039     if (!opts) {
4040         return;
4041     }
4042 
4043     reverse = qemu_opt_get_bool(opts, "reverse", false);
4044     if (vnc_display_get_addresses(opts, reverse, &saddr_list, &wsaddr_list,
4045                                   errp) < 0) {
4046         goto fail;
4047     }
4048 
4049 
4050     passwordSecret = qemu_opt_get(opts, "password-secret");
4051     if (passwordSecret) {
4052         if (qemu_opt_get(opts, "password")) {
4053             error_setg(errp,
4054                        "'password' flag is redundant with 'password-secret'");
4055             goto fail;
4056         }
4057         vd->password = qcrypto_secret_lookup_as_utf8(passwordSecret,
4058                                                      errp);
4059         if (!vd->password) {
4060             goto fail;
4061         }
4062         password = true;
4063     } else {
4064         password = qemu_opt_get_bool(opts, "password", false);
4065     }
4066     if (password) {
4067         if (!qcrypto_cipher_supports(
4068                 QCRYPTO_CIPHER_ALG_DES, QCRYPTO_CIPHER_MODE_ECB)) {
4069             error_setg(errp,
4070                        "Cipher backend does not support DES algorithm");
4071             goto fail;
4072         }
4073     }
4074 
4075     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
4076     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
4077     sasl = qemu_opt_get_bool(opts, "sasl", false);
4078 #ifndef CONFIG_VNC_SASL
4079     if (sasl) {
4080         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
4081         goto fail;
4082     }
4083 #endif /* CONFIG_VNC_SASL */
4084     credid = qemu_opt_get(opts, "tls-creds");
4085     if (credid) {
4086         Object *creds;
4087         creds = object_resolve_path_component(
4088             object_get_objects_root(), credid);
4089         if (!creds) {
4090             error_setg(errp, "No TLS credentials with id '%s'",
4091                        credid);
4092             goto fail;
4093         }
4094         vd->tlscreds = (QCryptoTLSCreds *)
4095             object_dynamic_cast(creds,
4096                                 TYPE_QCRYPTO_TLS_CREDS);
4097         if (!vd->tlscreds) {
4098             error_setg(errp, "Object with id '%s' is not TLS credentials",
4099                        credid);
4100             goto fail;
4101         }
4102         object_ref(OBJECT(vd->tlscreds));
4103 
4104         if (!qcrypto_tls_creds_check_endpoint(vd->tlscreds,
4105                                               QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
4106                                               errp)) {
4107             goto fail;
4108         }
4109     }
4110     tlsauthz = qemu_opt_get(opts, "tls-authz");
4111     if (tlsauthz && !vd->tlscreds) {
4112         error_setg(errp, "'tls-authz' provided but TLS is not enabled");
4113         goto fail;
4114     }
4115 
4116     saslauthz = qemu_opt_get(opts, "sasl-authz");
4117     if (saslauthz && !sasl) {
4118         error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
4119         goto fail;
4120     }
4121 
4122     share = qemu_opt_get(opts, "share");
4123     if (share) {
4124         if (strcmp(share, "ignore") == 0) {
4125             vd->share_policy = VNC_SHARE_POLICY_IGNORE;
4126         } else if (strcmp(share, "allow-exclusive") == 0) {
4127             vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4128         } else if (strcmp(share, "force-shared") == 0) {
4129             vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
4130         } else {
4131             error_setg(errp, "unknown vnc share= option");
4132             goto fail;
4133         }
4134     } else {
4135         vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4136     }
4137     vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
4138 
4139 #ifdef CONFIG_VNC_JPEG
4140     vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
4141 #endif
4142     vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4143     /* adaptive updates are only used with tight encoding and
4144      * if lossy updates are enabled so we can disable all the
4145      * calculations otherwise */
4146     if (!vd->lossy) {
4147         vd->non_adaptive = true;
4148     }
4149 
4150     vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
4151 
4152     if (tlsauthz) {
4153         vd->tlsauthzid = g_strdup(tlsauthz);
4154     }
4155 #ifdef CONFIG_VNC_SASL
4156     if (sasl) {
4157         if (saslauthz) {
4158             vd->sasl.authzid = g_strdup(saslauthz);
4159         }
4160     }
4161 #endif
4162 
4163     if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4164                                vd->tlscreds, password,
4165                                sasl, false, errp) < 0) {
4166         goto fail;
4167     }
4168     trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4169 
4170     if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4171                                vd->tlscreds, password,
4172                                sasl, true, errp) < 0) {
4173         goto fail;
4174     }
4175     trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
4176 
4177 #ifdef CONFIG_VNC_SASL
4178     if (sasl && !vnc_sasl_server_init(errp)) {
4179         goto fail;
4180     }
4181 #endif
4182     vd->lock_key_sync = lock_key_sync;
4183     if (lock_key_sync) {
4184         vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4185     }
4186     vd->ledstate = 0;
4187 
4188     audiodev = qemu_opt_get(opts, "audiodev");
4189     if (audiodev) {
4190         vd->audio_state = audio_state_by_name(audiodev, errp);
4191         if (!vd->audio_state) {
4192             goto fail;
4193         }
4194     } else {
4195         vd->audio_state = audio_get_default_audio_state(NULL);
4196     }
4197 
4198     device_id = qemu_opt_get(opts, "display");
4199     if (device_id) {
4200         int head = qemu_opt_get_number(opts, "head", 0);
4201         Error *err = NULL;
4202 
4203         con = qemu_console_lookup_by_device_name(device_id, head, &err);
4204         if (err) {
4205             error_propagate(errp, err);
4206             goto fail;
4207         }
4208     } else {
4209         con = NULL;
4210     }
4211 
4212     if (con != vd->dcl.con) {
4213         qkbd_state_free(vd->kbd);
4214         unregister_displaychangelistener(&vd->dcl);
4215         vd->dcl.con = con;
4216         register_displaychangelistener(&vd->dcl);
4217         vd->kbd = qkbd_state_init(vd->dcl.con);
4218     }
4219     qkbd_state_set_delay(vd->kbd, key_delay_ms);
4220 
4221     if (saddr_list == NULL) {
4222         return;
4223     }
4224 
4225     if (reverse) {
4226         if (vnc_display_connect(vd, saddr_list, wsaddr_list, errp) < 0) {
4227             goto fail;
4228         }
4229     } else {
4230         if (vnc_display_listen(vd, saddr_list, wsaddr_list, errp) < 0) {
4231             goto fail;
4232         }
4233     }
4234 
4235     if (qemu_opt_get(opts, "to")) {
4236         vnc_display_print_local_addr(vd);
4237     }
4238 
4239     /* Success */
4240     return;
4241 
4242 fail:
4243     vnc_display_close(vd);
4244 }
4245 
4246 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4247 {
4248     VncDisplay *vd = vnc_display_find(id);
4249     QIOChannelSocket *sioc;
4250 
4251     if (!vd) {
4252         return;
4253     }
4254 
4255     sioc = qio_channel_socket_new_fd(csock, NULL);
4256     if (sioc) {
4257         qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4258         vnc_connect(vd, sioc, skipauth, false);
4259         object_unref(OBJECT(sioc));
4260     }
4261 }
4262 
4263 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4264 {
4265     int i = 2;
4266     char *id;
4267 
4268     id = g_strdup("default");
4269     while (qemu_opts_find(olist, id)) {
4270         g_free(id);
4271         id = g_strdup_printf("vnc%d", i++);
4272     }
4273     qemu_opts_set_id(opts, id);
4274 }
4275 
4276 void vnc_parse(const char *str)
4277 {
4278     QemuOptsList *olist = qemu_find_opts("vnc");
4279     QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
4280     const char *id;
4281 
4282     if (!opts) {
4283         exit(1);
4284     }
4285 
4286     id = qemu_opts_id(opts);
4287     if (!id) {
4288         /* auto-assign id if not present */
4289         vnc_auto_assign_id(olist, opts);
4290     }
4291 }
4292 
4293 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4294 {
4295     Error *local_err = NULL;
4296     char *id = (char *)qemu_opts_id(opts);
4297 
4298     assert(id);
4299     vnc_display_init(id, &local_err);
4300     if (local_err) {
4301         error_propagate(errp, local_err);
4302         return -1;
4303     }
4304     vnc_display_open(id, &local_err);
4305     if (local_err != NULL) {
4306         error_propagate(errp, local_err);
4307         return -1;
4308     }
4309     return 0;
4310 }
4311 
4312 static void vnc_register_config(void)
4313 {
4314     qemu_add_opts(&qemu_vnc_opts);
4315 }
4316 opts_init(vnc_register_config);
4317