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