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