esp: remove CMD pdma_origin
[qemu/ar7.git] / ui / vnc.c
blob310abc937812df3a89c2ac06b3a934e32755b5ed
1 /*
2 * QEMU VNC display driver
4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5 * Copyright (C) 2006 Fabrice Bellard
6 * Copyright (C) 2009 Red Hat, Inc
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:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
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.
27 #include "qemu/osdep.h"
28 #include "vnc.h"
29 #include "vnc-jobs.h"
30 #include "trace.h"
31 #include "hw/qdev-core.h"
32 #include "sysemu/sysemu.h"
33 #include "sysemu/runstate.h"
34 #include "qemu/error-report.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qemu/option.h"
38 #include "qemu/sockets.h"
39 #include "qemu/timer.h"
40 #include "authz/list.h"
41 #include "qemu/config-file.h"
42 #include "qapi/qapi-emit-events.h"
43 #include "qapi/qapi-events-ui.h"
44 #include "qapi/error.h"
45 #include "qapi/qapi-commands-ui.h"
46 #include "ui/input.h"
47 #include "crypto/hash.h"
48 #include "crypto/tlscredsanon.h"
49 #include "crypto/tlscredsx509.h"
50 #include "crypto/random.h"
51 #include "qom/object_interfaces.h"
52 #include "qemu/cutils.h"
53 #include "qemu/help_option.h"
54 #include "io/dns-resolver.h"
56 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
57 #define VNC_REFRESH_INTERVAL_INC 50
58 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
59 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
60 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
62 #include "vnc_keysym.h"
63 #include "crypto/cipher.h"
65 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
66 QTAILQ_HEAD_INITIALIZER(vnc_displays);
68 static int vnc_cursor_define(VncState *vs);
69 static void vnc_update_throttle_offset(VncState *vs);
71 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
73 #ifdef _VNC_DEBUG
74 static const char *mn[] = {
75 [0] = "undefined",
76 [VNC_SHARE_MODE_CONNECTING] = "connecting",
77 [VNC_SHARE_MODE_SHARED] = "shared",
78 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
79 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
81 fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
82 vs->ioc, mn[vs->share_mode], mn[mode]);
83 #endif
85 switch (vs->share_mode) {
86 case VNC_SHARE_MODE_CONNECTING:
87 vs->vd->num_connecting--;
88 break;
89 case VNC_SHARE_MODE_SHARED:
90 vs->vd->num_shared--;
91 break;
92 case VNC_SHARE_MODE_EXCLUSIVE:
93 vs->vd->num_exclusive--;
94 break;
95 default:
96 break;
99 vs->share_mode = mode;
101 switch (vs->share_mode) {
102 case VNC_SHARE_MODE_CONNECTING:
103 vs->vd->num_connecting++;
104 break;
105 case VNC_SHARE_MODE_SHARED:
106 vs->vd->num_shared++;
107 break;
108 case VNC_SHARE_MODE_EXCLUSIVE:
109 vs->vd->num_exclusive++;
110 break;
111 default:
112 break;
117 static void vnc_init_basic_info(SocketAddress *addr,
118 VncBasicInfo *info,
119 Error **errp)
121 switch (addr->type) {
122 case SOCKET_ADDRESS_TYPE_INET:
123 info->host = g_strdup(addr->u.inet.host);
124 info->service = g_strdup(addr->u.inet.port);
125 if (addr->u.inet.ipv6) {
126 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
127 } else {
128 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
130 break;
132 case SOCKET_ADDRESS_TYPE_UNIX:
133 info->host = g_strdup("");
134 info->service = g_strdup(addr->u.q_unix.path);
135 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
136 break;
138 case SOCKET_ADDRESS_TYPE_VSOCK:
139 case SOCKET_ADDRESS_TYPE_FD:
140 error_setg(errp, "Unsupported socket address type %s",
141 SocketAddressType_str(addr->type));
142 break;
143 default:
144 abort();
147 return;
150 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
151 VncBasicInfo *info,
152 Error **errp)
154 SocketAddress *addr = NULL;
156 if (!ioc) {
157 error_setg(errp, "No listener socket available");
158 return;
161 addr = qio_channel_socket_get_local_address(ioc, errp);
162 if (!addr) {
163 return;
166 vnc_init_basic_info(addr, info, errp);
167 qapi_free_SocketAddress(addr);
170 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
171 VncBasicInfo *info,
172 Error **errp)
174 SocketAddress *addr = NULL;
176 addr = qio_channel_socket_get_remote_address(ioc, errp);
177 if (!addr) {
178 return;
181 vnc_init_basic_info(addr, info, errp);
182 qapi_free_SocketAddress(addr);
185 static const char *vnc_auth_name(VncDisplay *vd) {
186 switch (vd->auth) {
187 case VNC_AUTH_INVALID:
188 return "invalid";
189 case VNC_AUTH_NONE:
190 return "none";
191 case VNC_AUTH_VNC:
192 return "vnc";
193 case VNC_AUTH_RA2:
194 return "ra2";
195 case VNC_AUTH_RA2NE:
196 return "ra2ne";
197 case VNC_AUTH_TIGHT:
198 return "tight";
199 case VNC_AUTH_ULTRA:
200 return "ultra";
201 case VNC_AUTH_TLS:
202 return "tls";
203 case VNC_AUTH_VENCRYPT:
204 switch (vd->subauth) {
205 case VNC_AUTH_VENCRYPT_PLAIN:
206 return "vencrypt+plain";
207 case VNC_AUTH_VENCRYPT_TLSNONE:
208 return "vencrypt+tls+none";
209 case VNC_AUTH_VENCRYPT_TLSVNC:
210 return "vencrypt+tls+vnc";
211 case VNC_AUTH_VENCRYPT_TLSPLAIN:
212 return "vencrypt+tls+plain";
213 case VNC_AUTH_VENCRYPT_X509NONE:
214 return "vencrypt+x509+none";
215 case VNC_AUTH_VENCRYPT_X509VNC:
216 return "vencrypt+x509+vnc";
217 case VNC_AUTH_VENCRYPT_X509PLAIN:
218 return "vencrypt+x509+plain";
219 case VNC_AUTH_VENCRYPT_TLSSASL:
220 return "vencrypt+tls+sasl";
221 case VNC_AUTH_VENCRYPT_X509SASL:
222 return "vencrypt+x509+sasl";
223 default:
224 return "vencrypt";
226 case VNC_AUTH_SASL:
227 return "sasl";
229 return "unknown";
232 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
234 VncServerInfo *info;
235 Error *err = NULL;
237 if (!vd->listener || !vd->listener->nsioc) {
238 return NULL;
241 info = g_malloc0(sizeof(*info));
242 vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
243 qapi_VncServerInfo_base(info), &err);
244 info->has_auth = true;
245 info->auth = g_strdup(vnc_auth_name(vd));
246 if (err) {
247 qapi_free_VncServerInfo(info);
248 info = NULL;
249 error_free(err);
251 return info;
254 static void vnc_client_cache_auth(VncState *client)
256 if (!client->info) {
257 return;
260 if (client->tls) {
261 client->info->x509_dname =
262 qcrypto_tls_session_get_peer_name(client->tls);
263 client->info->has_x509_dname =
264 client->info->x509_dname != NULL;
266 #ifdef CONFIG_VNC_SASL
267 if (client->sasl.conn &&
268 client->sasl.username) {
269 client->info->has_sasl_username = true;
270 client->info->sasl_username = g_strdup(client->sasl.username);
272 #endif
275 static void vnc_client_cache_addr(VncState *client)
277 Error *err = NULL;
279 client->info = g_malloc0(sizeof(*client->info));
280 vnc_init_basic_info_from_remote_addr(client->sioc,
281 qapi_VncClientInfo_base(client->info),
282 &err);
283 client->info->websocket = client->websocket;
284 if (err) {
285 qapi_free_VncClientInfo(client->info);
286 client->info = NULL;
287 error_free(err);
291 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
293 VncServerInfo *si;
295 if (!vs->info) {
296 return;
299 si = vnc_server_info_get(vs->vd);
300 if (!si) {
301 return;
304 switch (event) {
305 case QAPI_EVENT_VNC_CONNECTED:
306 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
307 break;
308 case QAPI_EVENT_VNC_INITIALIZED:
309 qapi_event_send_vnc_initialized(si, vs->info);
310 break;
311 case QAPI_EVENT_VNC_DISCONNECTED:
312 qapi_event_send_vnc_disconnected(si, vs->info);
313 break;
314 default:
315 break;
318 qapi_free_VncServerInfo(si);
321 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
323 VncClientInfo *info;
324 Error *err = NULL;
326 info = g_malloc0(sizeof(*info));
328 vnc_init_basic_info_from_remote_addr(client->sioc,
329 qapi_VncClientInfo_base(info),
330 &err);
331 if (err) {
332 error_free(err);
333 qapi_free_VncClientInfo(info);
334 return NULL;
337 info->websocket = client->websocket;
339 if (client->tls) {
340 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
341 info->has_x509_dname = info->x509_dname != NULL;
343 #ifdef CONFIG_VNC_SASL
344 if (client->sasl.conn && client->sasl.username) {
345 info->has_sasl_username = true;
346 info->sasl_username = g_strdup(client->sasl.username);
348 #endif
350 return info;
353 static VncDisplay *vnc_display_find(const char *id)
355 VncDisplay *vd;
357 if (id == NULL) {
358 return QTAILQ_FIRST(&vnc_displays);
360 QTAILQ_FOREACH(vd, &vnc_displays, next) {
361 if (strcmp(id, vd->id) == 0) {
362 return vd;
365 return NULL;
368 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
370 VncClientInfoList *prev = NULL;
371 VncState *client;
373 QTAILQ_FOREACH(client, &vd->clients, next) {
374 QAPI_LIST_PREPEND(prev, qmp_query_vnc_client(client));
376 return prev;
379 VncInfo *qmp_query_vnc(Error **errp)
381 VncInfo *info = g_malloc0(sizeof(*info));
382 VncDisplay *vd = vnc_display_find(NULL);
383 SocketAddress *addr = NULL;
385 if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
386 info->enabled = false;
387 } else {
388 info->enabled = true;
390 /* for compatibility with the original command */
391 info->has_clients = true;
392 info->clients = qmp_query_client_list(vd);
394 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
395 errp);
396 if (!addr) {
397 goto out_error;
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;
409 break;
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;
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();
426 info->has_host = true;
427 info->has_service = true;
428 info->has_family = true;
430 info->has_auth = true;
431 info->auth = g_strdup(vnc_auth_name(vd));
434 qapi_free_SocketAddress(addr);
435 return info;
437 out_error:
438 qapi_free_SocketAddress(addr);
439 qapi_free_VncInfo(info);
440 return NULL;
444 static void qmp_query_auth(int auth, int subauth,
445 VncPrimaryAuth *qmp_auth,
446 VncVencryptSubAuth *qmp_vencrypt,
447 bool *qmp_has_vencrypt);
449 static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
450 bool websocket,
451 int auth,
452 int subauth,
453 VncServerInfo2List *prev)
455 VncServerInfo2 *info;
456 Error *err = NULL;
457 SocketAddress *addr;
459 addr = qio_channel_socket_get_local_address(ioc, NULL);
460 if (!addr) {
461 return prev;
464 info = g_new0(VncServerInfo2, 1);
465 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
466 qapi_free_SocketAddress(addr);
467 if (err) {
468 qapi_free_VncServerInfo2(info);
469 error_free(err);
470 return prev;
472 info->websocket = websocket;
474 qmp_query_auth(auth, subauth, &info->auth,
475 &info->vencrypt, &info->has_vencrypt);
477 QAPI_LIST_PREPEND(prev, info);
478 return prev;
481 static void qmp_query_auth(int auth, int subauth,
482 VncPrimaryAuth *qmp_auth,
483 VncVencryptSubAuth *qmp_vencrypt,
484 bool *qmp_has_vencrypt)
486 switch (auth) {
487 case VNC_AUTH_VNC:
488 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
489 break;
490 case VNC_AUTH_RA2:
491 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
492 break;
493 case VNC_AUTH_RA2NE:
494 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
495 break;
496 case VNC_AUTH_TIGHT:
497 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
498 break;
499 case VNC_AUTH_ULTRA:
500 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
501 break;
502 case VNC_AUTH_TLS:
503 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
504 break;
505 case VNC_AUTH_VENCRYPT:
506 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
507 *qmp_has_vencrypt = true;
508 switch (subauth) {
509 case VNC_AUTH_VENCRYPT_PLAIN:
510 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
511 break;
512 case VNC_AUTH_VENCRYPT_TLSNONE:
513 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
514 break;
515 case VNC_AUTH_VENCRYPT_TLSVNC:
516 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
517 break;
518 case VNC_AUTH_VENCRYPT_TLSPLAIN:
519 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
520 break;
521 case VNC_AUTH_VENCRYPT_X509NONE:
522 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
523 break;
524 case VNC_AUTH_VENCRYPT_X509VNC:
525 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
526 break;
527 case VNC_AUTH_VENCRYPT_X509PLAIN:
528 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
529 break;
530 case VNC_AUTH_VENCRYPT_TLSSASL:
531 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
532 break;
533 case VNC_AUTH_VENCRYPT_X509SASL:
534 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
535 break;
536 default:
537 *qmp_has_vencrypt = false;
538 break;
540 break;
541 case VNC_AUTH_SASL:
542 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
543 break;
544 case VNC_AUTH_NONE:
545 default:
546 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
547 break;
551 VncInfo2List *qmp_query_vnc_servers(Error **errp)
553 VncInfo2List *prev = NULL;
554 VncInfo2 *info;
555 VncDisplay *vd;
556 DeviceState *dev;
557 size_t i;
559 QTAILQ_FOREACH(vd, &vnc_displays, next) {
560 info = g_new0(VncInfo2, 1);
561 info->id = g_strdup(vd->id);
562 info->clients = qmp_query_client_list(vd);
563 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
564 &info->vencrypt, &info->has_vencrypt);
565 if (vd->dcl.con) {
566 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
567 "device", &error_abort));
568 info->has_display = true;
569 info->display = g_strdup(dev->id);
571 for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
572 info->server = qmp_query_server_entry(
573 vd->listener->sioc[i], false, vd->auth, vd->subauth,
574 info->server);
576 for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
577 info->server = qmp_query_server_entry(
578 vd->wslistener->sioc[i], true, vd->ws_auth,
579 vd->ws_subauth, info->server);
582 QAPI_LIST_PREPEND(prev, info);
584 return prev;
587 /* TODO
588 1) Get the queue working for IO.
589 2) there is some weirdness when using the -S option (the screen is grey
590 and not totally invalidated
591 3) resolutions > 1024
594 static int vnc_update_client(VncState *vs, int has_dirty);
595 static void vnc_disconnect_start(VncState *vs);
597 static void vnc_colordepth(VncState *vs);
598 static void framebuffer_update_request(VncState *vs, int incremental,
599 int x_position, int y_position,
600 int w, int h);
601 static void vnc_refresh(DisplayChangeListener *dcl);
602 static int vnc_refresh_server_surface(VncDisplay *vd);
604 static int vnc_width(VncDisplay *vd)
606 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
607 VNC_DIRTY_PIXELS_PER_BIT));
610 static int vnc_height(VncDisplay *vd)
612 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
615 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
616 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
617 VncDisplay *vd,
618 int x, int y, int w, int h)
620 int width = vnc_width(vd);
621 int height = vnc_height(vd);
623 /* this is needed this to ensure we updated all affected
624 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
625 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
626 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
628 x = MIN(x, width);
629 y = MIN(y, height);
630 w = MIN(x + w, width) - x;
631 h = MIN(y + h, height);
633 for (; y < h; y++) {
634 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
635 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
639 static void vnc_dpy_update(DisplayChangeListener *dcl,
640 int x, int y, int w, int h)
642 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
643 struct VncSurface *s = &vd->guest;
645 vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
648 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
649 int32_t encoding)
651 vnc_write_u16(vs, x);
652 vnc_write_u16(vs, y);
653 vnc_write_u16(vs, w);
654 vnc_write_u16(vs, h);
656 vnc_write_s32(vs, encoding);
659 static void vnc_desktop_resize_ext(VncState *vs, int reject_reason)
661 vnc_lock_output(vs);
662 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
663 vnc_write_u8(vs, 0);
664 vnc_write_u16(vs, 1); /* number of rects */
665 vnc_framebuffer_update(vs,
666 reject_reason ? 1 : 0,
667 reject_reason,
668 vs->client_width, vs->client_height,
669 VNC_ENCODING_DESKTOP_RESIZE_EXT);
670 vnc_write_u8(vs, 1); /* number of screens */
671 vnc_write_u8(vs, 0); /* padding */
672 vnc_write_u8(vs, 0); /* padding */
673 vnc_write_u8(vs, 0); /* padding */
674 vnc_write_u32(vs, 0); /* screen id */
675 vnc_write_u16(vs, 0); /* screen x-pos */
676 vnc_write_u16(vs, 0); /* screen y-pos */
677 vnc_write_u16(vs, vs->client_width);
678 vnc_write_u16(vs, vs->client_height);
679 vnc_write_u32(vs, 0); /* screen flags */
680 vnc_unlock_output(vs);
681 vnc_flush(vs);
684 static void vnc_desktop_resize(VncState *vs)
686 if (vs->ioc == NULL || (!vnc_has_feature(vs, VNC_FEATURE_RESIZE) &&
687 !vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT))) {
688 return;
690 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
691 vs->client_height == pixman_image_get_height(vs->vd->server)) {
692 return;
695 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
696 pixman_image_get_width(vs->vd->server) >= 0);
697 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
698 pixman_image_get_height(vs->vd->server) >= 0);
699 vs->client_width = pixman_image_get_width(vs->vd->server);
700 vs->client_height = pixman_image_get_height(vs->vd->server);
702 if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
703 vnc_desktop_resize_ext(vs, 0);
704 return;
707 vnc_lock_output(vs);
708 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
709 vnc_write_u8(vs, 0);
710 vnc_write_u16(vs, 1); /* number of rects */
711 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
712 VNC_ENCODING_DESKTOPRESIZE);
713 vnc_unlock_output(vs);
714 vnc_flush(vs);
717 static void vnc_abort_display_jobs(VncDisplay *vd)
719 VncState *vs;
721 QTAILQ_FOREACH(vs, &vd->clients, next) {
722 vnc_lock_output(vs);
723 vs->abort = true;
724 vnc_unlock_output(vs);
726 QTAILQ_FOREACH(vs, &vd->clients, next) {
727 vnc_jobs_join(vs);
729 QTAILQ_FOREACH(vs, &vd->clients, next) {
730 vnc_lock_output(vs);
731 if (vs->update == VNC_STATE_UPDATE_NONE &&
732 vs->job_update != VNC_STATE_UPDATE_NONE) {
733 /* job aborted before completion */
734 vs->update = vs->job_update;
735 vs->job_update = VNC_STATE_UPDATE_NONE;
737 vs->abort = false;
738 vnc_unlock_output(vs);
742 int vnc_server_fb_stride(VncDisplay *vd)
744 return pixman_image_get_stride(vd->server);
747 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
749 uint8_t *ptr;
751 ptr = (uint8_t *)pixman_image_get_data(vd->server);
752 ptr += y * vnc_server_fb_stride(vd);
753 ptr += x * VNC_SERVER_FB_BYTES;
754 return ptr;
757 static void vnc_update_server_surface(VncDisplay *vd)
759 int width, height;
761 qemu_pixman_image_unref(vd->server);
762 vd->server = NULL;
764 if (QTAILQ_EMPTY(&vd->clients)) {
765 return;
768 width = vnc_width(vd);
769 height = vnc_height(vd);
770 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
771 width, height,
772 NULL, 0);
774 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
775 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
776 width, height);
779 static bool vnc_check_pageflip(DisplaySurface *s1,
780 DisplaySurface *s2)
782 return (s1 != NULL &&
783 s2 != NULL &&
784 surface_width(s1) == surface_width(s2) &&
785 surface_height(s1) == surface_height(s2) &&
786 surface_format(s1) == surface_format(s2));
790 static void vnc_dpy_switch(DisplayChangeListener *dcl,
791 DisplaySurface *surface)
793 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
794 bool pageflip = vnc_check_pageflip(vd->ds, surface);
795 VncState *vs;
797 vnc_abort_display_jobs(vd);
798 vd->ds = surface;
800 /* guest surface */
801 qemu_pixman_image_unref(vd->guest.fb);
802 vd->guest.fb = pixman_image_ref(surface->image);
803 vd->guest.format = surface->format;
805 if (pageflip) {
806 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
807 surface_width(surface),
808 surface_height(surface));
809 return;
812 /* server surface */
813 vnc_update_server_surface(vd);
815 QTAILQ_FOREACH(vs, &vd->clients, next) {
816 vnc_colordepth(vs);
817 vnc_desktop_resize(vs);
818 vnc_cursor_define(vs);
819 memset(vs->dirty, 0x00, sizeof(vs->dirty));
820 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
821 vnc_width(vd),
822 vnc_height(vd));
823 vnc_update_throttle_offset(vs);
827 /* fastest code */
828 static void vnc_write_pixels_copy(VncState *vs,
829 void *pixels, int size)
831 vnc_write(vs, pixels, size);
834 /* slowest but generic code. */
835 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
837 uint8_t r, g, b;
839 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
840 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
841 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
842 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
843 #else
844 # error need some bits here if you change VNC_SERVER_FB_FORMAT
845 #endif
846 v = (r << vs->client_pf.rshift) |
847 (g << vs->client_pf.gshift) |
848 (b << vs->client_pf.bshift);
849 switch (vs->client_pf.bytes_per_pixel) {
850 case 1:
851 buf[0] = v;
852 break;
853 case 2:
854 if (vs->client_be) {
855 buf[0] = v >> 8;
856 buf[1] = v;
857 } else {
858 buf[1] = v >> 8;
859 buf[0] = v;
861 break;
862 default:
863 case 4:
864 if (vs->client_be) {
865 buf[0] = v >> 24;
866 buf[1] = v >> 16;
867 buf[2] = v >> 8;
868 buf[3] = v;
869 } else {
870 buf[3] = v >> 24;
871 buf[2] = v >> 16;
872 buf[1] = v >> 8;
873 buf[0] = v;
875 break;
879 static void vnc_write_pixels_generic(VncState *vs,
880 void *pixels1, int size)
882 uint8_t buf[4];
884 if (VNC_SERVER_FB_BYTES == 4) {
885 uint32_t *pixels = pixels1;
886 int n, i;
887 n = size >> 2;
888 for (i = 0; i < n; i++) {
889 vnc_convert_pixel(vs, buf, pixels[i]);
890 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
895 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
897 int i;
898 uint8_t *row;
899 VncDisplay *vd = vs->vd;
901 row = vnc_server_fb_ptr(vd, x, y);
902 for (i = 0; i < h; i++) {
903 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
904 row += vnc_server_fb_stride(vd);
906 return 1;
909 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
911 int n = 0;
913 switch(vs->vnc_encoding) {
914 case VNC_ENCODING_ZLIB:
915 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
916 break;
917 case VNC_ENCODING_HEXTILE:
918 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
919 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
920 break;
921 case VNC_ENCODING_TIGHT:
922 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
923 break;
924 case VNC_ENCODING_TIGHT_PNG:
925 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
926 break;
927 case VNC_ENCODING_ZRLE:
928 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
929 break;
930 case VNC_ENCODING_ZYWRLE:
931 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
932 break;
933 default:
934 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
935 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
936 break;
938 return n;
941 static void vnc_mouse_set(DisplayChangeListener *dcl,
942 int x, int y, int visible)
944 /* can we ask the client(s) to move the pointer ??? */
947 static int vnc_cursor_define(VncState *vs)
949 QEMUCursor *c = vs->vd->cursor;
950 int isize;
952 if (!vs->vd->cursor) {
953 return -1;
956 if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
957 vnc_lock_output(vs);
958 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
959 vnc_write_u8(vs, 0); /* padding */
960 vnc_write_u16(vs, 1); /* # of rects */
961 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
962 VNC_ENCODING_ALPHA_CURSOR);
963 vnc_write_s32(vs, VNC_ENCODING_RAW);
964 vnc_write(vs, c->data, c->width * c->height * 4);
965 vnc_unlock_output(vs);
966 return 0;
968 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
969 vnc_lock_output(vs);
970 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
971 vnc_write_u8(vs, 0); /* padding */
972 vnc_write_u16(vs, 1); /* # of rects */
973 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
974 VNC_ENCODING_RICH_CURSOR);
975 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
976 vnc_write_pixels_generic(vs, c->data, isize);
977 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
978 vnc_unlock_output(vs);
979 return 0;
981 return -1;
984 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
985 QEMUCursor *c)
987 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
988 VncState *vs;
990 cursor_put(vd->cursor);
991 g_free(vd->cursor_mask);
993 vd->cursor = c;
994 cursor_get(vd->cursor);
995 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
996 vd->cursor_mask = g_malloc0(vd->cursor_msize);
997 cursor_get_mono_mask(c, 0, vd->cursor_mask);
999 QTAILQ_FOREACH(vs, &vd->clients, next) {
1000 vnc_cursor_define(vs);
1004 static int find_and_clear_dirty_height(VncState *vs,
1005 int y, int last_x, int x, int height)
1007 int h;
1009 for (h = 1; h < (height - y); h++) {
1010 if (!test_bit(last_x, vs->dirty[y + h])) {
1011 break;
1013 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1016 return h;
1020 * Figure out how much pending data we should allow in the output
1021 * buffer before we throttle incremental display updates, and/or
1022 * drop audio samples.
1024 * We allow for equiv of 1 full display's worth of FB updates,
1025 * and 1 second of audio samples. If audio backlog was larger
1026 * than that the client would already suffering awful audio
1027 * glitches, so dropping samples is no worse really).
1029 static void vnc_update_throttle_offset(VncState *vs)
1031 size_t offset =
1032 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1034 if (vs->audio_cap) {
1035 int bps;
1036 switch (vs->as.fmt) {
1037 default:
1038 case AUDIO_FORMAT_U8:
1039 case AUDIO_FORMAT_S8:
1040 bps = 1;
1041 break;
1042 case AUDIO_FORMAT_U16:
1043 case AUDIO_FORMAT_S16:
1044 bps = 2;
1045 break;
1046 case AUDIO_FORMAT_U32:
1047 case AUDIO_FORMAT_S32:
1048 bps = 4;
1049 break;
1051 offset += vs->as.freq * bps * vs->as.nchannels;
1054 /* Put a floor of 1MB on offset, so that if we have a large pending
1055 * buffer and the display is resized to a small size & back again
1056 * we don't suddenly apply a tiny send limit
1058 offset = MAX(offset, 1024 * 1024);
1060 if (vs->throttle_output_offset != offset) {
1061 trace_vnc_client_throttle_threshold(
1062 vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1063 vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1066 vs->throttle_output_offset = offset;
1069 static bool vnc_should_update(VncState *vs)
1071 switch (vs->update) {
1072 case VNC_STATE_UPDATE_NONE:
1073 break;
1074 case VNC_STATE_UPDATE_INCREMENTAL:
1075 /* Only allow incremental updates if the pending send queue
1076 * is less than the permitted threshold, and the job worker
1077 * is completely idle.
1079 if (vs->output.offset < vs->throttle_output_offset &&
1080 vs->job_update == VNC_STATE_UPDATE_NONE) {
1081 return true;
1083 trace_vnc_client_throttle_incremental(
1084 vs, vs->ioc, vs->job_update, vs->output.offset);
1085 break;
1086 case VNC_STATE_UPDATE_FORCE:
1087 /* Only allow forced updates if the pending send queue
1088 * does not contain a previous forced update, and the
1089 * job worker is completely idle.
1091 * Note this means we'll queue a forced update, even if
1092 * the output buffer size is otherwise over the throttle
1093 * output limit.
1095 if (vs->force_update_offset == 0 &&
1096 vs->job_update == VNC_STATE_UPDATE_NONE) {
1097 return true;
1099 trace_vnc_client_throttle_forced(
1100 vs, vs->ioc, vs->job_update, vs->force_update_offset);
1101 break;
1103 return false;
1106 static int vnc_update_client(VncState *vs, int has_dirty)
1108 VncDisplay *vd = vs->vd;
1109 VncJob *job;
1110 int y;
1111 int height, width;
1112 int n = 0;
1114 if (vs->disconnecting) {
1115 vnc_disconnect_finish(vs);
1116 return 0;
1119 vs->has_dirty += has_dirty;
1120 if (!vnc_should_update(vs)) {
1121 return 0;
1124 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1125 return 0;
1129 * Send screen updates to the vnc client using the server
1130 * surface and server dirty map. guest surface updates
1131 * happening in parallel don't disturb us, the next pass will
1132 * send them to the client.
1134 job = vnc_job_new(vs);
1136 height = pixman_image_get_height(vd->server);
1137 width = pixman_image_get_width(vd->server);
1139 y = 0;
1140 for (;;) {
1141 int x, h;
1142 unsigned long x2;
1143 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1144 height * VNC_DIRTY_BPL(vs),
1145 y * VNC_DIRTY_BPL(vs));
1146 if (offset == height * VNC_DIRTY_BPL(vs)) {
1147 /* no more dirty bits */
1148 break;
1150 y = offset / VNC_DIRTY_BPL(vs);
1151 x = offset % VNC_DIRTY_BPL(vs);
1152 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1153 VNC_DIRTY_BPL(vs), x);
1154 bitmap_clear(vs->dirty[y], x, x2 - x);
1155 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1156 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1157 if (x2 > x) {
1158 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1159 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1161 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1162 y += h;
1163 if (y == height) {
1164 break;
1169 vs->job_update = vs->update;
1170 vs->update = VNC_STATE_UPDATE_NONE;
1171 vnc_job_push(job);
1172 vs->has_dirty = 0;
1173 return n;
1176 /* audio */
1177 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1179 VncState *vs = opaque;
1181 assert(vs->magic == VNC_MAGIC);
1182 switch (cmd) {
1183 case AUD_CNOTIFY_DISABLE:
1184 vnc_lock_output(vs);
1185 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1186 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1187 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1188 vnc_unlock_output(vs);
1189 vnc_flush(vs);
1190 break;
1192 case AUD_CNOTIFY_ENABLE:
1193 vnc_lock_output(vs);
1194 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1195 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1196 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1197 vnc_unlock_output(vs);
1198 vnc_flush(vs);
1199 break;
1203 static void audio_capture_destroy(void *opaque)
1207 static void audio_capture(void *opaque, const void *buf, int size)
1209 VncState *vs = opaque;
1211 assert(vs->magic == VNC_MAGIC);
1212 vnc_lock_output(vs);
1213 if (vs->output.offset < vs->throttle_output_offset) {
1214 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1215 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1216 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1217 vnc_write_u32(vs, size);
1218 vnc_write(vs, buf, size);
1219 } else {
1220 trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1222 vnc_unlock_output(vs);
1223 vnc_flush(vs);
1226 static void audio_add(VncState *vs)
1228 struct audio_capture_ops ops;
1230 if (vs->audio_cap) {
1231 error_report("audio already running");
1232 return;
1235 ops.notify = audio_capture_notify;
1236 ops.destroy = audio_capture_destroy;
1237 ops.capture = audio_capture;
1239 vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
1240 if (!vs->audio_cap) {
1241 error_report("Failed to add audio capture");
1245 static void audio_del(VncState *vs)
1247 if (vs->audio_cap) {
1248 AUD_del_capture(vs->audio_cap, vs);
1249 vs->audio_cap = NULL;
1253 static void vnc_disconnect_start(VncState *vs)
1255 if (vs->disconnecting) {
1256 return;
1258 trace_vnc_client_disconnect_start(vs, vs->ioc);
1259 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1260 if (vs->ioc_tag) {
1261 g_source_remove(vs->ioc_tag);
1262 vs->ioc_tag = 0;
1264 qio_channel_close(vs->ioc, NULL);
1265 vs->disconnecting = TRUE;
1268 void vnc_disconnect_finish(VncState *vs)
1270 int i;
1272 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1274 vnc_jobs_join(vs); /* Wait encoding jobs */
1276 vnc_lock_output(vs);
1277 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1279 buffer_free(&vs->input);
1280 buffer_free(&vs->output);
1282 qapi_free_VncClientInfo(vs->info);
1284 vnc_zlib_clear(vs);
1285 vnc_tight_clear(vs);
1286 vnc_zrle_clear(vs);
1288 #ifdef CONFIG_VNC_SASL
1289 vnc_sasl_client_cleanup(vs);
1290 #endif /* CONFIG_VNC_SASL */
1291 audio_del(vs);
1292 qkbd_state_lift_all_keys(vs->vd->kbd);
1294 if (vs->mouse_mode_notifier.notify != NULL) {
1295 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1297 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1298 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1299 /* last client gone */
1300 vnc_update_server_surface(vs->vd);
1303 vnc_unlock_output(vs);
1305 qemu_mutex_destroy(&vs->output_mutex);
1306 if (vs->bh != NULL) {
1307 qemu_bh_delete(vs->bh);
1309 buffer_free(&vs->jobs_buffer);
1311 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1312 g_free(vs->lossy_rect[i]);
1314 g_free(vs->lossy_rect);
1316 object_unref(OBJECT(vs->ioc));
1317 vs->ioc = NULL;
1318 object_unref(OBJECT(vs->sioc));
1319 vs->sioc = NULL;
1320 vs->magic = 0;
1321 g_free(vs->zrle);
1322 g_free(vs->tight);
1323 g_free(vs);
1326 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
1328 if (ret <= 0) {
1329 if (ret == 0) {
1330 trace_vnc_client_eof(vs, vs->ioc);
1331 vnc_disconnect_start(vs);
1332 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1333 trace_vnc_client_io_error(vs, vs->ioc,
1334 err ? error_get_pretty(err) : "Unknown");
1335 vnc_disconnect_start(vs);
1338 error_free(err);
1339 return 0;
1341 return ret;
1345 void vnc_client_error(VncState *vs)
1347 VNC_DEBUG("Closing down client sock: protocol error\n");
1348 vnc_disconnect_start(vs);
1353 * Called to write a chunk of data to the client socket. The data may
1354 * be the raw data, or may have already been encoded by SASL.
1355 * The data will be written either straight onto the socket, or
1356 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1358 * NB, it is theoretically possible to have 2 layers of encryption,
1359 * both SASL, and this TLS layer. It is highly unlikely in practice
1360 * though, since SASL encryption will typically be a no-op if TLS
1361 * is active
1363 * Returns the number of bytes written, which may be less than
1364 * the requested 'datalen' if the socket would block. Returns
1365 * 0 on I/O error, and disconnects the client socket.
1367 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1369 Error *err = NULL;
1370 ssize_t ret;
1371 ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
1372 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1373 return vnc_client_io_error(vs, ret, err);
1378 * Called to write buffered data to the client socket, when not
1379 * using any SASL SSF encryption layers. Will write as much data
1380 * as possible without blocking. If all buffered data is written,
1381 * will switch the FD poll() handler back to read monitoring.
1383 * Returns the number of bytes written, which may be less than
1384 * the buffered output data if the socket would block. Returns
1385 * 0 on I/O error, and disconnects the client socket.
1387 static size_t vnc_client_write_plain(VncState *vs)
1389 size_t offset;
1390 size_t ret;
1392 #ifdef CONFIG_VNC_SASL
1393 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1394 vs->output.buffer, vs->output.capacity, vs->output.offset,
1395 vs->sasl.waitWriteSSF);
1397 if (vs->sasl.conn &&
1398 vs->sasl.runSSF &&
1399 vs->sasl.waitWriteSSF) {
1400 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1401 if (ret)
1402 vs->sasl.waitWriteSSF -= ret;
1403 } else
1404 #endif /* CONFIG_VNC_SASL */
1405 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1406 if (!ret)
1407 return 0;
1409 if (ret >= vs->force_update_offset) {
1410 if (vs->force_update_offset != 0) {
1411 trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1413 vs->force_update_offset = 0;
1414 } else {
1415 vs->force_update_offset -= ret;
1417 offset = vs->output.offset;
1418 buffer_advance(&vs->output, ret);
1419 if (offset >= vs->throttle_output_offset &&
1420 vs->output.offset < vs->throttle_output_offset) {
1421 trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1424 if (vs->output.offset == 0) {
1425 if (vs->ioc_tag) {
1426 g_source_remove(vs->ioc_tag);
1428 vs->ioc_tag = qio_channel_add_watch(
1429 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1430 vnc_client_io, vs, NULL);
1433 return ret;
1438 * First function called whenever there is data to be written to
1439 * the client socket. Will delegate actual work according to whether
1440 * SASL SSF layers are enabled (thus requiring encryption calls)
1442 static void vnc_client_write_locked(VncState *vs)
1444 #ifdef CONFIG_VNC_SASL
1445 if (vs->sasl.conn &&
1446 vs->sasl.runSSF &&
1447 !vs->sasl.waitWriteSSF) {
1448 vnc_client_write_sasl(vs);
1449 } else
1450 #endif /* CONFIG_VNC_SASL */
1452 vnc_client_write_plain(vs);
1456 static void vnc_client_write(VncState *vs)
1458 assert(vs->magic == VNC_MAGIC);
1459 vnc_lock_output(vs);
1460 if (vs->output.offset) {
1461 vnc_client_write_locked(vs);
1462 } else if (vs->ioc != NULL) {
1463 if (vs->ioc_tag) {
1464 g_source_remove(vs->ioc_tag);
1466 vs->ioc_tag = qio_channel_add_watch(
1467 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1468 vnc_client_io, vs, NULL);
1470 vnc_unlock_output(vs);
1473 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1475 vs->read_handler = func;
1476 vs->read_handler_expect = expecting;
1481 * Called to read a chunk of data from the client socket. The data may
1482 * be the raw data, or may need to be further decoded by SASL.
1483 * The data will be read either straight from to the socket, or
1484 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1486 * NB, it is theoretically possible to have 2 layers of encryption,
1487 * both SASL, and this TLS layer. It is highly unlikely in practice
1488 * though, since SASL encryption will typically be a no-op if TLS
1489 * is active
1491 * Returns the number of bytes read, which may be less than
1492 * the requested 'datalen' if the socket would block. Returns
1493 * 0 on I/O error or EOF, and disconnects the client socket.
1495 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1497 ssize_t ret;
1498 Error *err = NULL;
1499 ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
1500 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1501 return vnc_client_io_error(vs, ret, err);
1506 * Called to read data from the client socket to the input buffer,
1507 * when not using any SASL SSF encryption layers. Will read as much
1508 * data as possible without blocking.
1510 * Returns the number of bytes read, which may be less than
1511 * the requested 'datalen' if the socket would block. Returns
1512 * 0 on I/O error or EOF, and disconnects the client socket.
1514 static size_t vnc_client_read_plain(VncState *vs)
1516 size_t ret;
1517 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1518 vs->input.buffer, vs->input.capacity, vs->input.offset);
1519 buffer_reserve(&vs->input, 4096);
1520 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1521 if (!ret)
1522 return 0;
1523 vs->input.offset += ret;
1524 return ret;
1527 static void vnc_jobs_bh(void *opaque)
1529 VncState *vs = opaque;
1531 assert(vs->magic == VNC_MAGIC);
1532 vnc_jobs_consume_buffer(vs);
1536 * First function called whenever there is more data to be read from
1537 * the client socket. Will delegate actual work according to whether
1538 * SASL SSF layers are enabled (thus requiring decryption calls)
1539 * Returns 0 on success, -1 if client disconnected
1541 static int vnc_client_read(VncState *vs)
1543 size_t ret;
1545 #ifdef CONFIG_VNC_SASL
1546 if (vs->sasl.conn && vs->sasl.runSSF)
1547 ret = vnc_client_read_sasl(vs);
1548 else
1549 #endif /* CONFIG_VNC_SASL */
1550 ret = vnc_client_read_plain(vs);
1551 if (!ret) {
1552 if (vs->disconnecting) {
1553 vnc_disconnect_finish(vs);
1554 return -1;
1556 return 0;
1559 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1560 size_t len = vs->read_handler_expect;
1561 int ret;
1563 ret = vs->read_handler(vs, vs->input.buffer, len);
1564 if (vs->disconnecting) {
1565 vnc_disconnect_finish(vs);
1566 return -1;
1569 if (!ret) {
1570 buffer_advance(&vs->input, len);
1571 } else {
1572 vs->read_handler_expect = ret;
1575 return 0;
1578 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1579 GIOCondition condition, void *opaque)
1581 VncState *vs = opaque;
1583 assert(vs->magic == VNC_MAGIC);
1585 if (condition & (G_IO_HUP | G_IO_ERR)) {
1586 vnc_disconnect_start(vs);
1587 return TRUE;
1590 if (condition & G_IO_IN) {
1591 if (vnc_client_read(vs) < 0) {
1592 /* vs is free()ed here */
1593 return TRUE;
1596 if (condition & G_IO_OUT) {
1597 vnc_client_write(vs);
1600 if (vs->disconnecting) {
1601 if (vs->ioc_tag != 0) {
1602 g_source_remove(vs->ioc_tag);
1604 vs->ioc_tag = 0;
1606 return TRUE;
1611 * Scale factor to apply to vs->throttle_output_offset when checking for
1612 * hard limit. Worst case normal usage could be x2, if we have a complete
1613 * incremental update and complete forced update in the output buffer.
1614 * So x3 should be good enough, but we pick x5 to be conservative and thus
1615 * (hopefully) never trigger incorrectly.
1617 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1619 void vnc_write(VncState *vs, const void *data, size_t len)
1621 assert(vs->magic == VNC_MAGIC);
1622 if (vs->disconnecting) {
1623 return;
1625 /* Protection against malicious client/guest to prevent our output
1626 * buffer growing without bound if client stops reading data. This
1627 * should rarely trigger, because we have earlier throttling code
1628 * which stops issuing framebuffer updates and drops audio data
1629 * if the throttle_output_offset value is exceeded. So we only reach
1630 * this higher level if a huge number of pseudo-encodings get
1631 * triggered while data can't be sent on the socket.
1633 * NB throttle_output_offset can be zero during early protocol
1634 * handshake, or from the job thread's VncState clone
1636 if (vs->throttle_output_offset != 0 &&
1637 (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1638 vs->throttle_output_offset) {
1639 trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1640 vs->throttle_output_offset);
1641 vnc_disconnect_start(vs);
1642 return;
1644 buffer_reserve(&vs->output, len);
1646 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1647 if (vs->ioc_tag) {
1648 g_source_remove(vs->ioc_tag);
1650 vs->ioc_tag = qio_channel_add_watch(
1651 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
1652 vnc_client_io, vs, NULL);
1655 buffer_append(&vs->output, data, len);
1658 void vnc_write_s32(VncState *vs, int32_t value)
1660 vnc_write_u32(vs, *(uint32_t *)&value);
1663 void vnc_write_u32(VncState *vs, uint32_t value)
1665 uint8_t buf[4];
1667 buf[0] = (value >> 24) & 0xFF;
1668 buf[1] = (value >> 16) & 0xFF;
1669 buf[2] = (value >> 8) & 0xFF;
1670 buf[3] = value & 0xFF;
1672 vnc_write(vs, buf, 4);
1675 void vnc_write_u16(VncState *vs, uint16_t value)
1677 uint8_t buf[2];
1679 buf[0] = (value >> 8) & 0xFF;
1680 buf[1] = value & 0xFF;
1682 vnc_write(vs, buf, 2);
1685 void vnc_write_u8(VncState *vs, uint8_t value)
1687 vnc_write(vs, (char *)&value, 1);
1690 void vnc_flush(VncState *vs)
1692 vnc_lock_output(vs);
1693 if (vs->ioc != NULL && vs->output.offset) {
1694 vnc_client_write_locked(vs);
1696 if (vs->disconnecting) {
1697 if (vs->ioc_tag != 0) {
1698 g_source_remove(vs->ioc_tag);
1700 vs->ioc_tag = 0;
1702 vnc_unlock_output(vs);
1705 static uint8_t read_u8(uint8_t *data, size_t offset)
1707 return data[offset];
1710 static uint16_t read_u16(uint8_t *data, size_t offset)
1712 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1715 static int32_t read_s32(uint8_t *data, size_t offset)
1717 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1718 (data[offset + 2] << 8) | data[offset + 3]);
1721 uint32_t read_u32(uint8_t *data, size_t offset)
1723 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1724 (data[offset + 2] << 8) | data[offset + 3]);
1727 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1731 static void check_pointer_type_change(Notifier *notifier, void *data)
1733 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1734 int absolute = qemu_input_is_absolute();
1736 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1737 vnc_lock_output(vs);
1738 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1739 vnc_write_u8(vs, 0);
1740 vnc_write_u16(vs, 1);
1741 vnc_framebuffer_update(vs, absolute, 0,
1742 pixman_image_get_width(vs->vd->server),
1743 pixman_image_get_height(vs->vd->server),
1744 VNC_ENCODING_POINTER_TYPE_CHANGE);
1745 vnc_unlock_output(vs);
1746 vnc_flush(vs);
1748 vs->absolute = absolute;
1751 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1753 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1754 [INPUT_BUTTON_LEFT] = 0x01,
1755 [INPUT_BUTTON_MIDDLE] = 0x02,
1756 [INPUT_BUTTON_RIGHT] = 0x04,
1757 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1758 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1760 QemuConsole *con = vs->vd->dcl.con;
1761 int width = pixman_image_get_width(vs->vd->server);
1762 int height = pixman_image_get_height(vs->vd->server);
1764 if (vs->last_bmask != button_mask) {
1765 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1766 vs->last_bmask = button_mask;
1769 if (vs->absolute) {
1770 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1771 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1772 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1773 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1774 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1775 } else {
1776 if (vs->last_x != -1) {
1777 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1778 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1780 vs->last_x = x;
1781 vs->last_y = y;
1783 qemu_input_event_sync();
1786 static void press_key(VncState *vs, QKeyCode qcode)
1788 qkbd_state_key_event(vs->vd->kbd, qcode, true);
1789 qkbd_state_key_event(vs->vd->kbd, qcode, false);
1792 static void vnc_led_state_change(VncState *vs)
1794 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1795 return;
1798 vnc_lock_output(vs);
1799 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1800 vnc_write_u8(vs, 0);
1801 vnc_write_u16(vs, 1);
1802 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1803 vnc_write_u8(vs, vs->vd->ledstate);
1804 vnc_unlock_output(vs);
1805 vnc_flush(vs);
1808 static void kbd_leds(void *opaque, int ledstate)
1810 VncDisplay *vd = opaque;
1811 VncState *client;
1813 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1814 (ledstate & QEMU_NUM_LOCK_LED),
1815 (ledstate & QEMU_SCROLL_LOCK_LED));
1817 if (ledstate == vd->ledstate) {
1818 return;
1821 vd->ledstate = ledstate;
1823 QTAILQ_FOREACH(client, &vd->clients, next) {
1824 vnc_led_state_change(client);
1828 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1830 QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1832 /* QEMU console switch */
1833 switch (qcode) {
1834 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1835 if (vs->vd->dcl.con == NULL && down &&
1836 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1837 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1838 /* Reset the modifiers sent to the current console */
1839 qkbd_state_lift_all_keys(vs->vd->kbd);
1840 console_select(qcode - Q_KEY_CODE_1);
1841 return;
1843 default:
1844 break;
1847 /* Turn off the lock state sync logic if the client support the led
1848 state extension.
1850 if (down && vs->vd->lock_key_sync &&
1851 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1852 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1853 /* If the numlock state needs to change then simulate an additional
1854 keypress before sending this one. This will happen if the user
1855 toggles numlock away from the VNC window.
1857 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1858 if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1859 trace_vnc_key_sync_numlock(true);
1860 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1862 } else {
1863 if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1864 trace_vnc_key_sync_numlock(false);
1865 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1870 if (down && vs->vd->lock_key_sync &&
1871 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1872 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1873 /* If the capslock state needs to change then simulate an additional
1874 keypress before sending this one. This will happen if the user
1875 toggles capslock away from the VNC window.
1877 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1878 bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1879 bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1880 if (capslock) {
1881 if (uppercase == shift) {
1882 trace_vnc_key_sync_capslock(false);
1883 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1885 } else {
1886 if (uppercase != shift) {
1887 trace_vnc_key_sync_capslock(true);
1888 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1893 qkbd_state_key_event(vs->vd->kbd, qcode, down);
1894 if (!qemu_console_is_graphic(NULL)) {
1895 bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1896 bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1897 /* QEMU console emulation */
1898 if (down) {
1899 switch (keycode) {
1900 case 0x2a: /* Left Shift */
1901 case 0x36: /* Right Shift */
1902 case 0x1d: /* Left CTRL */
1903 case 0x9d: /* Right CTRL */
1904 case 0x38: /* Left ALT */
1905 case 0xb8: /* Right ALT */
1906 break;
1907 case 0xc8:
1908 kbd_put_keysym(QEMU_KEY_UP);
1909 break;
1910 case 0xd0:
1911 kbd_put_keysym(QEMU_KEY_DOWN);
1912 break;
1913 case 0xcb:
1914 kbd_put_keysym(QEMU_KEY_LEFT);
1915 break;
1916 case 0xcd:
1917 kbd_put_keysym(QEMU_KEY_RIGHT);
1918 break;
1919 case 0xd3:
1920 kbd_put_keysym(QEMU_KEY_DELETE);
1921 break;
1922 case 0xc7:
1923 kbd_put_keysym(QEMU_KEY_HOME);
1924 break;
1925 case 0xcf:
1926 kbd_put_keysym(QEMU_KEY_END);
1927 break;
1928 case 0xc9:
1929 kbd_put_keysym(QEMU_KEY_PAGEUP);
1930 break;
1931 case 0xd1:
1932 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1933 break;
1935 case 0x47:
1936 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1937 break;
1938 case 0x48:
1939 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1940 break;
1941 case 0x49:
1942 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1943 break;
1944 case 0x4b:
1945 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1946 break;
1947 case 0x4c:
1948 kbd_put_keysym('5');
1949 break;
1950 case 0x4d:
1951 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1952 break;
1953 case 0x4f:
1954 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1955 break;
1956 case 0x50:
1957 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1958 break;
1959 case 0x51:
1960 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1961 break;
1962 case 0x52:
1963 kbd_put_keysym('0');
1964 break;
1965 case 0x53:
1966 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1967 break;
1969 case 0xb5:
1970 kbd_put_keysym('/');
1971 break;
1972 case 0x37:
1973 kbd_put_keysym('*');
1974 break;
1975 case 0x4a:
1976 kbd_put_keysym('-');
1977 break;
1978 case 0x4e:
1979 kbd_put_keysym('+');
1980 break;
1981 case 0x9c:
1982 kbd_put_keysym('\n');
1983 break;
1985 default:
1986 if (control) {
1987 kbd_put_keysym(sym & 0x1f);
1988 } else {
1989 kbd_put_keysym(sym);
1991 break;
1997 static const char *code2name(int keycode)
1999 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
2002 static void key_event(VncState *vs, int down, uint32_t sym)
2004 int keycode;
2005 int lsym = sym;
2007 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
2008 lsym = lsym - 'A' + 'a';
2011 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
2012 vs->vd->kbd, down) & SCANCODE_KEYMASK;
2013 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
2014 do_key_event(vs, down, keycode, sym);
2017 static void ext_key_event(VncState *vs, int down,
2018 uint32_t sym, uint16_t keycode)
2020 /* if the user specifies a keyboard layout, always use it */
2021 if (keyboard_layout) {
2022 key_event(vs, down, sym);
2023 } else {
2024 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2025 do_key_event(vs, down, keycode, sym);
2029 static void framebuffer_update_request(VncState *vs, int incremental,
2030 int x, int y, int w, int h)
2032 if (incremental) {
2033 if (vs->update != VNC_STATE_UPDATE_FORCE) {
2034 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2036 } else {
2037 vs->update = VNC_STATE_UPDATE_FORCE;
2038 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2039 if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
2040 vnc_desktop_resize_ext(vs, 0);
2045 static void send_ext_key_event_ack(VncState *vs)
2047 vnc_lock_output(vs);
2048 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2049 vnc_write_u8(vs, 0);
2050 vnc_write_u16(vs, 1);
2051 vnc_framebuffer_update(vs, 0, 0,
2052 pixman_image_get_width(vs->vd->server),
2053 pixman_image_get_height(vs->vd->server),
2054 VNC_ENCODING_EXT_KEY_EVENT);
2055 vnc_unlock_output(vs);
2056 vnc_flush(vs);
2059 static void send_ext_audio_ack(VncState *vs)
2061 vnc_lock_output(vs);
2062 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2063 vnc_write_u8(vs, 0);
2064 vnc_write_u16(vs, 1);
2065 vnc_framebuffer_update(vs, 0, 0,
2066 pixman_image_get_width(vs->vd->server),
2067 pixman_image_get_height(vs->vd->server),
2068 VNC_ENCODING_AUDIO);
2069 vnc_unlock_output(vs);
2070 vnc_flush(vs);
2073 static void send_xvp_message(VncState *vs, int code)
2075 vnc_lock_output(vs);
2076 vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
2077 vnc_write_u8(vs, 0); /* pad */
2078 vnc_write_u8(vs, 1); /* version */
2079 vnc_write_u8(vs, code);
2080 vnc_unlock_output(vs);
2081 vnc_flush(vs);
2084 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2086 int i;
2087 unsigned int enc = 0;
2089 vs->features = 0;
2090 vs->vnc_encoding = 0;
2091 vs->tight->compression = 9;
2092 vs->tight->quality = -1; /* Lossless by default */
2093 vs->absolute = -1;
2096 * Start from the end because the encodings are sent in order of preference.
2097 * This way the preferred encoding (first encoding defined in the array)
2098 * will be set at the end of the loop.
2100 for (i = n_encodings - 1; i >= 0; i--) {
2101 enc = encodings[i];
2102 switch (enc) {
2103 case VNC_ENCODING_RAW:
2104 vs->vnc_encoding = enc;
2105 break;
2106 case VNC_ENCODING_HEXTILE:
2107 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2108 vs->vnc_encoding = enc;
2109 break;
2110 case VNC_ENCODING_TIGHT:
2111 vs->features |= VNC_FEATURE_TIGHT_MASK;
2112 vs->vnc_encoding = enc;
2113 break;
2114 #ifdef CONFIG_VNC_PNG
2115 case VNC_ENCODING_TIGHT_PNG:
2116 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2117 vs->vnc_encoding = enc;
2118 break;
2119 #endif
2120 case VNC_ENCODING_ZLIB:
2122 * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2123 * So prioritize ZRLE, even if the client hints that it prefers
2124 * ZLIB.
2126 if ((vs->features & VNC_FEATURE_ZRLE_MASK) == 0) {
2127 vs->features |= VNC_FEATURE_ZLIB_MASK;
2128 vs->vnc_encoding = enc;
2130 break;
2131 case VNC_ENCODING_ZRLE:
2132 vs->features |= VNC_FEATURE_ZRLE_MASK;
2133 vs->vnc_encoding = enc;
2134 break;
2135 case VNC_ENCODING_ZYWRLE:
2136 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2137 vs->vnc_encoding = enc;
2138 break;
2139 case VNC_ENCODING_DESKTOPRESIZE:
2140 vs->features |= VNC_FEATURE_RESIZE_MASK;
2141 break;
2142 case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2143 vs->features |= VNC_FEATURE_RESIZE_EXT_MASK;
2144 break;
2145 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2146 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2147 break;
2148 case VNC_ENCODING_RICH_CURSOR:
2149 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2150 break;
2151 case VNC_ENCODING_ALPHA_CURSOR:
2152 vs->features |= VNC_FEATURE_ALPHA_CURSOR_MASK;
2153 break;
2154 case VNC_ENCODING_EXT_KEY_EVENT:
2155 send_ext_key_event_ack(vs);
2156 break;
2157 case VNC_ENCODING_AUDIO:
2158 send_ext_audio_ack(vs);
2159 break;
2160 case VNC_ENCODING_WMVi:
2161 vs->features |= VNC_FEATURE_WMVI_MASK;
2162 break;
2163 case VNC_ENCODING_LED_STATE:
2164 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2165 break;
2166 case VNC_ENCODING_XVP:
2167 if (vs->vd->power_control) {
2168 vs->features |= VNC_FEATURE_XVP;
2169 send_xvp_message(vs, VNC_XVP_CODE_INIT);
2171 break;
2172 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2173 vs->tight->compression = (enc & 0x0F);
2174 break;
2175 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2176 if (vs->vd->lossy) {
2177 vs->tight->quality = (enc & 0x0F);
2179 break;
2180 default:
2181 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2182 break;
2185 vnc_desktop_resize(vs);
2186 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2187 vnc_led_state_change(vs);
2188 vnc_cursor_define(vs);
2191 static void set_pixel_conversion(VncState *vs)
2193 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2195 if (fmt == VNC_SERVER_FB_FORMAT) {
2196 vs->write_pixels = vnc_write_pixels_copy;
2197 vnc_hextile_set_pixel_conversion(vs, 0);
2198 } else {
2199 vs->write_pixels = vnc_write_pixels_generic;
2200 vnc_hextile_set_pixel_conversion(vs, 1);
2204 static void send_color_map(VncState *vs)
2206 int i;
2208 vnc_lock_output(vs);
2209 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2210 vnc_write_u8(vs, 0); /* padding */
2211 vnc_write_u16(vs, 0); /* first color */
2212 vnc_write_u16(vs, 256); /* # of colors */
2214 for (i = 0; i < 256; i++) {
2215 PixelFormat *pf = &vs->client_pf;
2217 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2218 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2219 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2221 vnc_unlock_output(vs);
2224 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2225 int big_endian_flag, int true_color_flag,
2226 int red_max, int green_max, int blue_max,
2227 int red_shift, int green_shift, int blue_shift)
2229 if (!true_color_flag) {
2230 /* Expose a reasonable default 256 color map */
2231 bits_per_pixel = 8;
2232 red_max = 7;
2233 green_max = 7;
2234 blue_max = 3;
2235 red_shift = 0;
2236 green_shift = 3;
2237 blue_shift = 6;
2240 switch (bits_per_pixel) {
2241 case 8:
2242 case 16:
2243 case 32:
2244 break;
2245 default:
2246 vnc_client_error(vs);
2247 return;
2250 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2251 vs->client_pf.rbits = ctpopl(red_max);
2252 vs->client_pf.rshift = red_shift;
2253 vs->client_pf.rmask = red_max << red_shift;
2254 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2255 vs->client_pf.gbits = ctpopl(green_max);
2256 vs->client_pf.gshift = green_shift;
2257 vs->client_pf.gmask = green_max << green_shift;
2258 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2259 vs->client_pf.bbits = ctpopl(blue_max);
2260 vs->client_pf.bshift = blue_shift;
2261 vs->client_pf.bmask = blue_max << blue_shift;
2262 vs->client_pf.bits_per_pixel = bits_per_pixel;
2263 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2264 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2265 vs->client_be = big_endian_flag;
2267 if (!true_color_flag) {
2268 send_color_map(vs);
2271 set_pixel_conversion(vs);
2273 graphic_hw_invalidate(vs->vd->dcl.con);
2274 graphic_hw_update(vs->vd->dcl.con);
2277 static void pixel_format_message (VncState *vs) {
2278 char pad[3] = { 0, 0, 0 };
2280 vs->client_pf = qemu_default_pixelformat(32);
2282 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2283 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2285 #ifdef HOST_WORDS_BIGENDIAN
2286 vnc_write_u8(vs, 1); /* big-endian-flag */
2287 #else
2288 vnc_write_u8(vs, 0); /* big-endian-flag */
2289 #endif
2290 vnc_write_u8(vs, 1); /* true-color-flag */
2291 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2292 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2293 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2294 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2295 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2296 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2297 vnc_write(vs, pad, 3); /* padding */
2299 vnc_hextile_set_pixel_conversion(vs, 0);
2300 vs->write_pixels = vnc_write_pixels_copy;
2303 static void vnc_colordepth(VncState *vs)
2305 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2306 /* Sending a WMVi message to notify the client*/
2307 vnc_lock_output(vs);
2308 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2309 vnc_write_u8(vs, 0);
2310 vnc_write_u16(vs, 1); /* number of rects */
2311 vnc_framebuffer_update(vs, 0, 0,
2312 pixman_image_get_width(vs->vd->server),
2313 pixman_image_get_height(vs->vd->server),
2314 VNC_ENCODING_WMVi);
2315 pixel_format_message(vs);
2316 vnc_unlock_output(vs);
2317 vnc_flush(vs);
2318 } else {
2319 set_pixel_conversion(vs);
2323 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2325 int i;
2326 uint16_t limit;
2327 uint32_t freq;
2328 VncDisplay *vd = vs->vd;
2330 if (data[0] > 3) {
2331 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2334 switch (data[0]) {
2335 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2336 if (len == 1)
2337 return 20;
2339 set_pixel_format(vs, read_u8(data, 4),
2340 read_u8(data, 6), read_u8(data, 7),
2341 read_u16(data, 8), read_u16(data, 10),
2342 read_u16(data, 12), read_u8(data, 14),
2343 read_u8(data, 15), read_u8(data, 16));
2344 break;
2345 case VNC_MSG_CLIENT_SET_ENCODINGS:
2346 if (len == 1)
2347 return 4;
2349 if (len == 4) {
2350 limit = read_u16(data, 2);
2351 if (limit > 0)
2352 return 4 + (limit * 4);
2353 } else
2354 limit = read_u16(data, 2);
2356 for (i = 0; i < limit; i++) {
2357 int32_t val = read_s32(data, 4 + (i * 4));
2358 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2361 set_encodings(vs, (int32_t *)(data + 4), limit);
2362 break;
2363 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2364 if (len == 1)
2365 return 10;
2367 framebuffer_update_request(vs,
2368 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2369 read_u16(data, 6), read_u16(data, 8));
2370 break;
2371 case VNC_MSG_CLIENT_KEY_EVENT:
2372 if (len == 1)
2373 return 8;
2375 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2376 break;
2377 case VNC_MSG_CLIENT_POINTER_EVENT:
2378 if (len == 1)
2379 return 6;
2381 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2382 break;
2383 case VNC_MSG_CLIENT_CUT_TEXT:
2384 if (len == 1) {
2385 return 8;
2387 if (len == 8) {
2388 uint32_t dlen = read_u32(data, 4);
2389 if (dlen > (1 << 20)) {
2390 error_report("vnc: client_cut_text msg payload has %u bytes"
2391 " which exceeds our limit of 1MB.", dlen);
2392 vnc_client_error(vs);
2393 break;
2395 if (dlen > 0) {
2396 return 8 + dlen;
2400 client_cut_text(vs, read_u32(data, 4), data + 8);
2401 break;
2402 case VNC_MSG_CLIENT_XVP:
2403 if (!(vs->features & VNC_FEATURE_XVP)) {
2404 error_report("vnc: xvp client message while disabled");
2405 vnc_client_error(vs);
2406 break;
2408 if (len == 1) {
2409 return 4;
2411 if (len == 4) {
2412 uint8_t version = read_u8(data, 2);
2413 uint8_t action = read_u8(data, 3);
2415 if (version != 1) {
2416 error_report("vnc: xvp client message version %d != 1",
2417 version);
2418 vnc_client_error(vs);
2419 break;
2422 switch (action) {
2423 case VNC_XVP_ACTION_SHUTDOWN:
2424 qemu_system_powerdown_request();
2425 break;
2426 case VNC_XVP_ACTION_REBOOT:
2427 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2428 break;
2429 case VNC_XVP_ACTION_RESET:
2430 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
2431 break;
2432 default:
2433 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2434 break;
2437 break;
2438 case VNC_MSG_CLIENT_QEMU:
2439 if (len == 1)
2440 return 2;
2442 switch (read_u8(data, 1)) {
2443 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2444 if (len == 2)
2445 return 12;
2447 ext_key_event(vs, read_u16(data, 2),
2448 read_u32(data, 4), read_u32(data, 8));
2449 break;
2450 case VNC_MSG_CLIENT_QEMU_AUDIO:
2451 if (len == 2)
2452 return 4;
2454 switch (read_u16 (data, 2)) {
2455 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2456 audio_add(vs);
2457 break;
2458 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2459 audio_del(vs);
2460 break;
2461 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2462 if (len == 4)
2463 return 10;
2464 switch (read_u8(data, 4)) {
2465 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
2466 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
2467 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
2468 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
2469 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
2470 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
2471 default:
2472 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2473 vnc_client_error(vs);
2474 break;
2476 vs->as.nchannels = read_u8(data, 5);
2477 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2478 VNC_DEBUG("Invalid audio channel count %d\n",
2479 read_u8(data, 5));
2480 vnc_client_error(vs);
2481 break;
2483 freq = read_u32(data, 6);
2484 /* No official limit for protocol, but 48khz is a sensible
2485 * upper bound for trustworthy clients, and this limit
2486 * protects calculations involving 'vs->as.freq' later.
2488 if (freq > 48000) {
2489 VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2490 vnc_client_error(vs);
2491 break;
2493 vs->as.freq = freq;
2494 break;
2495 default:
2496 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2497 vnc_client_error(vs);
2498 break;
2500 break;
2502 default:
2503 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2504 vnc_client_error(vs);
2505 break;
2507 break;
2508 case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2510 size_t size;
2511 uint8_t screens;
2513 if (len < 8) {
2514 return 8;
2517 screens = read_u8(data, 6);
2518 size = 8 + screens * 16;
2519 if (len < size) {
2520 return size;
2523 if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2524 QemuUIInfo info;
2525 memset(&info, 0, sizeof(info));
2526 info.width = read_u16(data, 2);
2527 info.height = read_u16(data, 4);
2528 dpy_set_ui_info(vs->vd->dcl.con, &info);
2529 vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2530 } else {
2531 vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2534 break;
2536 default:
2537 VNC_DEBUG("Msg: %d\n", data[0]);
2538 vnc_client_error(vs);
2539 break;
2542 vnc_update_throttle_offset(vs);
2543 vnc_read_when(vs, protocol_client_msg, 1);
2544 return 0;
2547 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2549 char buf[1024];
2550 VncShareMode mode;
2551 int size;
2553 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2554 switch (vs->vd->share_policy) {
2555 case VNC_SHARE_POLICY_IGNORE:
2557 * Ignore the shared flag. Nothing to do here.
2559 * Doesn't conform to the rfb spec but is traditional qemu
2560 * behavior, thus left here as option for compatibility
2561 * reasons.
2563 break;
2564 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2566 * Policy: Allow clients ask for exclusive access.
2568 * Implementation: When a client asks for exclusive access,
2569 * disconnect all others. Shared connects are allowed as long
2570 * as no exclusive connection exists.
2572 * This is how the rfb spec suggests to handle the shared flag.
2574 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2575 VncState *client;
2576 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2577 if (vs == client) {
2578 continue;
2580 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2581 client->share_mode != VNC_SHARE_MODE_SHARED) {
2582 continue;
2584 vnc_disconnect_start(client);
2587 if (mode == VNC_SHARE_MODE_SHARED) {
2588 if (vs->vd->num_exclusive > 0) {
2589 vnc_disconnect_start(vs);
2590 return 0;
2593 break;
2594 case VNC_SHARE_POLICY_FORCE_SHARED:
2596 * Policy: Shared connects only.
2597 * Implementation: Disallow clients asking for exclusive access.
2599 * Useful for shared desktop sessions where you don't want
2600 * someone forgetting to say -shared when running the vnc
2601 * client disconnect everybody else.
2603 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2604 vnc_disconnect_start(vs);
2605 return 0;
2607 break;
2609 vnc_set_share_mode(vs, mode);
2611 if (vs->vd->num_shared > vs->vd->connections_limit) {
2612 vnc_disconnect_start(vs);
2613 return 0;
2616 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2617 pixman_image_get_width(vs->vd->server) >= 0);
2618 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2619 pixman_image_get_height(vs->vd->server) >= 0);
2620 vs->client_width = pixman_image_get_width(vs->vd->server);
2621 vs->client_height = pixman_image_get_height(vs->vd->server);
2622 vnc_write_u16(vs, vs->client_width);
2623 vnc_write_u16(vs, vs->client_height);
2625 pixel_format_message(vs);
2627 if (qemu_name) {
2628 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2629 if (size > sizeof(buf)) {
2630 size = sizeof(buf);
2632 } else {
2633 size = snprintf(buf, sizeof(buf), "QEMU");
2636 vnc_write_u32(vs, size);
2637 vnc_write(vs, buf, size);
2638 vnc_flush(vs);
2640 vnc_client_cache_auth(vs);
2641 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2643 vnc_read_when(vs, protocol_client_msg, 1);
2645 return 0;
2648 void start_client_init(VncState *vs)
2650 vnc_read_when(vs, protocol_client_init, 1);
2653 static void authentication_failed(VncState *vs)
2655 vnc_write_u32(vs, 1); /* Reject auth */
2656 if (vs->minor >= 8) {
2657 static const char err[] = "Authentication failed";
2658 vnc_write_u32(vs, sizeof(err));
2659 vnc_write(vs, err, sizeof(err));
2661 vnc_flush(vs);
2662 vnc_client_error(vs);
2665 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2667 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2668 size_t i, pwlen;
2669 unsigned char key[8];
2670 time_t now = time(NULL);
2671 QCryptoCipher *cipher = NULL;
2672 Error *err = NULL;
2674 if (!vs->vd->password) {
2675 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2676 goto reject;
2678 if (vs->vd->expires < now) {
2679 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2680 goto reject;
2683 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2685 /* Calculate the expected challenge response */
2686 pwlen = strlen(vs->vd->password);
2687 for (i=0; i<sizeof(key); i++)
2688 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2690 cipher = qcrypto_cipher_new(
2691 QCRYPTO_CIPHER_ALG_DES_RFB,
2692 QCRYPTO_CIPHER_MODE_ECB,
2693 key, G_N_ELEMENTS(key),
2694 &err);
2695 if (!cipher) {
2696 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2697 error_get_pretty(err));
2698 error_free(err);
2699 goto reject;
2702 if (qcrypto_cipher_encrypt(cipher,
2703 vs->challenge,
2704 response,
2705 VNC_AUTH_CHALLENGE_SIZE,
2706 &err) < 0) {
2707 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2708 error_get_pretty(err));
2709 error_free(err);
2710 goto reject;
2713 /* Compare expected vs actual challenge response */
2714 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2715 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2716 goto reject;
2717 } else {
2718 trace_vnc_auth_pass(vs, vs->auth);
2719 vnc_write_u32(vs, 0); /* Accept auth */
2720 vnc_flush(vs);
2722 start_client_init(vs);
2725 qcrypto_cipher_free(cipher);
2726 return 0;
2728 reject:
2729 authentication_failed(vs);
2730 qcrypto_cipher_free(cipher);
2731 return 0;
2734 void start_auth_vnc(VncState *vs)
2736 Error *err = NULL;
2738 if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2739 trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2740 error_get_pretty(err));
2741 error_free(err);
2742 authentication_failed(vs);
2743 return;
2746 /* Send client a 'random' challenge */
2747 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2748 vnc_flush(vs);
2750 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2754 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2756 /* We only advertise 1 auth scheme at a time, so client
2757 * must pick the one we sent. Verify this */
2758 if (data[0] != vs->auth) { /* Reject auth */
2759 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2760 authentication_failed(vs);
2761 } else { /* Accept requested auth */
2762 trace_vnc_auth_start(vs, vs->auth);
2763 switch (vs->auth) {
2764 case VNC_AUTH_NONE:
2765 if (vs->minor >= 8) {
2766 vnc_write_u32(vs, 0); /* Accept auth completion */
2767 vnc_flush(vs);
2769 trace_vnc_auth_pass(vs, vs->auth);
2770 start_client_init(vs);
2771 break;
2773 case VNC_AUTH_VNC:
2774 start_auth_vnc(vs);
2775 break;
2777 case VNC_AUTH_VENCRYPT:
2778 start_auth_vencrypt(vs);
2779 break;
2781 #ifdef CONFIG_VNC_SASL
2782 case VNC_AUTH_SASL:
2783 start_auth_sasl(vs);
2784 break;
2785 #endif /* CONFIG_VNC_SASL */
2787 default: /* Should not be possible, but just in case */
2788 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2789 authentication_failed(vs);
2792 return 0;
2795 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2797 char local[13];
2799 memcpy(local, version, 12);
2800 local[12] = 0;
2802 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2803 VNC_DEBUG("Malformed protocol version %s\n", local);
2804 vnc_client_error(vs);
2805 return 0;
2807 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2808 if (vs->major != 3 ||
2809 (vs->minor != 3 &&
2810 vs->minor != 4 &&
2811 vs->minor != 5 &&
2812 vs->minor != 7 &&
2813 vs->minor != 8)) {
2814 VNC_DEBUG("Unsupported client version\n");
2815 vnc_write_u32(vs, VNC_AUTH_INVALID);
2816 vnc_flush(vs);
2817 vnc_client_error(vs);
2818 return 0;
2820 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2821 * as equivalent to v3.3 by servers
2823 if (vs->minor == 4 || vs->minor == 5)
2824 vs->minor = 3;
2826 if (vs->minor == 3) {
2827 trace_vnc_auth_start(vs, vs->auth);
2828 if (vs->auth == VNC_AUTH_NONE) {
2829 vnc_write_u32(vs, vs->auth);
2830 vnc_flush(vs);
2831 trace_vnc_auth_pass(vs, vs->auth);
2832 start_client_init(vs);
2833 } else if (vs->auth == VNC_AUTH_VNC) {
2834 VNC_DEBUG("Tell client VNC auth\n");
2835 vnc_write_u32(vs, vs->auth);
2836 vnc_flush(vs);
2837 start_auth_vnc(vs);
2838 } else {
2839 trace_vnc_auth_fail(vs, vs->auth,
2840 "Unsupported auth method for v3.3", "");
2841 vnc_write_u32(vs, VNC_AUTH_INVALID);
2842 vnc_flush(vs);
2843 vnc_client_error(vs);
2845 } else {
2846 vnc_write_u8(vs, 1); /* num auth */
2847 vnc_write_u8(vs, vs->auth);
2848 vnc_read_when(vs, protocol_client_auth, 1);
2849 vnc_flush(vs);
2852 return 0;
2855 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2857 struct VncSurface *vs = &vd->guest;
2859 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2862 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2864 int i, j;
2866 w = (x + w) / VNC_STAT_RECT;
2867 h = (y + h) / VNC_STAT_RECT;
2868 x /= VNC_STAT_RECT;
2869 y /= VNC_STAT_RECT;
2871 for (j = y; j <= h; j++) {
2872 for (i = x; i <= w; i++) {
2873 vs->lossy_rect[j][i] = 1;
2878 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2880 VncState *vs;
2881 int sty = y / VNC_STAT_RECT;
2882 int stx = x / VNC_STAT_RECT;
2883 int has_dirty = 0;
2885 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2886 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2888 QTAILQ_FOREACH(vs, &vd->clients, next) {
2889 int j;
2891 /* kernel send buffers are full -> refresh later */
2892 if (vs->output.offset) {
2893 continue;
2896 if (!vs->lossy_rect[sty][stx]) {
2897 continue;
2900 vs->lossy_rect[sty][stx] = 0;
2901 for (j = 0; j < VNC_STAT_RECT; ++j) {
2902 bitmap_set(vs->dirty[y + j],
2903 x / VNC_DIRTY_PIXELS_PER_BIT,
2904 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2906 has_dirty++;
2909 return has_dirty;
2912 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2914 int width = MIN(pixman_image_get_width(vd->guest.fb),
2915 pixman_image_get_width(vd->server));
2916 int height = MIN(pixman_image_get_height(vd->guest.fb),
2917 pixman_image_get_height(vd->server));
2918 int x, y;
2919 struct timeval res;
2920 int has_dirty = 0;
2922 for (y = 0; y < height; y += VNC_STAT_RECT) {
2923 for (x = 0; x < width; x += VNC_STAT_RECT) {
2924 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2926 rect->updated = false;
2930 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2932 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2933 return has_dirty;
2935 vd->guest.last_freq_check = *tv;
2937 for (y = 0; y < height; y += VNC_STAT_RECT) {
2938 for (x = 0; x < width; x += VNC_STAT_RECT) {
2939 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2940 int count = ARRAY_SIZE(rect->times);
2941 struct timeval min, max;
2943 if (!timerisset(&rect->times[count - 1])) {
2944 continue ;
2947 max = rect->times[(rect->idx + count - 1) % count];
2948 qemu_timersub(tv, &max, &res);
2950 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2951 rect->freq = 0;
2952 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2953 memset(rect->times, 0, sizeof (rect->times));
2954 continue ;
2957 min = rect->times[rect->idx];
2958 max = rect->times[(rect->idx + count - 1) % count];
2959 qemu_timersub(&max, &min, &res);
2961 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2962 rect->freq /= count;
2963 rect->freq = 1. / rect->freq;
2966 return has_dirty;
2969 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2971 int i, j;
2972 double total = 0;
2973 int num = 0;
2975 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2976 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2978 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2979 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2980 total += vnc_stat_rect(vs->vd, i, j)->freq;
2981 num++;
2985 if (num) {
2986 return total / num;
2987 } else {
2988 return 0;
2992 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2994 VncRectStat *rect;
2996 rect = vnc_stat_rect(vd, x, y);
2997 if (rect->updated) {
2998 return ;
3000 rect->times[rect->idx] = *tv;
3001 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3002 rect->updated = true;
3005 static int vnc_refresh_server_surface(VncDisplay *vd)
3007 int width = MIN(pixman_image_get_width(vd->guest.fb),
3008 pixman_image_get_width(vd->server));
3009 int height = MIN(pixman_image_get_height(vd->guest.fb),
3010 pixman_image_get_height(vd->server));
3011 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
3012 uint8_t *guest_row0 = NULL, *server_row0;
3013 VncState *vs;
3014 int has_dirty = 0;
3015 pixman_image_t *tmpbuf = NULL;
3017 struct timeval tv = { 0, 0 };
3019 if (!vd->non_adaptive) {
3020 gettimeofday(&tv, NULL);
3021 has_dirty = vnc_update_stats(vd, &tv);
3025 * Walk through the guest dirty map.
3026 * Check and copy modified bits from guest to server surface.
3027 * Update server dirty map.
3029 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3030 server_stride = guest_stride = guest_ll =
3031 pixman_image_get_stride(vd->server);
3032 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3033 server_stride);
3034 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3035 int width = pixman_image_get_width(vd->server);
3036 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
3037 } else {
3038 int guest_bpp =
3039 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
3040 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
3041 guest_stride = pixman_image_get_stride(vd->guest.fb);
3042 guest_ll = pixman_image_get_width(vd->guest.fb)
3043 * DIV_ROUND_UP(guest_bpp, 8);
3045 line_bytes = MIN(server_stride, guest_ll);
3047 for (;;) {
3048 int x;
3049 uint8_t *guest_ptr, *server_ptr;
3050 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
3051 height * VNC_DIRTY_BPL(&vd->guest),
3052 y * VNC_DIRTY_BPL(&vd->guest));
3053 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
3054 /* no more dirty bits */
3055 break;
3057 y = offset / VNC_DIRTY_BPL(&vd->guest);
3058 x = offset % VNC_DIRTY_BPL(&vd->guest);
3060 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
3062 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3063 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
3064 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
3065 } else {
3066 guest_ptr = guest_row0 + y * guest_stride;
3068 guest_ptr += x * cmp_bytes;
3070 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
3071 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3072 int _cmp_bytes = cmp_bytes;
3073 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
3074 continue;
3076 if ((x + 1) * cmp_bytes > line_bytes) {
3077 _cmp_bytes = line_bytes - x * cmp_bytes;
3079 assert(_cmp_bytes >= 0);
3080 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
3081 continue;
3083 memcpy(server_ptr, guest_ptr, _cmp_bytes);
3084 if (!vd->non_adaptive) {
3085 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
3086 y, &tv);
3088 QTAILQ_FOREACH(vs, &vd->clients, next) {
3089 set_bit(x, vs->dirty[y]);
3091 has_dirty++;
3094 y++;
3096 qemu_pixman_image_unref(tmpbuf);
3097 return has_dirty;
3100 static void vnc_refresh(DisplayChangeListener *dcl)
3102 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
3103 VncState *vs, *vn;
3104 int has_dirty, rects = 0;
3106 if (QTAILQ_EMPTY(&vd->clients)) {
3107 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
3108 return;
3111 graphic_hw_update(vd->dcl.con);
3113 if (vnc_trylock_display(vd)) {
3114 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3115 return;
3118 has_dirty = vnc_refresh_server_surface(vd);
3119 vnc_unlock_display(vd);
3121 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3122 rects += vnc_update_client(vs, has_dirty);
3123 /* vs might be free()ed here */
3126 if (has_dirty && rects) {
3127 vd->dcl.update_interval /= 2;
3128 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3129 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3131 } else {
3132 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3133 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3134 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3139 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3140 bool skipauth, bool websocket)
3142 VncState *vs = g_new0(VncState, 1);
3143 bool first_client = QTAILQ_EMPTY(&vd->clients);
3144 int i;
3146 trace_vnc_client_connect(vs, sioc);
3147 vs->zrle = g_new0(VncZrle, 1);
3148 vs->tight = g_new0(VncTight, 1);
3149 vs->magic = VNC_MAGIC;
3150 vs->sioc = sioc;
3151 object_ref(OBJECT(vs->sioc));
3152 vs->ioc = QIO_CHANNEL(sioc);
3153 object_ref(OBJECT(vs->ioc));
3154 vs->vd = vd;
3156 buffer_init(&vs->input, "vnc-input/%p", sioc);
3157 buffer_init(&vs->output, "vnc-output/%p", sioc);
3158 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
3160 buffer_init(&vs->tight->tight, "vnc-tight/%p", sioc);
3161 buffer_init(&vs->tight->zlib, "vnc-tight-zlib/%p", sioc);
3162 buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3163 #ifdef CONFIG_VNC_JPEG
3164 buffer_init(&vs->tight->jpeg, "vnc-tight-jpeg/%p", sioc);
3165 #endif
3166 #ifdef CONFIG_VNC_PNG
3167 buffer_init(&vs->tight->png, "vnc-tight-png/%p", sioc);
3168 #endif
3169 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
3170 buffer_init(&vs->zrle->zrle, "vnc-zrle/%p", sioc);
3171 buffer_init(&vs->zrle->fb, "vnc-zrle-fb/%p", sioc);
3172 buffer_init(&vs->zrle->zlib, "vnc-zrle-zlib/%p", sioc);
3174 if (skipauth) {
3175 vs->auth = VNC_AUTH_NONE;
3176 vs->subauth = VNC_AUTH_INVALID;
3177 } else {
3178 if (websocket) {
3179 vs->auth = vd->ws_auth;
3180 vs->subauth = VNC_AUTH_INVALID;
3181 } else {
3182 vs->auth = vd->auth;
3183 vs->subauth = vd->subauth;
3186 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3187 sioc, websocket, vs->auth, vs->subauth);
3189 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3190 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3191 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3194 VNC_DEBUG("New client on socket %p\n", vs->sioc);
3195 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3196 qio_channel_set_blocking(vs->ioc, false, NULL);
3197 if (vs->ioc_tag) {
3198 g_source_remove(vs->ioc_tag);
3200 if (websocket) {
3201 vs->websocket = 1;
3202 if (vd->tlscreds) {
3203 vs->ioc_tag = qio_channel_add_watch(
3204 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3205 vncws_tls_handshake_io, vs, NULL);
3206 } else {
3207 vs->ioc_tag = qio_channel_add_watch(
3208 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3209 vncws_handshake_io, vs, NULL);
3211 } else {
3212 vs->ioc_tag = qio_channel_add_watch(
3213 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3214 vnc_client_io, vs, NULL);
3217 vnc_client_cache_addr(vs);
3218 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3219 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3221 vs->last_x = -1;
3222 vs->last_y = -1;
3224 vs->as.freq = 44100;
3225 vs->as.nchannels = 2;
3226 vs->as.fmt = AUDIO_FORMAT_S16;
3227 vs->as.endianness = 0;
3229 qemu_mutex_init(&vs->output_mutex);
3230 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3232 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3233 if (first_client) {
3234 vnc_update_server_surface(vd);
3237 graphic_hw_update(vd->dcl.con);
3239 if (!vs->websocket) {
3240 vnc_start_protocol(vs);
3243 if (vd->num_connecting > vd->connections_limit) {
3244 QTAILQ_FOREACH(vs, &vd->clients, next) {
3245 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3246 vnc_disconnect_start(vs);
3247 return;
3253 void vnc_start_protocol(VncState *vs)
3255 vnc_write(vs, "RFB 003.008\n", 12);
3256 vnc_flush(vs);
3257 vnc_read_when(vs, protocol_version, 12);
3259 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3260 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3263 static void vnc_listen_io(QIONetListener *listener,
3264 QIOChannelSocket *cioc,
3265 void *opaque)
3267 VncDisplay *vd = opaque;
3268 bool isWebsock = listener == vd->wslistener;
3270 qio_channel_set_name(QIO_CHANNEL(cioc),
3271 isWebsock ? "vnc-ws-server" : "vnc-server");
3272 qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3273 vnc_connect(vd, cioc, false, isWebsock);
3276 static const DisplayChangeListenerOps dcl_ops = {
3277 .dpy_name = "vnc",
3278 .dpy_refresh = vnc_refresh,
3279 .dpy_gfx_update = vnc_dpy_update,
3280 .dpy_gfx_switch = vnc_dpy_switch,
3281 .dpy_gfx_check_format = qemu_pixman_check_format,
3282 .dpy_mouse_set = vnc_mouse_set,
3283 .dpy_cursor_define = vnc_dpy_cursor_define,
3286 void vnc_display_init(const char *id, Error **errp)
3288 VncDisplay *vd;
3290 if (vnc_display_find(id) != NULL) {
3291 return;
3293 vd = g_malloc0(sizeof(*vd));
3295 vd->id = strdup(id);
3296 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3298 QTAILQ_INIT(&vd->clients);
3299 vd->expires = TIME_MAX;
3301 if (keyboard_layout) {
3302 trace_vnc_key_map_init(keyboard_layout);
3303 vd->kbd_layout = init_keyboard_layout(name2keysym,
3304 keyboard_layout, errp);
3305 } else {
3306 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3309 if (!vd->kbd_layout) {
3310 return;
3313 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3314 vd->connections_limit = 32;
3316 qemu_mutex_init(&vd->mutex);
3317 vnc_start_worker_thread();
3319 vd->dcl.ops = &dcl_ops;
3320 register_displaychangelistener(&vd->dcl);
3321 vd->kbd = qkbd_state_init(vd->dcl.con);
3325 static void vnc_display_close(VncDisplay *vd)
3327 if (!vd) {
3328 return;
3330 vd->is_unix = false;
3332 if (vd->listener) {
3333 qio_net_listener_disconnect(vd->listener);
3334 object_unref(OBJECT(vd->listener));
3336 vd->listener = NULL;
3338 if (vd->wslistener) {
3339 qio_net_listener_disconnect(vd->wslistener);
3340 object_unref(OBJECT(vd->wslistener));
3342 vd->wslistener = NULL;
3344 vd->auth = VNC_AUTH_INVALID;
3345 vd->subauth = VNC_AUTH_INVALID;
3346 if (vd->tlscreds) {
3347 object_unref(OBJECT(vd->tlscreds));
3348 vd->tlscreds = NULL;
3350 if (vd->tlsauthz) {
3351 object_unparent(OBJECT(vd->tlsauthz));
3352 vd->tlsauthz = NULL;
3354 g_free(vd->tlsauthzid);
3355 vd->tlsauthzid = NULL;
3356 if (vd->lock_key_sync) {
3357 qemu_remove_led_event_handler(vd->led);
3358 vd->led = NULL;
3360 #ifdef CONFIG_VNC_SASL
3361 if (vd->sasl.authz) {
3362 object_unparent(OBJECT(vd->sasl.authz));
3363 vd->sasl.authz = NULL;
3365 g_free(vd->sasl.authzid);
3366 vd->sasl.authzid = NULL;
3367 #endif
3370 int vnc_display_password(const char *id, const char *password)
3372 VncDisplay *vd = vnc_display_find(id);
3374 if (!vd) {
3375 return -EINVAL;
3377 if (vd->auth == VNC_AUTH_NONE) {
3378 error_printf_unless_qmp("If you want use passwords please enable "
3379 "password auth using '-vnc ${dpy},password'.\n");
3380 return -EINVAL;
3383 g_free(vd->password);
3384 vd->password = g_strdup(password);
3386 return 0;
3389 int vnc_display_pw_expire(const char *id, time_t expires)
3391 VncDisplay *vd = vnc_display_find(id);
3393 if (!vd) {
3394 return -EINVAL;
3397 vd->expires = expires;
3398 return 0;
3401 static void vnc_display_print_local_addr(VncDisplay *vd)
3403 SocketAddress *addr;
3405 if (!vd->listener || !vd->listener->nsioc) {
3406 return;
3409 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
3410 if (!addr) {
3411 return;
3414 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3415 qapi_free_SocketAddress(addr);
3416 return;
3418 error_printf_unless_qmp("VNC server running on %s:%s\n",
3419 addr->u.inet.host,
3420 addr->u.inet.port);
3421 qapi_free_SocketAddress(addr);
3424 static QemuOptsList qemu_vnc_opts = {
3425 .name = "vnc",
3426 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3427 .implied_opt_name = "vnc",
3428 .desc = {
3430 .name = "vnc",
3431 .type = QEMU_OPT_STRING,
3433 .name = "websocket",
3434 .type = QEMU_OPT_STRING,
3436 .name = "tls-creds",
3437 .type = QEMU_OPT_STRING,
3439 .name = "share",
3440 .type = QEMU_OPT_STRING,
3442 .name = "display",
3443 .type = QEMU_OPT_STRING,
3445 .name = "head",
3446 .type = QEMU_OPT_NUMBER,
3448 .name = "connections",
3449 .type = QEMU_OPT_NUMBER,
3451 .name = "to",
3452 .type = QEMU_OPT_NUMBER,
3454 .name = "ipv4",
3455 .type = QEMU_OPT_BOOL,
3457 .name = "ipv6",
3458 .type = QEMU_OPT_BOOL,
3460 .name = "password",
3461 .type = QEMU_OPT_BOOL,
3463 .name = "reverse",
3464 .type = QEMU_OPT_BOOL,
3466 .name = "lock-key-sync",
3467 .type = QEMU_OPT_BOOL,
3469 .name = "key-delay-ms",
3470 .type = QEMU_OPT_NUMBER,
3472 .name = "sasl",
3473 .type = QEMU_OPT_BOOL,
3475 .name = "acl",
3476 .type = QEMU_OPT_BOOL,
3478 .name = "tls-authz",
3479 .type = QEMU_OPT_STRING,
3481 .name = "sasl-authz",
3482 .type = QEMU_OPT_STRING,
3484 .name = "lossy",
3485 .type = QEMU_OPT_BOOL,
3487 .name = "non-adaptive",
3488 .type = QEMU_OPT_BOOL,
3490 .name = "audiodev",
3491 .type = QEMU_OPT_STRING,
3493 .name = "power-control",
3494 .type = QEMU_OPT_BOOL,
3496 { /* end of list */ }
3501 static int
3502 vnc_display_setup_auth(int *auth,
3503 int *subauth,
3504 QCryptoTLSCreds *tlscreds,
3505 bool password,
3506 bool sasl,
3507 bool websocket,
3508 Error **errp)
3511 * We have a choice of 3 authentication options
3513 * 1. none
3514 * 2. vnc
3515 * 3. sasl
3517 * The channel can be run in 2 modes
3519 * 1. clear
3520 * 2. tls
3522 * And TLS can use 2 types of credentials
3524 * 1. anon
3525 * 2. x509
3527 * We thus have 9 possible logical combinations
3529 * 1. clear + none
3530 * 2. clear + vnc
3531 * 3. clear + sasl
3532 * 4. tls + anon + none
3533 * 5. tls + anon + vnc
3534 * 6. tls + anon + sasl
3535 * 7. tls + x509 + none
3536 * 8. tls + x509 + vnc
3537 * 9. tls + x509 + sasl
3539 * These need to be mapped into the VNC auth schemes
3540 * in an appropriate manner. In regular VNC, all the
3541 * TLS options get mapped into VNC_AUTH_VENCRYPT
3542 * sub-auth types.
3544 * In websockets, the https:// protocol already provides
3545 * TLS support, so there is no need to make use of the
3546 * VeNCrypt extension. Furthermore, websockets browser
3547 * clients could not use VeNCrypt even if they wanted to,
3548 * as they cannot control when the TLS handshake takes
3549 * place. Thus there is no option but to rely on https://,
3550 * meaning combinations 4->6 and 7->9 will be mapped to
3551 * VNC auth schemes in the same way as combos 1->3.
3553 * Regardless of fact that we have a different mapping to
3554 * VNC auth mechs for plain VNC vs websockets VNC, the end
3555 * result has the same security characteristics.
3557 if (websocket || !tlscreds) {
3558 if (password) {
3559 VNC_DEBUG("Initializing VNC server with password auth\n");
3560 *auth = VNC_AUTH_VNC;
3561 } else if (sasl) {
3562 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3563 *auth = VNC_AUTH_SASL;
3564 } else {
3565 VNC_DEBUG("Initializing VNC server with no auth\n");
3566 *auth = VNC_AUTH_NONE;
3568 *subauth = VNC_AUTH_INVALID;
3569 } else {
3570 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3571 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3572 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3573 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3575 if (!is_x509 && !is_anon) {
3576 error_setg(errp,
3577 "Unsupported TLS cred type %s",
3578 object_get_typename(OBJECT(tlscreds)));
3579 return -1;
3581 *auth = VNC_AUTH_VENCRYPT;
3582 if (password) {
3583 if (is_x509) {
3584 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3585 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3586 } else {
3587 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3588 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3591 } else if (sasl) {
3592 if (is_x509) {
3593 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3594 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3595 } else {
3596 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3597 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3599 } else {
3600 if (is_x509) {
3601 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3602 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3603 } else {
3604 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3605 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3609 return 0;
3613 static int vnc_display_get_address(const char *addrstr,
3614 bool websocket,
3615 bool reverse,
3616 int displaynum,
3617 int to,
3618 bool has_ipv4,
3619 bool has_ipv6,
3620 bool ipv4,
3621 bool ipv6,
3622 SocketAddress **retaddr,
3623 Error **errp)
3625 int ret = -1;
3626 SocketAddress *addr = NULL;
3628 addr = g_new0(SocketAddress, 1);
3630 if (strncmp(addrstr, "unix:", 5) == 0) {
3631 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3632 addr->u.q_unix.path = g_strdup(addrstr + 5);
3634 if (websocket) {
3635 error_setg(errp, "UNIX sockets not supported with websock");
3636 goto cleanup;
3639 if (to) {
3640 error_setg(errp, "Port range not support with UNIX socket");
3641 goto cleanup;
3643 ret = 0;
3644 } else {
3645 const char *port;
3646 size_t hostlen;
3647 unsigned long long baseport = 0;
3648 InetSocketAddress *inet;
3650 port = strrchr(addrstr, ':');
3651 if (!port) {
3652 if (websocket) {
3653 hostlen = 0;
3654 port = addrstr;
3655 } else {
3656 error_setg(errp, "no vnc port specified");
3657 goto cleanup;
3659 } else {
3660 hostlen = port - addrstr;
3661 port++;
3662 if (*port == '\0') {
3663 error_setg(errp, "vnc port cannot be empty");
3664 goto cleanup;
3668 addr->type = SOCKET_ADDRESS_TYPE_INET;
3669 inet = &addr->u.inet;
3670 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3671 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3672 } else {
3673 inet->host = g_strndup(addrstr, hostlen);
3675 /* plain VNC port is just an offset, for websocket
3676 * port is absolute */
3677 if (websocket) {
3678 if (g_str_equal(addrstr, "") ||
3679 g_str_equal(addrstr, "on")) {
3680 if (displaynum == -1) {
3681 error_setg(errp, "explicit websocket port is required");
3682 goto cleanup;
3684 inet->port = g_strdup_printf(
3685 "%d", displaynum + 5700);
3686 if (to) {
3687 inet->has_to = true;
3688 inet->to = to + 5700;
3690 } else {
3691 inet->port = g_strdup(port);
3693 } else {
3694 int offset = reverse ? 0 : 5900;
3695 if (parse_uint_full(port, &baseport, 10) < 0) {
3696 error_setg(errp, "can't convert to a number: %s", port);
3697 goto cleanup;
3699 if (baseport > 65535 ||
3700 baseport + offset > 65535) {
3701 error_setg(errp, "port %s out of range", port);
3702 goto cleanup;
3704 inet->port = g_strdup_printf(
3705 "%d", (int)baseport + offset);
3707 if (to) {
3708 inet->has_to = true;
3709 inet->to = to + offset;
3713 inet->ipv4 = ipv4;
3714 inet->has_ipv4 = has_ipv4;
3715 inet->ipv6 = ipv6;
3716 inet->has_ipv6 = has_ipv6;
3718 ret = baseport;
3721 *retaddr = addr;
3723 cleanup:
3724 if (ret < 0) {
3725 qapi_free_SocketAddress(addr);
3727 return ret;
3730 static void vnc_free_addresses(SocketAddress ***retsaddr,
3731 size_t *retnsaddr)
3733 size_t i;
3735 for (i = 0; i < *retnsaddr; i++) {
3736 qapi_free_SocketAddress((*retsaddr)[i]);
3738 g_free(*retsaddr);
3740 *retsaddr = NULL;
3741 *retnsaddr = 0;
3744 static int vnc_display_get_addresses(QemuOpts *opts,
3745 bool reverse,
3746 SocketAddress ***retsaddr,
3747 size_t *retnsaddr,
3748 SocketAddress ***retwsaddr,
3749 size_t *retnwsaddr,
3750 Error **errp)
3752 SocketAddress *saddr = NULL;
3753 SocketAddress *wsaddr = NULL;
3754 QemuOptsIter addriter;
3755 const char *addr;
3756 int to = qemu_opt_get_number(opts, "to", 0);
3757 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3758 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3759 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3760 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3761 int displaynum = -1;
3762 int ret = -1;
3764 *retsaddr = NULL;
3765 *retnsaddr = 0;
3766 *retwsaddr = NULL;
3767 *retnwsaddr = 0;
3769 addr = qemu_opt_get(opts, "vnc");
3770 if (addr == NULL || g_str_equal(addr, "none")) {
3771 ret = 0;
3772 goto cleanup;
3774 if (qemu_opt_get(opts, "websocket") &&
3775 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3776 error_setg(errp,
3777 "SHA1 hash support is required for websockets");
3778 goto cleanup;
3781 qemu_opt_iter_init(&addriter, opts, "vnc");
3782 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3783 int rv;
3784 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3785 has_ipv4, has_ipv6,
3786 ipv4, ipv6,
3787 &saddr, errp);
3788 if (rv < 0) {
3789 goto cleanup;
3791 /* Historical compat - first listen address can be used
3792 * to set the default websocket port
3794 if (displaynum == -1) {
3795 displaynum = rv;
3797 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3798 (*retsaddr)[(*retnsaddr)++] = saddr;
3801 /* If we had multiple primary displays, we don't do defaults
3802 * for websocket, and require explicit config instead. */
3803 if (*retnsaddr > 1) {
3804 displaynum = -1;
3807 qemu_opt_iter_init(&addriter, opts, "websocket");
3808 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3809 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3810 has_ipv4, has_ipv6,
3811 ipv4, ipv6,
3812 &wsaddr, errp) < 0) {
3813 goto cleanup;
3816 /* Historical compat - if only a single listen address was
3817 * provided, then this is used to set the default listen
3818 * address for websocket too
3820 if (*retnsaddr == 1 &&
3821 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3822 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3823 g_str_equal(wsaddr->u.inet.host, "") &&
3824 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3825 g_free(wsaddr->u.inet.host);
3826 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3829 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3830 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3833 ret = 0;
3834 cleanup:
3835 if (ret < 0) {
3836 vnc_free_addresses(retsaddr, retnsaddr);
3837 vnc_free_addresses(retwsaddr, retnwsaddr);
3839 return ret;
3842 static int vnc_display_connect(VncDisplay *vd,
3843 SocketAddress **saddr,
3844 size_t nsaddr,
3845 SocketAddress **wsaddr,
3846 size_t nwsaddr,
3847 Error **errp)
3849 /* connect to viewer */
3850 QIOChannelSocket *sioc = NULL;
3851 if (nwsaddr != 0) {
3852 error_setg(errp, "Cannot use websockets in reverse mode");
3853 return -1;
3855 if (nsaddr != 1) {
3856 error_setg(errp, "Expected a single address in reverse mode");
3857 return -1;
3859 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3860 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3861 sioc = qio_channel_socket_new();
3862 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3863 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3864 object_unref(OBJECT(sioc));
3865 return -1;
3867 vnc_connect(vd, sioc, false, false);
3868 object_unref(OBJECT(sioc));
3869 return 0;
3873 static int vnc_display_listen(VncDisplay *vd,
3874 SocketAddress **saddr,
3875 size_t nsaddr,
3876 SocketAddress **wsaddr,
3877 size_t nwsaddr,
3878 Error **errp)
3880 size_t i;
3882 if (nsaddr) {
3883 vd->listener = qio_net_listener_new();
3884 qio_net_listener_set_name(vd->listener, "vnc-listen");
3885 for (i = 0; i < nsaddr; i++) {
3886 if (qio_net_listener_open_sync(vd->listener,
3887 saddr[i], 1,
3888 errp) < 0) {
3889 return -1;
3893 qio_net_listener_set_client_func(vd->listener,
3894 vnc_listen_io, vd, NULL);
3897 if (nwsaddr) {
3898 vd->wslistener = qio_net_listener_new();
3899 qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3900 for (i = 0; i < nwsaddr; i++) {
3901 if (qio_net_listener_open_sync(vd->wslistener,
3902 wsaddr[i], 1,
3903 errp) < 0) {
3904 return -1;
3908 qio_net_listener_set_client_func(vd->wslistener,
3909 vnc_listen_io, vd, NULL);
3912 return 0;
3916 void vnc_display_open(const char *id, Error **errp)
3918 VncDisplay *vd = vnc_display_find(id);
3919 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3920 SocketAddress **saddr = NULL, **wsaddr = NULL;
3921 size_t nsaddr, nwsaddr;
3922 const char *share, *device_id;
3923 QemuConsole *con;
3924 bool password = false;
3925 bool reverse = false;
3926 const char *credid;
3927 bool sasl = false;
3928 int acl = 0;
3929 const char *tlsauthz;
3930 const char *saslauthz;
3931 int lock_key_sync = 1;
3932 int key_delay_ms;
3933 const char *audiodev;
3935 if (!vd) {
3936 error_setg(errp, "VNC display not active");
3937 return;
3939 vnc_display_close(vd);
3941 if (!opts) {
3942 return;
3945 reverse = qemu_opt_get_bool(opts, "reverse", false);
3946 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3947 &wsaddr, &nwsaddr, errp) < 0) {
3948 goto fail;
3951 password = qemu_opt_get_bool(opts, "password", false);
3952 if (password) {
3953 if (fips_get_state()) {
3954 error_setg(errp,
3955 "VNC password auth disabled due to FIPS mode, "
3956 "consider using the VeNCrypt or SASL authentication "
3957 "methods as an alternative");
3958 goto fail;
3960 if (!qcrypto_cipher_supports(
3961 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3962 error_setg(errp,
3963 "Cipher backend does not support DES RFB algorithm");
3964 goto fail;
3968 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3969 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3970 sasl = qemu_opt_get_bool(opts, "sasl", false);
3971 #ifndef CONFIG_VNC_SASL
3972 if (sasl) {
3973 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3974 goto fail;
3976 #endif /* CONFIG_VNC_SASL */
3977 credid = qemu_opt_get(opts, "tls-creds");
3978 if (credid) {
3979 Object *creds;
3980 creds = object_resolve_path_component(
3981 object_get_objects_root(), credid);
3982 if (!creds) {
3983 error_setg(errp, "No TLS credentials with id '%s'",
3984 credid);
3985 goto fail;
3987 vd->tlscreds = (QCryptoTLSCreds *)
3988 object_dynamic_cast(creds,
3989 TYPE_QCRYPTO_TLS_CREDS);
3990 if (!vd->tlscreds) {
3991 error_setg(errp, "Object with id '%s' is not TLS credentials",
3992 credid);
3993 goto fail;
3995 object_ref(OBJECT(vd->tlscreds));
3997 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3998 error_setg(errp,
3999 "Expecting TLS credentials with a server endpoint");
4000 goto fail;
4003 if (qemu_opt_get(opts, "acl")) {
4004 error_report("The 'acl' option to -vnc is deprecated. "
4005 "Please use the 'tls-authz' and 'sasl-authz' "
4006 "options instead");
4008 acl = qemu_opt_get_bool(opts, "acl", false);
4009 tlsauthz = qemu_opt_get(opts, "tls-authz");
4010 if (acl && tlsauthz) {
4011 error_setg(errp, "'acl' option is mutually exclusive with the "
4012 "'tls-authz' option");
4013 goto fail;
4015 if (tlsauthz && !vd->tlscreds) {
4016 error_setg(errp, "'tls-authz' provided but TLS is not enabled");
4017 goto fail;
4020 saslauthz = qemu_opt_get(opts, "sasl-authz");
4021 if (acl && saslauthz) {
4022 error_setg(errp, "'acl' option is mutually exclusive with the "
4023 "'sasl-authz' option");
4024 goto fail;
4026 if (saslauthz && !sasl) {
4027 error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
4028 goto fail;
4031 share = qemu_opt_get(opts, "share");
4032 if (share) {
4033 if (strcmp(share, "ignore") == 0) {
4034 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
4035 } else if (strcmp(share, "allow-exclusive") == 0) {
4036 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4037 } else if (strcmp(share, "force-shared") == 0) {
4038 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
4039 } else {
4040 error_setg(errp, "unknown vnc share= option");
4041 goto fail;
4043 } else {
4044 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4046 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
4048 #ifdef CONFIG_VNC_JPEG
4049 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
4050 #endif
4051 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4052 /* adaptive updates are only used with tight encoding and
4053 * if lossy updates are enabled so we can disable all the
4054 * calculations otherwise */
4055 if (!vd->lossy) {
4056 vd->non_adaptive = true;
4059 vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
4061 if (tlsauthz) {
4062 vd->tlsauthzid = g_strdup(tlsauthz);
4063 } else if (acl) {
4064 if (strcmp(vd->id, "default") == 0) {
4065 vd->tlsauthzid = g_strdup("vnc.x509dname");
4066 } else {
4067 vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
4069 vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
4070 QAUTHZ_LIST_POLICY_DENY,
4071 &error_abort));
4073 #ifdef CONFIG_VNC_SASL
4074 if (sasl) {
4075 if (saslauthz) {
4076 vd->sasl.authzid = g_strdup(saslauthz);
4077 } else if (acl) {
4078 if (strcmp(vd->id, "default") == 0) {
4079 vd->sasl.authzid = g_strdup("vnc.username");
4080 } else {
4081 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
4083 vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
4084 QAUTHZ_LIST_POLICY_DENY,
4085 &error_abort));
4088 #endif
4090 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4091 vd->tlscreds, password,
4092 sasl, false, errp) < 0) {
4093 goto fail;
4095 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4097 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4098 vd->tlscreds, password,
4099 sasl, true, errp) < 0) {
4100 goto fail;
4102 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
4104 #ifdef CONFIG_VNC_SASL
4105 if (sasl) {
4106 int saslErr = sasl_server_init(NULL, "qemu");
4108 if (saslErr != SASL_OK) {
4109 error_setg(errp, "Failed to initialize SASL auth: %s",
4110 sasl_errstring(saslErr, NULL, NULL));
4111 goto fail;
4114 #endif
4115 vd->lock_key_sync = lock_key_sync;
4116 if (lock_key_sync) {
4117 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4119 vd->ledstate = 0;
4121 audiodev = qemu_opt_get(opts, "audiodev");
4122 if (audiodev) {
4123 vd->audio_state = audio_state_by_name(audiodev);
4124 if (!vd->audio_state) {
4125 error_setg(errp, "Audiodev '%s' not found", audiodev);
4126 goto fail;
4130 device_id = qemu_opt_get(opts, "display");
4131 if (device_id) {
4132 int head = qemu_opt_get_number(opts, "head", 0);
4133 Error *err = NULL;
4135 con = qemu_console_lookup_by_device_name(device_id, head, &err);
4136 if (err) {
4137 error_propagate(errp, err);
4138 goto fail;
4140 } else {
4141 con = NULL;
4144 if (con != vd->dcl.con) {
4145 qkbd_state_free(vd->kbd);
4146 unregister_displaychangelistener(&vd->dcl);
4147 vd->dcl.con = con;
4148 register_displaychangelistener(&vd->dcl);
4149 vd->kbd = qkbd_state_init(vd->dcl.con);
4151 qkbd_state_set_delay(vd->kbd, key_delay_ms);
4153 if (saddr == NULL) {
4154 goto cleanup;
4157 if (reverse) {
4158 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4159 goto fail;
4161 } else {
4162 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4163 goto fail;
4167 if (qemu_opt_get(opts, "to")) {
4168 vnc_display_print_local_addr(vd);
4171 cleanup:
4172 vnc_free_addresses(&saddr, &nsaddr);
4173 vnc_free_addresses(&wsaddr, &nwsaddr);
4174 return;
4176 fail:
4177 vnc_display_close(vd);
4178 goto cleanup;
4181 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4183 VncDisplay *vd = vnc_display_find(id);
4184 QIOChannelSocket *sioc;
4186 if (!vd) {
4187 return;
4190 sioc = qio_channel_socket_new_fd(csock, NULL);
4191 if (sioc) {
4192 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4193 vnc_connect(vd, sioc, skipauth, false);
4194 object_unref(OBJECT(sioc));
4198 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4200 int i = 2;
4201 char *id;
4203 id = g_strdup("default");
4204 while (qemu_opts_find(olist, id)) {
4205 g_free(id);
4206 id = g_strdup_printf("vnc%d", i++);
4208 qemu_opts_set_id(opts, id);
4211 void vnc_parse(const char *str)
4213 QemuOptsList *olist = qemu_find_opts("vnc");
4214 QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
4215 const char *id;
4217 if (!opts) {
4218 exit(1);
4221 id = qemu_opts_id(opts);
4222 if (!id) {
4223 /* auto-assign id if not present */
4224 vnc_auto_assign_id(olist, opts);
4228 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4230 Error *local_err = NULL;
4231 char *id = (char *)qemu_opts_id(opts);
4233 assert(id);
4234 vnc_display_init(id, &local_err);
4235 if (local_err) {
4236 error_propagate(errp, local_err);
4237 return -1;
4239 vnc_display_open(id, &local_err);
4240 if (local_err != NULL) {
4241 error_propagate(errp, local_err);
4242 return -1;
4244 return 0;
4247 static void vnc_register_config(void)
4249 qemu_add_opts(&qemu_vnc_opts);
4251 opts_init(vnc_register_config);