2 * QEMU VNC display driver
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
27 #include "qemu/osdep.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"
47 #include "crypto/hash.h"
48 #include "crypto/tlscredsanon.h"
49 #include "crypto/tlscredsx509.h"
50 #include "crypto/random.h"
51 #include "crypto/secret_common.h"
52 #include "qom/object_interfaces.h"
53 #include "qemu/cutils.h"
54 #include "qemu/help_option.h"
55 #include "io/dns-resolver.h"
57 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
58 #define VNC_REFRESH_INTERVAL_INC 50
59 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
60 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
61 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
63 #include "vnc_keysym.h"
64 #include "crypto/cipher.h"
66 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
67 QTAILQ_HEAD_INITIALIZER(vnc_displays);
69 static int vnc_cursor_define(VncState *vs);
70 static void vnc_update_throttle_offset(VncState *vs);
72 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
75 static const char *mn[] = {
77 [VNC_SHARE_MODE_CONNECTING] = "connecting",
78 [VNC_SHARE_MODE_SHARED] = "shared",
79 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
80 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
82 fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
83 vs->ioc, mn[vs->share_mode], mn[mode]);
86 switch (vs->share_mode) {
87 case VNC_SHARE_MODE_CONNECTING:
88 vs->vd->num_connecting--;
90 case VNC_SHARE_MODE_SHARED:
93 case VNC_SHARE_MODE_EXCLUSIVE:
94 vs->vd->num_exclusive--;
100 vs->share_mode = mode;
102 switch (vs->share_mode) {
103 case VNC_SHARE_MODE_CONNECTING:
104 vs->vd->num_connecting++;
106 case VNC_SHARE_MODE_SHARED:
107 vs->vd->num_shared++;
109 case VNC_SHARE_MODE_EXCLUSIVE:
110 vs->vd->num_exclusive++;
118 static void vnc_init_basic_info(SocketAddress *addr,
122 switch (addr->type) {
123 case SOCKET_ADDRESS_TYPE_INET:
124 info->host = g_strdup(addr->u.inet.host);
125 info->service = g_strdup(addr->u.inet.port);
126 if (addr->u.inet.ipv6) {
127 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
129 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
133 case SOCKET_ADDRESS_TYPE_UNIX:
134 info->host = g_strdup("");
135 info->service = g_strdup(addr->u.q_unix.path);
136 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
139 case SOCKET_ADDRESS_TYPE_VSOCK:
140 case SOCKET_ADDRESS_TYPE_FD:
141 error_setg(errp, "Unsupported socket address type %s",
142 SocketAddressType_str(addr->type));
151 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
155 SocketAddress *addr = NULL;
158 error_setg(errp, "No listener socket available");
162 addr = qio_channel_socket_get_local_address(ioc, errp);
167 vnc_init_basic_info(addr, info, errp);
168 qapi_free_SocketAddress(addr);
171 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
175 SocketAddress *addr = NULL;
177 addr = qio_channel_socket_get_remote_address(ioc, errp);
182 vnc_init_basic_info(addr, info, errp);
183 qapi_free_SocketAddress(addr);
186 static const char *vnc_auth_name(VncDisplay *vd) {
188 case VNC_AUTH_INVALID:
204 case VNC_AUTH_VENCRYPT:
205 switch (vd->subauth) {
206 case VNC_AUTH_VENCRYPT_PLAIN:
207 return "vencrypt+plain";
208 case VNC_AUTH_VENCRYPT_TLSNONE:
209 return "vencrypt+tls+none";
210 case VNC_AUTH_VENCRYPT_TLSVNC:
211 return "vencrypt+tls+vnc";
212 case VNC_AUTH_VENCRYPT_TLSPLAIN:
213 return "vencrypt+tls+plain";
214 case VNC_AUTH_VENCRYPT_X509NONE:
215 return "vencrypt+x509+none";
216 case VNC_AUTH_VENCRYPT_X509VNC:
217 return "vencrypt+x509+vnc";
218 case VNC_AUTH_VENCRYPT_X509PLAIN:
219 return "vencrypt+x509+plain";
220 case VNC_AUTH_VENCRYPT_TLSSASL:
221 return "vencrypt+tls+sasl";
222 case VNC_AUTH_VENCRYPT_X509SASL:
223 return "vencrypt+x509+sasl";
233 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
238 if (!vd->listener || !vd->listener->nsioc) {
242 info = g_malloc0(sizeof(*info));
243 vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
244 qapi_VncServerInfo_base(info), &err);
245 info->has_auth = true;
246 info->auth = g_strdup(vnc_auth_name(vd));
248 qapi_free_VncServerInfo(info);
255 static void vnc_client_cache_auth(VncState *client)
262 client->info->x509_dname =
263 qcrypto_tls_session_get_peer_name(client->tls);
264 client->info->has_x509_dname =
265 client->info->x509_dname != NULL;
267 #ifdef CONFIG_VNC_SASL
268 if (client->sasl.conn &&
269 client->sasl.username) {
270 client->info->has_sasl_username = true;
271 client->info->sasl_username = g_strdup(client->sasl.username);
276 static void vnc_client_cache_addr(VncState *client)
280 client->info = g_malloc0(sizeof(*client->info));
281 vnc_init_basic_info_from_remote_addr(client->sioc,
282 qapi_VncClientInfo_base(client->info),
284 client->info->websocket = client->websocket;
286 qapi_free_VncClientInfo(client->info);
292 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
300 si = vnc_server_info_get(vs->vd);
306 case QAPI_EVENT_VNC_CONNECTED:
307 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
309 case QAPI_EVENT_VNC_INITIALIZED:
310 qapi_event_send_vnc_initialized(si, vs->info);
312 case QAPI_EVENT_VNC_DISCONNECTED:
313 qapi_event_send_vnc_disconnected(si, vs->info);
319 qapi_free_VncServerInfo(si);
322 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
327 info = g_malloc0(sizeof(*info));
329 vnc_init_basic_info_from_remote_addr(client->sioc,
330 qapi_VncClientInfo_base(info),
334 qapi_free_VncClientInfo(info);
338 info->websocket = client->websocket;
341 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
342 info->has_x509_dname = info->x509_dname != NULL;
344 #ifdef CONFIG_VNC_SASL
345 if (client->sasl.conn && client->sasl.username) {
346 info->has_sasl_username = true;
347 info->sasl_username = g_strdup(client->sasl.username);
354 static VncDisplay *vnc_display_find(const char *id)
359 return QTAILQ_FIRST(&vnc_displays);
361 QTAILQ_FOREACH(vd, &vnc_displays, next) {
362 if (strcmp(id, vd->id) == 0) {
369 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
371 VncClientInfoList *prev = NULL;
374 QTAILQ_FOREACH(client, &vd->clients, next) {
375 QAPI_LIST_PREPEND(prev, qmp_query_vnc_client(client));
380 VncInfo *qmp_query_vnc(Error **errp)
382 VncInfo *info = g_malloc0(sizeof(*info));
383 VncDisplay *vd = vnc_display_find(NULL);
384 SocketAddress *addr = NULL;
386 if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
387 info->enabled = false;
389 info->enabled = true;
391 /* for compatibility with the original command */
392 info->has_clients = true;
393 info->clients = qmp_query_client_list(vd);
395 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
401 switch (addr->type) {
402 case SOCKET_ADDRESS_TYPE_INET:
403 info->host = g_strdup(addr->u.inet.host);
404 info->service = g_strdup(addr->u.inet.port);
405 if (addr->u.inet.ipv6) {
406 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
408 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
412 case SOCKET_ADDRESS_TYPE_UNIX:
413 info->host = g_strdup("");
414 info->service = g_strdup(addr->u.q_unix.path);
415 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
418 case SOCKET_ADDRESS_TYPE_VSOCK:
419 case SOCKET_ADDRESS_TYPE_FD:
420 error_setg(errp, "Unsupported socket address type %s",
421 SocketAddressType_str(addr->type));
427 info->has_host = true;
428 info->has_service = true;
429 info->has_family = true;
431 info->has_auth = true;
432 info->auth = g_strdup(vnc_auth_name(vd));
435 qapi_free_SocketAddress(addr);
439 qapi_free_SocketAddress(addr);
440 qapi_free_VncInfo(info);
445 static void qmp_query_auth(int auth, int subauth,
446 VncPrimaryAuth *qmp_auth,
447 VncVencryptSubAuth *qmp_vencrypt,
448 bool *qmp_has_vencrypt);
450 static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
454 VncServerInfo2List *prev)
456 VncServerInfo2 *info;
460 addr = qio_channel_socket_get_local_address(ioc, NULL);
465 info = g_new0(VncServerInfo2, 1);
466 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
467 qapi_free_SocketAddress(addr);
469 qapi_free_VncServerInfo2(info);
473 info->websocket = websocket;
475 qmp_query_auth(auth, subauth, &info->auth,
476 &info->vencrypt, &info->has_vencrypt);
478 QAPI_LIST_PREPEND(prev, info);
482 static void qmp_query_auth(int auth, int subauth,
483 VncPrimaryAuth *qmp_auth,
484 VncVencryptSubAuth *qmp_vencrypt,
485 bool *qmp_has_vencrypt)
489 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
492 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
495 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
498 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
501 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
504 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
506 case VNC_AUTH_VENCRYPT:
507 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
508 *qmp_has_vencrypt = true;
510 case VNC_AUTH_VENCRYPT_PLAIN:
511 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
513 case VNC_AUTH_VENCRYPT_TLSNONE:
514 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
516 case VNC_AUTH_VENCRYPT_TLSVNC:
517 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
519 case VNC_AUTH_VENCRYPT_TLSPLAIN:
520 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
522 case VNC_AUTH_VENCRYPT_X509NONE:
523 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
525 case VNC_AUTH_VENCRYPT_X509VNC:
526 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
528 case VNC_AUTH_VENCRYPT_X509PLAIN:
529 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
531 case VNC_AUTH_VENCRYPT_TLSSASL:
532 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
534 case VNC_AUTH_VENCRYPT_X509SASL:
535 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
538 *qmp_has_vencrypt = false;
543 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
547 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
552 VncInfo2List *qmp_query_vnc_servers(Error **errp)
554 VncInfo2List *prev = NULL;
560 QTAILQ_FOREACH(vd, &vnc_displays, next) {
561 info = g_new0(VncInfo2, 1);
562 info->id = g_strdup(vd->id);
563 info->clients = qmp_query_client_list(vd);
564 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
565 &info->vencrypt, &info->has_vencrypt);
567 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
568 "device", &error_abort));
569 info->has_display = true;
570 info->display = g_strdup(dev->id);
572 for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
573 info->server = qmp_query_server_entry(
574 vd->listener->sioc[i], false, vd->auth, vd->subauth,
577 for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
578 info->server = qmp_query_server_entry(
579 vd->wslistener->sioc[i], true, vd->ws_auth,
580 vd->ws_subauth, info->server);
583 QAPI_LIST_PREPEND(prev, info);
589 1) Get the queue working for IO.
590 2) there is some weirdness when using the -S option (the screen is grey
591 and not totally invalidated
592 3) resolutions > 1024
595 static int vnc_update_client(VncState *vs, int has_dirty);
596 static void vnc_disconnect_start(VncState *vs);
598 static void vnc_colordepth(VncState *vs);
599 static void framebuffer_update_request(VncState *vs, int incremental,
600 int x_position, int y_position,
602 static void vnc_refresh(DisplayChangeListener *dcl);
603 static int vnc_refresh_server_surface(VncDisplay *vd);
605 static int vnc_width(VncDisplay *vd)
607 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
608 VNC_DIRTY_PIXELS_PER_BIT));
611 static int vnc_true_width(VncDisplay *vd)
613 return MIN(VNC_MAX_WIDTH, surface_width(vd->ds));
616 static int vnc_height(VncDisplay *vd)
618 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
621 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
622 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
624 int x, int y, int w, int h)
626 int width = vnc_width(vd);
627 int height = vnc_height(vd);
629 /* this is needed this to ensure we updated all affected
630 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
631 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
632 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
636 w = MIN(x + w, width) - x;
637 h = MIN(y + h, height);
640 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
641 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
645 static void vnc_dpy_update(DisplayChangeListener *dcl,
646 int x, int y, int w, int h)
648 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
649 struct VncSurface *s = &vd->guest;
651 vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
654 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
657 vnc_write_u16(vs, x);
658 vnc_write_u16(vs, y);
659 vnc_write_u16(vs, w);
660 vnc_write_u16(vs, h);
662 vnc_write_s32(vs, encoding);
665 static void vnc_desktop_resize_ext(VncState *vs, int reject_reason)
667 trace_vnc_msg_server_ext_desktop_resize(
668 vs, vs->ioc, vs->client_width, vs->client_height, reject_reason);
671 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
673 vnc_write_u16(vs, 1); /* number of rects */
674 vnc_framebuffer_update(vs,
675 reject_reason ? 1 : 0,
677 vs->client_width, vs->client_height,
678 VNC_ENCODING_DESKTOP_RESIZE_EXT);
679 vnc_write_u8(vs, 1); /* number of screens */
680 vnc_write_u8(vs, 0); /* padding */
681 vnc_write_u8(vs, 0); /* padding */
682 vnc_write_u8(vs, 0); /* padding */
683 vnc_write_u32(vs, 0); /* screen id */
684 vnc_write_u16(vs, 0); /* screen x-pos */
685 vnc_write_u16(vs, 0); /* screen y-pos */
686 vnc_write_u16(vs, vs->client_width);
687 vnc_write_u16(vs, vs->client_height);
688 vnc_write_u32(vs, 0); /* screen flags */
689 vnc_unlock_output(vs);
693 static void vnc_desktop_resize(VncState *vs)
695 if (vs->ioc == NULL || (!vnc_has_feature(vs, VNC_FEATURE_RESIZE) &&
696 !vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT))) {
699 if (vs->client_width == vs->vd->true_width &&
700 vs->client_height == pixman_image_get_height(vs->vd->server)) {
704 assert(vs->vd->true_width < 65536 &&
705 vs->vd->true_width >= 0);
706 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
707 pixman_image_get_height(vs->vd->server) >= 0);
708 vs->client_width = vs->vd->true_width;
709 vs->client_height = pixman_image_get_height(vs->vd->server);
711 if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
712 vnc_desktop_resize_ext(vs, 0);
716 trace_vnc_msg_server_desktop_resize(
717 vs, vs->ioc, vs->client_width, vs->client_height);
720 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
722 vnc_write_u16(vs, 1); /* number of rects */
723 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
724 VNC_ENCODING_DESKTOPRESIZE);
725 vnc_unlock_output(vs);
729 static void vnc_abort_display_jobs(VncDisplay *vd)
733 QTAILQ_FOREACH(vs, &vd->clients, next) {
736 vnc_unlock_output(vs);
738 QTAILQ_FOREACH(vs, &vd->clients, next) {
741 QTAILQ_FOREACH(vs, &vd->clients, next) {
743 if (vs->update == VNC_STATE_UPDATE_NONE &&
744 vs->job_update != VNC_STATE_UPDATE_NONE) {
745 /* job aborted before completion */
746 vs->update = vs->job_update;
747 vs->job_update = VNC_STATE_UPDATE_NONE;
750 vnc_unlock_output(vs);
754 int vnc_server_fb_stride(VncDisplay *vd)
756 return pixman_image_get_stride(vd->server);
759 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
763 ptr = (uint8_t *)pixman_image_get_data(vd->server);
764 ptr += y * vnc_server_fb_stride(vd);
765 ptr += x * VNC_SERVER_FB_BYTES;
769 static void vnc_update_server_surface(VncDisplay *vd)
773 qemu_pixman_image_unref(vd->server);
776 if (QTAILQ_EMPTY(&vd->clients)) {
780 width = vnc_width(vd);
781 height = vnc_height(vd);
782 vd->true_width = vnc_true_width(vd);
783 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
787 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
788 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
792 static bool vnc_check_pageflip(DisplaySurface *s1,
795 return (s1 != NULL &&
797 surface_width(s1) == surface_width(s2) &&
798 surface_height(s1) == surface_height(s2) &&
799 surface_format(s1) == surface_format(s2));
803 static void vnc_dpy_switch(DisplayChangeListener *dcl,
804 DisplaySurface *surface)
806 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
807 bool pageflip = vnc_check_pageflip(vd->ds, surface);
810 vnc_abort_display_jobs(vd);
814 qemu_pixman_image_unref(vd->guest.fb);
815 vd->guest.fb = pixman_image_ref(surface->image);
816 vd->guest.format = surface->format;
820 trace_vnc_server_dpy_pageflip(vd,
821 surface_width(surface),
822 surface_height(surface),
823 surface_format(surface));
824 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
825 surface_width(surface),
826 surface_height(surface));
830 trace_vnc_server_dpy_recreate(vd,
831 surface_width(surface),
832 surface_height(surface),
833 surface_format(surface));
835 vnc_update_server_surface(vd);
837 QTAILQ_FOREACH(vs, &vd->clients, next) {
839 vnc_desktop_resize(vs);
840 vnc_cursor_define(vs);
841 memset(vs->dirty, 0x00, sizeof(vs->dirty));
842 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
845 vnc_update_throttle_offset(vs);
850 static void vnc_write_pixels_copy(VncState *vs,
851 void *pixels, int size)
853 vnc_write(vs, pixels, size);
856 /* slowest but generic code. */
857 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
861 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
862 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
863 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
864 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
866 # error need some bits here if you change VNC_SERVER_FB_FORMAT
868 v = (r << vs->client_pf.rshift) |
869 (g << vs->client_pf.gshift) |
870 (b << vs->client_pf.bshift);
871 switch (vs->client_pf.bytes_per_pixel) {
901 static void vnc_write_pixels_generic(VncState *vs,
902 void *pixels1, int size)
906 if (VNC_SERVER_FB_BYTES == 4) {
907 uint32_t *pixels = pixels1;
910 for (i = 0; i < n; i++) {
911 vnc_convert_pixel(vs, buf, pixels[i]);
912 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
917 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
921 VncDisplay *vd = vs->vd;
923 row = vnc_server_fb_ptr(vd, x, y);
924 for (i = 0; i < h; i++) {
925 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
926 row += vnc_server_fb_stride(vd);
931 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
935 switch(vs->vnc_encoding) {
936 case VNC_ENCODING_ZLIB:
937 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
939 case VNC_ENCODING_HEXTILE:
940 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
941 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
943 case VNC_ENCODING_TIGHT:
944 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
946 case VNC_ENCODING_TIGHT_PNG:
947 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
949 case VNC_ENCODING_ZRLE:
950 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
952 case VNC_ENCODING_ZYWRLE:
953 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
956 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
957 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
963 static void vnc_mouse_set(DisplayChangeListener *dcl,
964 int x, int y, int visible)
966 /* can we ask the client(s) to move the pointer ??? */
969 static int vnc_cursor_define(VncState *vs)
971 QEMUCursor *c = vs->vd->cursor;
974 if (!vs->vd->cursor) {
978 if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
980 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
981 vnc_write_u8(vs, 0); /* padding */
982 vnc_write_u16(vs, 1); /* # of rects */
983 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
984 VNC_ENCODING_ALPHA_CURSOR);
985 vnc_write_s32(vs, VNC_ENCODING_RAW);
986 vnc_write(vs, c->data, c->width * c->height * 4);
987 vnc_unlock_output(vs);
990 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
992 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
993 vnc_write_u8(vs, 0); /* padding */
994 vnc_write_u16(vs, 1); /* # of rects */
995 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
996 VNC_ENCODING_RICH_CURSOR);
997 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
998 vnc_write_pixels_generic(vs, c->data, isize);
999 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
1000 vnc_unlock_output(vs);
1006 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
1009 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
1012 cursor_put(vd->cursor);
1013 g_free(vd->cursor_mask);
1016 cursor_get(vd->cursor);
1017 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
1018 vd->cursor_mask = g_malloc0(vd->cursor_msize);
1019 cursor_get_mono_mask(c, 0, vd->cursor_mask);
1021 QTAILQ_FOREACH(vs, &vd->clients, next) {
1022 vnc_cursor_define(vs);
1026 static int find_and_clear_dirty_height(VncState *vs,
1027 int y, int last_x, int x, int height)
1031 for (h = 1; h < (height - y); h++) {
1032 if (!test_bit(last_x, vs->dirty[y + h])) {
1035 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1042 * Figure out how much pending data we should allow in the output
1043 * buffer before we throttle incremental display updates, and/or
1044 * drop audio samples.
1046 * We allow for equiv of 1 full display's worth of FB updates,
1047 * and 1 second of audio samples. If audio backlog was larger
1048 * than that the client would already suffering awful audio
1049 * glitches, so dropping samples is no worse really).
1051 static void vnc_update_throttle_offset(VncState *vs)
1054 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1056 if (vs->audio_cap) {
1058 switch (vs->as.fmt) {
1060 case AUDIO_FORMAT_U8:
1061 case AUDIO_FORMAT_S8:
1064 case AUDIO_FORMAT_U16:
1065 case AUDIO_FORMAT_S16:
1068 case AUDIO_FORMAT_U32:
1069 case AUDIO_FORMAT_S32:
1073 offset += vs->as.freq * bps * vs->as.nchannels;
1076 /* Put a floor of 1MB on offset, so that if we have a large pending
1077 * buffer and the display is resized to a small size & back again
1078 * we don't suddenly apply a tiny send limit
1080 offset = MAX(offset, 1024 * 1024);
1082 if (vs->throttle_output_offset != offset) {
1083 trace_vnc_client_throttle_threshold(
1084 vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1085 vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1088 vs->throttle_output_offset = offset;
1091 static bool vnc_should_update(VncState *vs)
1093 switch (vs->update) {
1094 case VNC_STATE_UPDATE_NONE:
1096 case VNC_STATE_UPDATE_INCREMENTAL:
1097 /* Only allow incremental updates if the pending send queue
1098 * is less than the permitted threshold, and the job worker
1099 * is completely idle.
1101 if (vs->output.offset < vs->throttle_output_offset &&
1102 vs->job_update == VNC_STATE_UPDATE_NONE) {
1105 trace_vnc_client_throttle_incremental(
1106 vs, vs->ioc, vs->job_update, vs->output.offset);
1108 case VNC_STATE_UPDATE_FORCE:
1109 /* Only allow forced updates if the pending send queue
1110 * does not contain a previous forced update, and the
1111 * job worker is completely idle.
1113 * Note this means we'll queue a forced update, even if
1114 * the output buffer size is otherwise over the throttle
1117 if (vs->force_update_offset == 0 &&
1118 vs->job_update == VNC_STATE_UPDATE_NONE) {
1121 trace_vnc_client_throttle_forced(
1122 vs, vs->ioc, vs->job_update, vs->force_update_offset);
1128 static int vnc_update_client(VncState *vs, int has_dirty)
1130 VncDisplay *vd = vs->vd;
1136 if (vs->disconnecting) {
1137 vnc_disconnect_finish(vs);
1141 vs->has_dirty += has_dirty;
1142 if (!vnc_should_update(vs)) {
1146 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1151 * Send screen updates to the vnc client using the server
1152 * surface and server dirty map. guest surface updates
1153 * happening in parallel don't disturb us, the next pass will
1154 * send them to the client.
1156 job = vnc_job_new(vs);
1158 height = pixman_image_get_height(vd->server);
1159 width = pixman_image_get_width(vd->server);
1165 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1166 height * VNC_DIRTY_BPL(vs),
1167 y * VNC_DIRTY_BPL(vs));
1168 if (offset == height * VNC_DIRTY_BPL(vs)) {
1169 /* no more dirty bits */
1172 y = offset / VNC_DIRTY_BPL(vs);
1173 x = offset % VNC_DIRTY_BPL(vs);
1174 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1175 VNC_DIRTY_BPL(vs), x);
1176 bitmap_clear(vs->dirty[y], x, x2 - x);
1177 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1178 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1180 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1181 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1183 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1191 vs->job_update = vs->update;
1192 vs->update = VNC_STATE_UPDATE_NONE;
1199 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1201 VncState *vs = opaque;
1203 assert(vs->magic == VNC_MAGIC);
1205 case AUD_CNOTIFY_DISABLE:
1206 trace_vnc_msg_server_audio_end(vs, vs->ioc);
1207 vnc_lock_output(vs);
1208 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1209 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1210 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1211 vnc_unlock_output(vs);
1215 case AUD_CNOTIFY_ENABLE:
1216 trace_vnc_msg_server_audio_begin(vs, vs->ioc);
1217 vnc_lock_output(vs);
1218 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1219 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1220 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1221 vnc_unlock_output(vs);
1227 static void audio_capture_destroy(void *opaque)
1231 static void audio_capture(void *opaque, const void *buf, int size)
1233 VncState *vs = opaque;
1235 assert(vs->magic == VNC_MAGIC);
1236 trace_vnc_msg_server_audio_data(vs, vs->ioc, buf, size);
1237 vnc_lock_output(vs);
1238 if (vs->output.offset < vs->throttle_output_offset) {
1239 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1240 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1241 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1242 vnc_write_u32(vs, size);
1243 vnc_write(vs, buf, size);
1245 trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1247 vnc_unlock_output(vs);
1251 static void audio_add(VncState *vs)
1253 struct audio_capture_ops ops;
1255 if (vs->audio_cap) {
1256 error_report("audio already running");
1260 ops.notify = audio_capture_notify;
1261 ops.destroy = audio_capture_destroy;
1262 ops.capture = audio_capture;
1264 vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
1265 if (!vs->audio_cap) {
1266 error_report("Failed to add audio capture");
1270 static void audio_del(VncState *vs)
1272 if (vs->audio_cap) {
1273 AUD_del_capture(vs->audio_cap, vs);
1274 vs->audio_cap = NULL;
1278 static void vnc_disconnect_start(VncState *vs)
1280 if (vs->disconnecting) {
1283 trace_vnc_client_disconnect_start(vs, vs->ioc);
1284 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1286 g_source_remove(vs->ioc_tag);
1289 qio_channel_close(vs->ioc, NULL);
1290 vs->disconnecting = TRUE;
1293 void vnc_disconnect_finish(VncState *vs)
1297 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1299 vnc_jobs_join(vs); /* Wait encoding jobs */
1301 vnc_lock_output(vs);
1302 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1304 buffer_free(&vs->input);
1305 buffer_free(&vs->output);
1307 qapi_free_VncClientInfo(vs->info);
1310 vnc_tight_clear(vs);
1313 #ifdef CONFIG_VNC_SASL
1314 vnc_sasl_client_cleanup(vs);
1315 #endif /* CONFIG_VNC_SASL */
1317 qkbd_state_lift_all_keys(vs->vd->kbd);
1319 if (vs->mouse_mode_notifier.notify != NULL) {
1320 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1322 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1323 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1324 /* last client gone */
1325 vnc_update_server_surface(vs->vd);
1328 vnc_unlock_output(vs);
1330 qemu_mutex_destroy(&vs->output_mutex);
1331 if (vs->bh != NULL) {
1332 qemu_bh_delete(vs->bh);
1334 buffer_free(&vs->jobs_buffer);
1336 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1337 g_free(vs->lossy_rect[i]);
1339 g_free(vs->lossy_rect);
1341 object_unref(OBJECT(vs->ioc));
1343 object_unref(OBJECT(vs->sioc));
1351 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
1355 trace_vnc_client_eof(vs, vs->ioc);
1356 vnc_disconnect_start(vs);
1357 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1358 trace_vnc_client_io_error(vs, vs->ioc,
1359 err ? error_get_pretty(err) : "Unknown");
1360 vnc_disconnect_start(vs);
1370 void vnc_client_error(VncState *vs)
1372 VNC_DEBUG("Closing down client sock: protocol error\n");
1373 vnc_disconnect_start(vs);
1378 * Called to write a chunk of data to the client socket. The data may
1379 * be the raw data, or may have already been encoded by SASL.
1380 * The data will be written either straight onto the socket, or
1381 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1383 * NB, it is theoretically possible to have 2 layers of encryption,
1384 * both SASL, and this TLS layer. It is highly unlikely in practice
1385 * though, since SASL encryption will typically be a no-op if TLS
1388 * Returns the number of bytes written, which may be less than
1389 * the requested 'datalen' if the socket would block. Returns
1390 * 0 on I/O error, and disconnects the client socket.
1392 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1396 ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
1397 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1398 return vnc_client_io_error(vs, ret, err);
1403 * Called to write buffered data to the client socket, when not
1404 * using any SASL SSF encryption layers. Will write as much data
1405 * as possible without blocking. If all buffered data is written,
1406 * will switch the FD poll() handler back to read monitoring.
1408 * Returns the number of bytes written, which may be less than
1409 * the buffered output data if the socket would block. Returns
1410 * 0 on I/O error, and disconnects the client socket.
1412 static size_t vnc_client_write_plain(VncState *vs)
1417 #ifdef CONFIG_VNC_SASL
1418 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1419 vs->output.buffer, vs->output.capacity, vs->output.offset,
1420 vs->sasl.waitWriteSSF);
1422 if (vs->sasl.conn &&
1424 vs->sasl.waitWriteSSF) {
1425 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1427 vs->sasl.waitWriteSSF -= ret;
1429 #endif /* CONFIG_VNC_SASL */
1430 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1434 if (ret >= vs->force_update_offset) {
1435 if (vs->force_update_offset != 0) {
1436 trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1438 vs->force_update_offset = 0;
1440 vs->force_update_offset -= ret;
1442 offset = vs->output.offset;
1443 buffer_advance(&vs->output, ret);
1444 if (offset >= vs->throttle_output_offset &&
1445 vs->output.offset < vs->throttle_output_offset) {
1446 trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1449 if (vs->output.offset == 0) {
1451 g_source_remove(vs->ioc_tag);
1453 vs->ioc_tag = qio_channel_add_watch(
1454 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1455 vnc_client_io, vs, NULL);
1463 * First function called whenever there is data to be written to
1464 * the client socket. Will delegate actual work according to whether
1465 * SASL SSF layers are enabled (thus requiring encryption calls)
1467 static void vnc_client_write_locked(VncState *vs)
1469 #ifdef CONFIG_VNC_SASL
1470 if (vs->sasl.conn &&
1472 !vs->sasl.waitWriteSSF) {
1473 vnc_client_write_sasl(vs);
1475 #endif /* CONFIG_VNC_SASL */
1477 vnc_client_write_plain(vs);
1481 static void vnc_client_write(VncState *vs)
1483 assert(vs->magic == VNC_MAGIC);
1484 vnc_lock_output(vs);
1485 if (vs->output.offset) {
1486 vnc_client_write_locked(vs);
1487 } else if (vs->ioc != NULL) {
1489 g_source_remove(vs->ioc_tag);
1491 vs->ioc_tag = qio_channel_add_watch(
1492 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1493 vnc_client_io, vs, NULL);
1495 vnc_unlock_output(vs);
1498 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1500 vs->read_handler = func;
1501 vs->read_handler_expect = expecting;
1506 * Called to read a chunk of data from the client socket. The data may
1507 * be the raw data, or may need to be further decoded by SASL.
1508 * The data will be read either straight from to the socket, or
1509 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1511 * NB, it is theoretically possible to have 2 layers of encryption,
1512 * both SASL, and this TLS layer. It is highly unlikely in practice
1513 * though, since SASL encryption will typically be a no-op if TLS
1516 * Returns the number of bytes read, which may be less than
1517 * the requested 'datalen' if the socket would block. Returns
1518 * 0 on I/O error or EOF, and disconnects the client socket.
1520 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1524 ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
1525 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1526 return vnc_client_io_error(vs, ret, err);
1531 * Called to read data from the client socket to the input buffer,
1532 * when not using any SASL SSF encryption layers. Will read as much
1533 * data as possible without blocking.
1535 * Returns the number of bytes read, which may be less than
1536 * the requested 'datalen' if the socket would block. Returns
1537 * 0 on I/O error or EOF, and disconnects the client socket.
1539 static size_t vnc_client_read_plain(VncState *vs)
1542 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1543 vs->input.buffer, vs->input.capacity, vs->input.offset);
1544 buffer_reserve(&vs->input, 4096);
1545 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1548 vs->input.offset += ret;
1552 static void vnc_jobs_bh(void *opaque)
1554 VncState *vs = opaque;
1556 assert(vs->magic == VNC_MAGIC);
1557 vnc_jobs_consume_buffer(vs);
1561 * First function called whenever there is more data to be read from
1562 * the client socket. Will delegate actual work according to whether
1563 * SASL SSF layers are enabled (thus requiring decryption calls)
1564 * Returns 0 on success, -1 if client disconnected
1566 static int vnc_client_read(VncState *vs)
1570 #ifdef CONFIG_VNC_SASL
1571 if (vs->sasl.conn && vs->sasl.runSSF)
1572 ret = vnc_client_read_sasl(vs);
1574 #endif /* CONFIG_VNC_SASL */
1575 ret = vnc_client_read_plain(vs);
1577 if (vs->disconnecting) {
1578 vnc_disconnect_finish(vs);
1584 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1585 size_t len = vs->read_handler_expect;
1588 ret = vs->read_handler(vs, vs->input.buffer, len);
1589 if (vs->disconnecting) {
1590 vnc_disconnect_finish(vs);
1595 buffer_advance(&vs->input, len);
1597 vs->read_handler_expect = ret;
1603 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1604 GIOCondition condition, void *opaque)
1606 VncState *vs = opaque;
1608 assert(vs->magic == VNC_MAGIC);
1610 if (condition & (G_IO_HUP | G_IO_ERR)) {
1611 vnc_disconnect_start(vs);
1615 if (condition & G_IO_IN) {
1616 if (vnc_client_read(vs) < 0) {
1617 /* vs is free()ed here */
1621 if (condition & G_IO_OUT) {
1622 vnc_client_write(vs);
1625 if (vs->disconnecting) {
1626 if (vs->ioc_tag != 0) {
1627 g_source_remove(vs->ioc_tag);
1636 * Scale factor to apply to vs->throttle_output_offset when checking for
1637 * hard limit. Worst case normal usage could be x2, if we have a complete
1638 * incremental update and complete forced update in the output buffer.
1639 * So x3 should be good enough, but we pick x5 to be conservative and thus
1640 * (hopefully) never trigger incorrectly.
1642 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1644 void vnc_write(VncState *vs, const void *data, size_t len)
1646 assert(vs->magic == VNC_MAGIC);
1647 if (vs->disconnecting) {
1650 /* Protection against malicious client/guest to prevent our output
1651 * buffer growing without bound if client stops reading data. This
1652 * should rarely trigger, because we have earlier throttling code
1653 * which stops issuing framebuffer updates and drops audio data
1654 * if the throttle_output_offset value is exceeded. So we only reach
1655 * this higher level if a huge number of pseudo-encodings get
1656 * triggered while data can't be sent on the socket.
1658 * NB throttle_output_offset can be zero during early protocol
1659 * handshake, or from the job thread's VncState clone
1661 if (vs->throttle_output_offset != 0 &&
1662 (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1663 vs->throttle_output_offset) {
1664 trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1665 vs->throttle_output_offset);
1666 vnc_disconnect_start(vs);
1669 buffer_reserve(&vs->output, len);
1671 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1673 g_source_remove(vs->ioc_tag);
1675 vs->ioc_tag = qio_channel_add_watch(
1676 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
1677 vnc_client_io, vs, NULL);
1680 buffer_append(&vs->output, data, len);
1683 void vnc_write_s32(VncState *vs, int32_t value)
1685 vnc_write_u32(vs, *(uint32_t *)&value);
1688 void vnc_write_u32(VncState *vs, uint32_t value)
1692 buf[0] = (value >> 24) & 0xFF;
1693 buf[1] = (value >> 16) & 0xFF;
1694 buf[2] = (value >> 8) & 0xFF;
1695 buf[3] = value & 0xFF;
1697 vnc_write(vs, buf, 4);
1700 void vnc_write_u16(VncState *vs, uint16_t value)
1704 buf[0] = (value >> 8) & 0xFF;
1705 buf[1] = value & 0xFF;
1707 vnc_write(vs, buf, 2);
1710 void vnc_write_u8(VncState *vs, uint8_t value)
1712 vnc_write(vs, (char *)&value, 1);
1715 void vnc_flush(VncState *vs)
1717 vnc_lock_output(vs);
1718 if (vs->ioc != NULL && vs->output.offset) {
1719 vnc_client_write_locked(vs);
1721 if (vs->disconnecting) {
1722 if (vs->ioc_tag != 0) {
1723 g_source_remove(vs->ioc_tag);
1727 vnc_unlock_output(vs);
1730 static uint8_t read_u8(uint8_t *data, size_t offset)
1732 return data[offset];
1735 static uint16_t read_u16(uint8_t *data, size_t offset)
1737 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1740 static int32_t read_s32(uint8_t *data, size_t offset)
1742 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1743 (data[offset + 2] << 8) | data[offset + 3]);
1746 uint32_t read_u32(uint8_t *data, size_t offset)
1748 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1749 (data[offset + 2] << 8) | data[offset + 3]);
1752 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1756 static void check_pointer_type_change(Notifier *notifier, void *data)
1758 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1759 int absolute = qemu_input_is_absolute();
1761 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1762 vnc_lock_output(vs);
1763 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1764 vnc_write_u8(vs, 0);
1765 vnc_write_u16(vs, 1);
1766 vnc_framebuffer_update(vs, absolute, 0,
1767 pixman_image_get_width(vs->vd->server),
1768 pixman_image_get_height(vs->vd->server),
1769 VNC_ENCODING_POINTER_TYPE_CHANGE);
1770 vnc_unlock_output(vs);
1773 vs->absolute = absolute;
1776 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1778 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1779 [INPUT_BUTTON_LEFT] = 0x01,
1780 [INPUT_BUTTON_MIDDLE] = 0x02,
1781 [INPUT_BUTTON_RIGHT] = 0x04,
1782 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1783 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1785 QemuConsole *con = vs->vd->dcl.con;
1786 int width = pixman_image_get_width(vs->vd->server);
1787 int height = pixman_image_get_height(vs->vd->server);
1789 if (vs->last_bmask != button_mask) {
1790 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1791 vs->last_bmask = button_mask;
1795 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1796 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1797 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1798 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1799 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1801 if (vs->last_x != -1) {
1802 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1803 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1808 qemu_input_event_sync();
1811 static void press_key(VncState *vs, QKeyCode qcode)
1813 qkbd_state_key_event(vs->vd->kbd, qcode, true);
1814 qkbd_state_key_event(vs->vd->kbd, qcode, false);
1817 static void vnc_led_state_change(VncState *vs)
1819 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1823 vnc_lock_output(vs);
1824 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1825 vnc_write_u8(vs, 0);
1826 vnc_write_u16(vs, 1);
1827 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1828 vnc_write_u8(vs, vs->vd->ledstate);
1829 vnc_unlock_output(vs);
1833 static void kbd_leds(void *opaque, int ledstate)
1835 VncDisplay *vd = opaque;
1838 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1839 (ledstate & QEMU_NUM_LOCK_LED),
1840 (ledstate & QEMU_SCROLL_LOCK_LED));
1842 if (ledstate == vd->ledstate) {
1846 vd->ledstate = ledstate;
1848 QTAILQ_FOREACH(client, &vd->clients, next) {
1849 vnc_led_state_change(client);
1853 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1855 QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1857 /* QEMU console switch */
1859 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1860 if (vs->vd->dcl.con == NULL && down &&
1861 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1862 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1863 /* Reset the modifiers sent to the current console */
1864 qkbd_state_lift_all_keys(vs->vd->kbd);
1865 console_select(qcode - Q_KEY_CODE_1);
1872 /* Turn off the lock state sync logic if the client support the led
1875 if (down && vs->vd->lock_key_sync &&
1876 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1877 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1878 /* If the numlock state needs to change then simulate an additional
1879 keypress before sending this one. This will happen if the user
1880 toggles numlock away from the VNC window.
1882 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1883 if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1884 trace_vnc_key_sync_numlock(true);
1885 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1888 if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1889 trace_vnc_key_sync_numlock(false);
1890 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1895 if (down && vs->vd->lock_key_sync &&
1896 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1897 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1898 /* If the capslock state needs to change then simulate an additional
1899 keypress before sending this one. This will happen if the user
1900 toggles capslock away from the VNC window.
1902 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1903 bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1904 bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1906 if (uppercase == shift) {
1907 trace_vnc_key_sync_capslock(false);
1908 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1911 if (uppercase != shift) {
1912 trace_vnc_key_sync_capslock(true);
1913 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1918 qkbd_state_key_event(vs->vd->kbd, qcode, down);
1919 if (!qemu_console_is_graphic(NULL)) {
1920 bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1921 bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1922 /* QEMU console emulation */
1925 case 0x2a: /* Left Shift */
1926 case 0x36: /* Right Shift */
1927 case 0x1d: /* Left CTRL */
1928 case 0x9d: /* Right CTRL */
1929 case 0x38: /* Left ALT */
1930 case 0xb8: /* Right ALT */
1933 kbd_put_keysym(QEMU_KEY_UP);
1936 kbd_put_keysym(QEMU_KEY_DOWN);
1939 kbd_put_keysym(QEMU_KEY_LEFT);
1942 kbd_put_keysym(QEMU_KEY_RIGHT);
1945 kbd_put_keysym(QEMU_KEY_DELETE);
1948 kbd_put_keysym(QEMU_KEY_HOME);
1951 kbd_put_keysym(QEMU_KEY_END);
1954 kbd_put_keysym(QEMU_KEY_PAGEUP);
1957 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1961 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1964 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1967 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1970 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1973 kbd_put_keysym('5');
1976 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1979 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1982 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1985 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1988 kbd_put_keysym('0');
1991 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1995 kbd_put_keysym('/');
1998 kbd_put_keysym('*');
2001 kbd_put_keysym('-');
2004 kbd_put_keysym('+');
2007 kbd_put_keysym('\n');
2012 kbd_put_keysym(sym & 0x1f);
2014 kbd_put_keysym(sym);
2022 static const char *code2name(int keycode)
2024 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
2027 static void key_event(VncState *vs, int down, uint32_t sym)
2032 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
2033 lsym = lsym - 'A' + 'a';
2036 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
2037 vs->vd->kbd, down) & SCANCODE_KEYMASK;
2038 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
2039 do_key_event(vs, down, keycode, sym);
2042 static void ext_key_event(VncState *vs, int down,
2043 uint32_t sym, uint16_t keycode)
2045 /* if the user specifies a keyboard layout, always use it */
2046 if (keyboard_layout) {
2047 key_event(vs, down, sym);
2049 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2050 do_key_event(vs, down, keycode, sym);
2054 static void framebuffer_update_request(VncState *vs, int incremental,
2055 int x, int y, int w, int h)
2058 if (vs->update != VNC_STATE_UPDATE_FORCE) {
2059 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2062 vs->update = VNC_STATE_UPDATE_FORCE;
2063 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2064 if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
2065 vnc_desktop_resize_ext(vs, 0);
2070 static void send_ext_key_event_ack(VncState *vs)
2072 vnc_lock_output(vs);
2073 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2074 vnc_write_u8(vs, 0);
2075 vnc_write_u16(vs, 1);
2076 vnc_framebuffer_update(vs, 0, 0,
2077 pixman_image_get_width(vs->vd->server),
2078 pixman_image_get_height(vs->vd->server),
2079 VNC_ENCODING_EXT_KEY_EVENT);
2080 vnc_unlock_output(vs);
2084 static void send_ext_audio_ack(VncState *vs)
2086 vnc_lock_output(vs);
2087 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2088 vnc_write_u8(vs, 0);
2089 vnc_write_u16(vs, 1);
2090 vnc_framebuffer_update(vs, 0, 0,
2091 pixman_image_get_width(vs->vd->server),
2092 pixman_image_get_height(vs->vd->server),
2093 VNC_ENCODING_AUDIO);
2094 vnc_unlock_output(vs);
2098 static void send_xvp_message(VncState *vs, int code)
2100 vnc_lock_output(vs);
2101 vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
2102 vnc_write_u8(vs, 0); /* pad */
2103 vnc_write_u8(vs, 1); /* version */
2104 vnc_write_u8(vs, code);
2105 vnc_unlock_output(vs);
2109 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2112 unsigned int enc = 0;
2115 vs->vnc_encoding = 0;
2116 vs->tight->compression = 9;
2117 vs->tight->quality = -1; /* Lossless by default */
2121 * Start from the end because the encodings are sent in order of preference.
2122 * This way the preferred encoding (first encoding defined in the array)
2123 * will be set at the end of the loop.
2125 for (i = n_encodings - 1; i >= 0; i--) {
2128 case VNC_ENCODING_RAW:
2129 vs->vnc_encoding = enc;
2131 case VNC_ENCODING_HEXTILE:
2132 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2133 vs->vnc_encoding = enc;
2135 case VNC_ENCODING_TIGHT:
2136 vs->features |= VNC_FEATURE_TIGHT_MASK;
2137 vs->vnc_encoding = enc;
2139 #ifdef CONFIG_VNC_PNG
2140 case VNC_ENCODING_TIGHT_PNG:
2141 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2142 vs->vnc_encoding = enc;
2145 case VNC_ENCODING_ZLIB:
2147 * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2148 * So prioritize ZRLE, even if the client hints that it prefers
2151 if ((vs->features & VNC_FEATURE_ZRLE_MASK) == 0) {
2152 vs->features |= VNC_FEATURE_ZLIB_MASK;
2153 vs->vnc_encoding = enc;
2156 case VNC_ENCODING_ZRLE:
2157 vs->features |= VNC_FEATURE_ZRLE_MASK;
2158 vs->vnc_encoding = enc;
2160 case VNC_ENCODING_ZYWRLE:
2161 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2162 vs->vnc_encoding = enc;
2164 case VNC_ENCODING_DESKTOPRESIZE:
2165 vs->features |= VNC_FEATURE_RESIZE_MASK;
2167 case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2168 vs->features |= VNC_FEATURE_RESIZE_EXT_MASK;
2170 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2171 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2173 case VNC_ENCODING_RICH_CURSOR:
2174 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2176 case VNC_ENCODING_ALPHA_CURSOR:
2177 vs->features |= VNC_FEATURE_ALPHA_CURSOR_MASK;
2179 case VNC_ENCODING_EXT_KEY_EVENT:
2180 send_ext_key_event_ack(vs);
2182 case VNC_ENCODING_AUDIO:
2183 send_ext_audio_ack(vs);
2185 case VNC_ENCODING_WMVi:
2186 vs->features |= VNC_FEATURE_WMVI_MASK;
2188 case VNC_ENCODING_LED_STATE:
2189 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2191 case VNC_ENCODING_XVP:
2192 if (vs->vd->power_control) {
2193 vs->features |= VNC_FEATURE_XVP;
2194 send_xvp_message(vs, VNC_XVP_CODE_INIT);
2197 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2198 vs->tight->compression = (enc & 0x0F);
2200 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2201 if (vs->vd->lossy) {
2202 vs->tight->quality = (enc & 0x0F);
2206 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2210 vnc_desktop_resize(vs);
2211 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2212 vnc_led_state_change(vs);
2213 vnc_cursor_define(vs);
2216 static void set_pixel_conversion(VncState *vs)
2218 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2220 if (fmt == VNC_SERVER_FB_FORMAT) {
2221 vs->write_pixels = vnc_write_pixels_copy;
2222 vnc_hextile_set_pixel_conversion(vs, 0);
2224 vs->write_pixels = vnc_write_pixels_generic;
2225 vnc_hextile_set_pixel_conversion(vs, 1);
2229 static void send_color_map(VncState *vs)
2233 vnc_lock_output(vs);
2234 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2235 vnc_write_u8(vs, 0); /* padding */
2236 vnc_write_u16(vs, 0); /* first color */
2237 vnc_write_u16(vs, 256); /* # of colors */
2239 for (i = 0; i < 256; i++) {
2240 PixelFormat *pf = &vs->client_pf;
2242 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2243 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2244 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2246 vnc_unlock_output(vs);
2249 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2250 int big_endian_flag, int true_color_flag,
2251 int red_max, int green_max, int blue_max,
2252 int red_shift, int green_shift, int blue_shift)
2254 if (!true_color_flag) {
2255 /* Expose a reasonable default 256 color map */
2265 switch (bits_per_pixel) {
2271 vnc_client_error(vs);
2275 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2276 vs->client_pf.rbits = ctpopl(red_max);
2277 vs->client_pf.rshift = red_shift;
2278 vs->client_pf.rmask = red_max << red_shift;
2279 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2280 vs->client_pf.gbits = ctpopl(green_max);
2281 vs->client_pf.gshift = green_shift;
2282 vs->client_pf.gmask = green_max << green_shift;
2283 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2284 vs->client_pf.bbits = ctpopl(blue_max);
2285 vs->client_pf.bshift = blue_shift;
2286 vs->client_pf.bmask = blue_max << blue_shift;
2287 vs->client_pf.bits_per_pixel = bits_per_pixel;
2288 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2289 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2290 vs->client_be = big_endian_flag;
2292 if (!true_color_flag) {
2296 set_pixel_conversion(vs);
2298 graphic_hw_invalidate(vs->vd->dcl.con);
2299 graphic_hw_update(vs->vd->dcl.con);
2302 static void pixel_format_message (VncState *vs) {
2303 char pad[3] = { 0, 0, 0 };
2305 vs->client_pf = qemu_default_pixelformat(32);
2307 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2308 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2310 #ifdef HOST_WORDS_BIGENDIAN
2311 vnc_write_u8(vs, 1); /* big-endian-flag */
2313 vnc_write_u8(vs, 0); /* big-endian-flag */
2315 vnc_write_u8(vs, 1); /* true-color-flag */
2316 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2317 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2318 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2319 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2320 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2321 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2322 vnc_write(vs, pad, 3); /* padding */
2324 vnc_hextile_set_pixel_conversion(vs, 0);
2325 vs->write_pixels = vnc_write_pixels_copy;
2328 static void vnc_colordepth(VncState *vs)
2330 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2331 /* Sending a WMVi message to notify the client*/
2332 vnc_lock_output(vs);
2333 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2334 vnc_write_u8(vs, 0);
2335 vnc_write_u16(vs, 1); /* number of rects */
2336 vnc_framebuffer_update(vs, 0, 0,
2340 pixel_format_message(vs);
2341 vnc_unlock_output(vs);
2344 set_pixel_conversion(vs);
2348 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2353 VncDisplay *vd = vs->vd;
2356 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2360 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2364 set_pixel_format(vs, read_u8(data, 4),
2365 read_u8(data, 6), read_u8(data, 7),
2366 read_u16(data, 8), read_u16(data, 10),
2367 read_u16(data, 12), read_u8(data, 14),
2368 read_u8(data, 15), read_u8(data, 16));
2370 case VNC_MSG_CLIENT_SET_ENCODINGS:
2375 limit = read_u16(data, 2);
2377 return 4 + (limit * 4);
2379 limit = read_u16(data, 2);
2381 for (i = 0; i < limit; i++) {
2382 int32_t val = read_s32(data, 4 + (i * 4));
2383 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2386 set_encodings(vs, (int32_t *)(data + 4), limit);
2388 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2392 framebuffer_update_request(vs,
2393 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2394 read_u16(data, 6), read_u16(data, 8));
2396 case VNC_MSG_CLIENT_KEY_EVENT:
2400 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2402 case VNC_MSG_CLIENT_POINTER_EVENT:
2406 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2408 case VNC_MSG_CLIENT_CUT_TEXT:
2413 uint32_t dlen = read_u32(data, 4);
2414 if (dlen > (1 << 20)) {
2415 error_report("vnc: client_cut_text msg payload has %u bytes"
2416 " which exceeds our limit of 1MB.", dlen);
2417 vnc_client_error(vs);
2425 client_cut_text(vs, read_u32(data, 4), data + 8);
2427 case VNC_MSG_CLIENT_XVP:
2428 if (!(vs->features & VNC_FEATURE_XVP)) {
2429 error_report("vnc: xvp client message while disabled");
2430 vnc_client_error(vs);
2437 uint8_t version = read_u8(data, 2);
2438 uint8_t action = read_u8(data, 3);
2441 error_report("vnc: xvp client message version %d != 1",
2443 vnc_client_error(vs);
2448 case VNC_XVP_ACTION_SHUTDOWN:
2449 qemu_system_powerdown_request();
2451 case VNC_XVP_ACTION_REBOOT:
2452 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2454 case VNC_XVP_ACTION_RESET:
2455 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
2458 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2463 case VNC_MSG_CLIENT_QEMU:
2467 switch (read_u8(data, 1)) {
2468 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2472 ext_key_event(vs, read_u16(data, 2),
2473 read_u32(data, 4), read_u32(data, 8));
2475 case VNC_MSG_CLIENT_QEMU_AUDIO:
2479 switch (read_u16 (data, 2)) {
2480 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2481 trace_vnc_msg_client_audio_enable(vs, vs->ioc);
2484 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2485 trace_vnc_msg_client_audio_disable(vs, vs->ioc);
2488 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2491 switch (read_u8(data, 4)) {
2492 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
2493 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
2494 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
2495 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
2496 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
2497 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
2499 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2500 vnc_client_error(vs);
2503 vs->as.nchannels = read_u8(data, 5);
2504 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2505 VNC_DEBUG("Invalid audio channel count %d\n",
2507 vnc_client_error(vs);
2510 freq = read_u32(data, 6);
2511 /* No official limit for protocol, but 48khz is a sensible
2512 * upper bound for trustworthy clients, and this limit
2513 * protects calculations involving 'vs->as.freq' later.
2516 VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2517 vnc_client_error(vs);
2521 trace_vnc_msg_client_audio_format(
2522 vs, vs->ioc, vs->as.fmt, vs->as.nchannels, vs->as.freq);
2525 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2526 vnc_client_error(vs);
2532 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2533 vnc_client_error(vs);
2537 case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2547 screens = read_u8(data, 6);
2548 size = 8 + screens * 16;
2552 w = read_u16(data, 2);
2553 h = read_u16(data, 4);
2555 trace_vnc_msg_client_set_desktop_size(vs, vs->ioc, w, h, screens);
2556 if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2558 memset(&info, 0, sizeof(info));
2561 dpy_set_ui_info(vs->vd->dcl.con, &info);
2562 vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2564 vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2570 VNC_DEBUG("Msg: %d\n", data[0]);
2571 vnc_client_error(vs);
2575 vnc_update_throttle_offset(vs);
2576 vnc_read_when(vs, protocol_client_msg, 1);
2580 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2586 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2587 switch (vs->vd->share_policy) {
2588 case VNC_SHARE_POLICY_IGNORE:
2590 * Ignore the shared flag. Nothing to do here.
2592 * Doesn't conform to the rfb spec but is traditional qemu
2593 * behavior, thus left here as option for compatibility
2597 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2599 * Policy: Allow clients ask for exclusive access.
2601 * Implementation: When a client asks for exclusive access,
2602 * disconnect all others. Shared connects are allowed as long
2603 * as no exclusive connection exists.
2605 * This is how the rfb spec suggests to handle the shared flag.
2607 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2609 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2613 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2614 client->share_mode != VNC_SHARE_MODE_SHARED) {
2617 vnc_disconnect_start(client);
2620 if (mode == VNC_SHARE_MODE_SHARED) {
2621 if (vs->vd->num_exclusive > 0) {
2622 vnc_disconnect_start(vs);
2627 case VNC_SHARE_POLICY_FORCE_SHARED:
2629 * Policy: Shared connects only.
2630 * Implementation: Disallow clients asking for exclusive access.
2632 * Useful for shared desktop sessions where you don't want
2633 * someone forgetting to say -shared when running the vnc
2634 * client disconnect everybody else.
2636 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2637 vnc_disconnect_start(vs);
2642 vnc_set_share_mode(vs, mode);
2644 if (vs->vd->num_shared > vs->vd->connections_limit) {
2645 vnc_disconnect_start(vs);
2649 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2650 pixman_image_get_width(vs->vd->server) >= 0);
2651 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2652 pixman_image_get_height(vs->vd->server) >= 0);
2653 vs->client_width = pixman_image_get_width(vs->vd->server);
2654 vs->client_height = pixman_image_get_height(vs->vd->server);
2655 vnc_write_u16(vs, vs->client_width);
2656 vnc_write_u16(vs, vs->client_height);
2658 pixel_format_message(vs);
2661 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2662 if (size > sizeof(buf)) {
2666 size = snprintf(buf, sizeof(buf), "QEMU");
2669 vnc_write_u32(vs, size);
2670 vnc_write(vs, buf, size);
2673 vnc_client_cache_auth(vs);
2674 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2676 vnc_read_when(vs, protocol_client_msg, 1);
2681 void start_client_init(VncState *vs)
2683 vnc_read_when(vs, protocol_client_init, 1);
2686 static void authentication_failed(VncState *vs)
2688 vnc_write_u32(vs, 1); /* Reject auth */
2689 if (vs->minor >= 8) {
2690 static const char err[] = "Authentication failed";
2691 vnc_write_u32(vs, sizeof(err));
2692 vnc_write(vs, err, sizeof(err));
2695 vnc_client_error(vs);
2698 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2700 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2702 unsigned char key[8];
2703 time_t now = time(NULL);
2704 QCryptoCipher *cipher = NULL;
2707 if (!vs->vd->password) {
2708 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2711 if (vs->vd->expires < now) {
2712 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2716 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2718 /* Calculate the expected challenge response */
2719 pwlen = strlen(vs->vd->password);
2720 for (i=0; i<sizeof(key); i++)
2721 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2723 cipher = qcrypto_cipher_new(
2724 QCRYPTO_CIPHER_ALG_DES_RFB,
2725 QCRYPTO_CIPHER_MODE_ECB,
2726 key, G_N_ELEMENTS(key),
2729 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2730 error_get_pretty(err));
2735 if (qcrypto_cipher_encrypt(cipher,
2738 VNC_AUTH_CHALLENGE_SIZE,
2740 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2741 error_get_pretty(err));
2746 /* Compare expected vs actual challenge response */
2747 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2748 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2751 trace_vnc_auth_pass(vs, vs->auth);
2752 vnc_write_u32(vs, 0); /* Accept auth */
2755 start_client_init(vs);
2758 qcrypto_cipher_free(cipher);
2762 authentication_failed(vs);
2763 qcrypto_cipher_free(cipher);
2767 void start_auth_vnc(VncState *vs)
2771 if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2772 trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2773 error_get_pretty(err));
2775 authentication_failed(vs);
2779 /* Send client a 'random' challenge */
2780 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2783 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2787 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2789 /* We only advertise 1 auth scheme at a time, so client
2790 * must pick the one we sent. Verify this */
2791 if (data[0] != vs->auth) { /* Reject auth */
2792 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2793 authentication_failed(vs);
2794 } else { /* Accept requested auth */
2795 trace_vnc_auth_start(vs, vs->auth);
2798 if (vs->minor >= 8) {
2799 vnc_write_u32(vs, 0); /* Accept auth completion */
2802 trace_vnc_auth_pass(vs, vs->auth);
2803 start_client_init(vs);
2810 case VNC_AUTH_VENCRYPT:
2811 start_auth_vencrypt(vs);
2814 #ifdef CONFIG_VNC_SASL
2816 start_auth_sasl(vs);
2818 #endif /* CONFIG_VNC_SASL */
2820 default: /* Should not be possible, but just in case */
2821 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2822 authentication_failed(vs);
2828 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2832 memcpy(local, version, 12);
2835 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2836 VNC_DEBUG("Malformed protocol version %s\n", local);
2837 vnc_client_error(vs);
2840 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2841 if (vs->major != 3 ||
2847 VNC_DEBUG("Unsupported client version\n");
2848 vnc_write_u32(vs, VNC_AUTH_INVALID);
2850 vnc_client_error(vs);
2853 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2854 * as equivalent to v3.3 by servers
2856 if (vs->minor == 4 || vs->minor == 5)
2859 if (vs->minor == 3) {
2860 trace_vnc_auth_start(vs, vs->auth);
2861 if (vs->auth == VNC_AUTH_NONE) {
2862 vnc_write_u32(vs, vs->auth);
2864 trace_vnc_auth_pass(vs, vs->auth);
2865 start_client_init(vs);
2866 } else if (vs->auth == VNC_AUTH_VNC) {
2867 VNC_DEBUG("Tell client VNC auth\n");
2868 vnc_write_u32(vs, vs->auth);
2872 trace_vnc_auth_fail(vs, vs->auth,
2873 "Unsupported auth method for v3.3", "");
2874 vnc_write_u32(vs, VNC_AUTH_INVALID);
2876 vnc_client_error(vs);
2879 vnc_write_u8(vs, 1); /* num auth */
2880 vnc_write_u8(vs, vs->auth);
2881 vnc_read_when(vs, protocol_client_auth, 1);
2888 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2890 struct VncSurface *vs = &vd->guest;
2892 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2895 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2899 w = (x + w) / VNC_STAT_RECT;
2900 h = (y + h) / VNC_STAT_RECT;
2904 for (j = y; j <= h; j++) {
2905 for (i = x; i <= w; i++) {
2906 vs->lossy_rect[j][i] = 1;
2911 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2914 int sty = y / VNC_STAT_RECT;
2915 int stx = x / VNC_STAT_RECT;
2918 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2919 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2921 QTAILQ_FOREACH(vs, &vd->clients, next) {
2924 /* kernel send buffers are full -> refresh later */
2925 if (vs->output.offset) {
2929 if (!vs->lossy_rect[sty][stx]) {
2933 vs->lossy_rect[sty][stx] = 0;
2934 for (j = 0; j < VNC_STAT_RECT; ++j) {
2935 bitmap_set(vs->dirty[y + j],
2936 x / VNC_DIRTY_PIXELS_PER_BIT,
2937 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2945 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2947 int width = MIN(pixman_image_get_width(vd->guest.fb),
2948 pixman_image_get_width(vd->server));
2949 int height = MIN(pixman_image_get_height(vd->guest.fb),
2950 pixman_image_get_height(vd->server));
2955 for (y = 0; y < height; y += VNC_STAT_RECT) {
2956 for (x = 0; x < width; x += VNC_STAT_RECT) {
2957 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2959 rect->updated = false;
2963 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2965 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2968 vd->guest.last_freq_check = *tv;
2970 for (y = 0; y < height; y += VNC_STAT_RECT) {
2971 for (x = 0; x < width; x += VNC_STAT_RECT) {
2972 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2973 int count = ARRAY_SIZE(rect->times);
2974 struct timeval min, max;
2976 if (!timerisset(&rect->times[count - 1])) {
2980 max = rect->times[(rect->idx + count - 1) % count];
2981 qemu_timersub(tv, &max, &res);
2983 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2985 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2986 memset(rect->times, 0, sizeof (rect->times));
2990 min = rect->times[rect->idx];
2991 max = rect->times[(rect->idx + count - 1) % count];
2992 qemu_timersub(&max, &min, &res);
2994 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2995 rect->freq /= count;
2996 rect->freq = 1. / rect->freq;
3002 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
3008 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
3009 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
3011 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
3012 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
3013 total += vnc_stat_rect(vs->vd, i, j)->freq;
3025 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
3029 rect = vnc_stat_rect(vd, x, y);
3030 if (rect->updated) {
3033 rect->times[rect->idx] = *tv;
3034 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3035 rect->updated = true;
3038 static int vnc_refresh_server_surface(VncDisplay *vd)
3040 int width = MIN(pixman_image_get_width(vd->guest.fb),
3041 pixman_image_get_width(vd->server));
3042 int height = MIN(pixman_image_get_height(vd->guest.fb),
3043 pixman_image_get_height(vd->server));
3044 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
3045 uint8_t *guest_row0 = NULL, *server_row0;
3048 pixman_image_t *tmpbuf = NULL;
3050 struct timeval tv = { 0, 0 };
3052 if (!vd->non_adaptive) {
3053 gettimeofday(&tv, NULL);
3054 has_dirty = vnc_update_stats(vd, &tv);
3058 * Walk through the guest dirty map.
3059 * Check and copy modified bits from guest to server surface.
3060 * Update server dirty map.
3062 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3063 server_stride = guest_stride = guest_ll =
3064 pixman_image_get_stride(vd->server);
3065 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3067 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3068 int width = pixman_image_get_width(vd->server);
3069 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
3072 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
3073 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
3074 guest_stride = pixman_image_get_stride(vd->guest.fb);
3075 guest_ll = pixman_image_get_width(vd->guest.fb)
3076 * DIV_ROUND_UP(guest_bpp, 8);
3078 line_bytes = MIN(server_stride, guest_ll);
3082 uint8_t *guest_ptr, *server_ptr;
3083 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
3084 height * VNC_DIRTY_BPL(&vd->guest),
3085 y * VNC_DIRTY_BPL(&vd->guest));
3086 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
3087 /* no more dirty bits */
3090 y = offset / VNC_DIRTY_BPL(&vd->guest);
3091 x = offset % VNC_DIRTY_BPL(&vd->guest);
3093 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
3095 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3096 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
3097 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
3099 guest_ptr = guest_row0 + y * guest_stride;
3101 guest_ptr += x * cmp_bytes;
3103 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
3104 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3105 int _cmp_bytes = cmp_bytes;
3106 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
3109 if ((x + 1) * cmp_bytes > line_bytes) {
3110 _cmp_bytes = line_bytes - x * cmp_bytes;
3112 assert(_cmp_bytes >= 0);
3113 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
3116 memcpy(server_ptr, guest_ptr, _cmp_bytes);
3117 if (!vd->non_adaptive) {
3118 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
3121 QTAILQ_FOREACH(vs, &vd->clients, next) {
3122 set_bit(x, vs->dirty[y]);
3129 qemu_pixman_image_unref(tmpbuf);
3133 static void vnc_refresh(DisplayChangeListener *dcl)
3135 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
3137 int has_dirty, rects = 0;
3139 if (QTAILQ_EMPTY(&vd->clients)) {
3140 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
3144 graphic_hw_update(vd->dcl.con);
3146 if (vnc_trylock_display(vd)) {
3147 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3151 has_dirty = vnc_refresh_server_surface(vd);
3152 vnc_unlock_display(vd);
3154 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3155 rects += vnc_update_client(vs, has_dirty);
3156 /* vs might be free()ed here */
3159 if (has_dirty && rects) {
3160 vd->dcl.update_interval /= 2;
3161 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3162 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3165 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3166 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3167 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3172 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3173 bool skipauth, bool websocket)
3175 VncState *vs = g_new0(VncState, 1);
3176 bool first_client = QTAILQ_EMPTY(&vd->clients);
3179 trace_vnc_client_connect(vs, sioc);
3180 vs->zrle = g_new0(VncZrle, 1);
3181 vs->tight = g_new0(VncTight, 1);
3182 vs->magic = VNC_MAGIC;
3184 object_ref(OBJECT(vs->sioc));
3185 vs->ioc = QIO_CHANNEL(sioc);
3186 object_ref(OBJECT(vs->ioc));
3189 buffer_init(&vs->input, "vnc-input/%p", sioc);
3190 buffer_init(&vs->output, "vnc-output/%p", sioc);
3191 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
3193 buffer_init(&vs->tight->tight, "vnc-tight/%p", sioc);
3194 buffer_init(&vs->tight->zlib, "vnc-tight-zlib/%p", sioc);
3195 buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3196 #ifdef CONFIG_VNC_JPEG
3197 buffer_init(&vs->tight->jpeg, "vnc-tight-jpeg/%p", sioc);
3199 #ifdef CONFIG_VNC_PNG
3200 buffer_init(&vs->tight->png, "vnc-tight-png/%p", sioc);
3202 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
3203 buffer_init(&vs->zrle->zrle, "vnc-zrle/%p", sioc);
3204 buffer_init(&vs->zrle->fb, "vnc-zrle-fb/%p", sioc);
3205 buffer_init(&vs->zrle->zlib, "vnc-zrle-zlib/%p", sioc);
3208 vs->auth = VNC_AUTH_NONE;
3209 vs->subauth = VNC_AUTH_INVALID;
3212 vs->auth = vd->ws_auth;
3213 vs->subauth = VNC_AUTH_INVALID;
3215 vs->auth = vd->auth;
3216 vs->subauth = vd->subauth;
3219 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3220 sioc, websocket, vs->auth, vs->subauth);
3222 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3223 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3224 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3227 VNC_DEBUG("New client on socket %p\n", vs->sioc);
3228 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3229 qio_channel_set_blocking(vs->ioc, false, NULL);
3231 g_source_remove(vs->ioc_tag);
3236 vs->ioc_tag = qio_channel_add_watch(
3237 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3238 vncws_tls_handshake_io, vs, NULL);
3240 vs->ioc_tag = qio_channel_add_watch(
3241 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3242 vncws_handshake_io, vs, NULL);
3245 vs->ioc_tag = qio_channel_add_watch(
3246 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3247 vnc_client_io, vs, NULL);
3250 vnc_client_cache_addr(vs);
3251 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3252 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3257 vs->as.freq = 44100;
3258 vs->as.nchannels = 2;
3259 vs->as.fmt = AUDIO_FORMAT_S16;
3260 vs->as.endianness = 0;
3262 qemu_mutex_init(&vs->output_mutex);
3263 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3265 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3267 vnc_update_server_surface(vd);
3270 graphic_hw_update(vd->dcl.con);
3272 if (!vs->websocket) {
3273 vnc_start_protocol(vs);
3276 if (vd->num_connecting > vd->connections_limit) {
3277 QTAILQ_FOREACH(vs, &vd->clients, next) {
3278 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3279 vnc_disconnect_start(vs);
3286 void vnc_start_protocol(VncState *vs)
3288 vnc_write(vs, "RFB 003.008\n", 12);
3290 vnc_read_when(vs, protocol_version, 12);
3292 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3293 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3296 static void vnc_listen_io(QIONetListener *listener,
3297 QIOChannelSocket *cioc,
3300 VncDisplay *vd = opaque;
3301 bool isWebsock = listener == vd->wslistener;
3303 qio_channel_set_name(QIO_CHANNEL(cioc),
3304 isWebsock ? "vnc-ws-server" : "vnc-server");
3305 qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3306 vnc_connect(vd, cioc, false, isWebsock);
3309 static const DisplayChangeListenerOps dcl_ops = {
3311 .dpy_refresh = vnc_refresh,
3312 .dpy_gfx_update = vnc_dpy_update,
3313 .dpy_gfx_switch = vnc_dpy_switch,
3314 .dpy_gfx_check_format = qemu_pixman_check_format,
3315 .dpy_mouse_set = vnc_mouse_set,
3316 .dpy_cursor_define = vnc_dpy_cursor_define,
3319 void vnc_display_init(const char *id, Error **errp)
3323 if (vnc_display_find(id) != NULL) {
3326 vd = g_malloc0(sizeof(*vd));
3328 vd->id = strdup(id);
3329 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3331 QTAILQ_INIT(&vd->clients);
3332 vd->expires = TIME_MAX;
3334 if (keyboard_layout) {
3335 trace_vnc_key_map_init(keyboard_layout);
3336 vd->kbd_layout = init_keyboard_layout(name2keysym,
3337 keyboard_layout, errp);
3339 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3342 if (!vd->kbd_layout) {
3346 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3347 vd->connections_limit = 32;
3349 qemu_mutex_init(&vd->mutex);
3350 vnc_start_worker_thread();
3352 vd->dcl.ops = &dcl_ops;
3353 register_displaychangelistener(&vd->dcl);
3354 vd->kbd = qkbd_state_init(vd->dcl.con);
3358 static void vnc_display_close(VncDisplay *vd)
3363 vd->is_unix = false;
3366 qio_net_listener_disconnect(vd->listener);
3367 object_unref(OBJECT(vd->listener));
3369 vd->listener = NULL;
3371 if (vd->wslistener) {
3372 qio_net_listener_disconnect(vd->wslistener);
3373 object_unref(OBJECT(vd->wslistener));
3375 vd->wslistener = NULL;
3377 vd->auth = VNC_AUTH_INVALID;
3378 vd->subauth = VNC_AUTH_INVALID;
3380 object_unref(OBJECT(vd->tlscreds));
3381 vd->tlscreds = NULL;
3384 object_unparent(OBJECT(vd->tlsauthz));
3385 vd->tlsauthz = NULL;
3387 g_free(vd->tlsauthzid);
3388 vd->tlsauthzid = NULL;
3389 if (vd->lock_key_sync) {
3390 qemu_remove_led_event_handler(vd->led);
3393 #ifdef CONFIG_VNC_SASL
3394 if (vd->sasl.authz) {
3395 object_unparent(OBJECT(vd->sasl.authz));
3396 vd->sasl.authz = NULL;
3398 g_free(vd->sasl.authzid);
3399 vd->sasl.authzid = NULL;
3403 int vnc_display_password(const char *id, const char *password)
3405 VncDisplay *vd = vnc_display_find(id);
3410 if (vd->auth == VNC_AUTH_NONE) {
3411 error_printf_unless_qmp("If you want use passwords please enable "
3412 "password auth using '-vnc ${dpy},password'.\n");
3416 g_free(vd->password);
3417 vd->password = g_strdup(password);
3422 int vnc_display_pw_expire(const char *id, time_t expires)
3424 VncDisplay *vd = vnc_display_find(id);
3430 vd->expires = expires;
3434 static void vnc_display_print_local_addr(VncDisplay *vd)
3436 SocketAddress *addr;
3438 if (!vd->listener || !vd->listener->nsioc) {
3442 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
3447 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3448 qapi_free_SocketAddress(addr);
3451 error_printf_unless_qmp("VNC server running on %s:%s\n",
3454 qapi_free_SocketAddress(addr);
3457 static QemuOptsList qemu_vnc_opts = {
3459 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3460 .implied_opt_name = "vnc",
3464 .type = QEMU_OPT_STRING,
3466 .name = "websocket",
3467 .type = QEMU_OPT_STRING,
3469 .name = "tls-creds",
3470 .type = QEMU_OPT_STRING,
3473 .type = QEMU_OPT_STRING,
3476 .type = QEMU_OPT_STRING,
3479 .type = QEMU_OPT_NUMBER,
3481 .name = "connections",
3482 .type = QEMU_OPT_NUMBER,
3485 .type = QEMU_OPT_NUMBER,
3488 .type = QEMU_OPT_BOOL,
3491 .type = QEMU_OPT_BOOL,
3494 .type = QEMU_OPT_BOOL,
3496 .name = "password-secret",
3497 .type = QEMU_OPT_STRING,
3500 .type = QEMU_OPT_BOOL,
3502 .name = "lock-key-sync",
3503 .type = QEMU_OPT_BOOL,
3505 .name = "key-delay-ms",
3506 .type = QEMU_OPT_NUMBER,
3509 .type = QEMU_OPT_BOOL,
3512 .type = QEMU_OPT_BOOL,
3514 .name = "tls-authz",
3515 .type = QEMU_OPT_STRING,
3517 .name = "sasl-authz",
3518 .type = QEMU_OPT_STRING,
3521 .type = QEMU_OPT_BOOL,
3523 .name = "non-adaptive",
3524 .type = QEMU_OPT_BOOL,
3527 .type = QEMU_OPT_STRING,
3529 .name = "power-control",
3530 .type = QEMU_OPT_BOOL,
3532 { /* end of list */ }
3538 vnc_display_setup_auth(int *auth,
3540 QCryptoTLSCreds *tlscreds,
3547 * We have a choice of 3 authentication options
3553 * The channel can be run in 2 modes
3558 * And TLS can use 2 types of credentials
3563 * We thus have 9 possible logical combinations
3568 * 4. tls + anon + none
3569 * 5. tls + anon + vnc
3570 * 6. tls + anon + sasl
3571 * 7. tls + x509 + none
3572 * 8. tls + x509 + vnc
3573 * 9. tls + x509 + sasl
3575 * These need to be mapped into the VNC auth schemes
3576 * in an appropriate manner. In regular VNC, all the
3577 * TLS options get mapped into VNC_AUTH_VENCRYPT
3580 * In websockets, the https:// protocol already provides
3581 * TLS support, so there is no need to make use of the
3582 * VeNCrypt extension. Furthermore, websockets browser
3583 * clients could not use VeNCrypt even if they wanted to,
3584 * as they cannot control when the TLS handshake takes
3585 * place. Thus there is no option but to rely on https://,
3586 * meaning combinations 4->6 and 7->9 will be mapped to
3587 * VNC auth schemes in the same way as combos 1->3.
3589 * Regardless of fact that we have a different mapping to
3590 * VNC auth mechs for plain VNC vs websockets VNC, the end
3591 * result has the same security characteristics.
3593 if (websocket || !tlscreds) {
3595 VNC_DEBUG("Initializing VNC server with password auth\n");
3596 *auth = VNC_AUTH_VNC;
3598 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3599 *auth = VNC_AUTH_SASL;
3601 VNC_DEBUG("Initializing VNC server with no auth\n");
3602 *auth = VNC_AUTH_NONE;
3604 *subauth = VNC_AUTH_INVALID;
3606 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3607 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3608 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3609 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3611 if (!is_x509 && !is_anon) {
3613 "Unsupported TLS cred type %s",
3614 object_get_typename(OBJECT(tlscreds)));
3617 *auth = VNC_AUTH_VENCRYPT;
3620 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3621 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3623 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3624 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3629 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3630 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3632 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3633 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3637 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3638 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3640 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3641 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3649 static int vnc_display_get_address(const char *addrstr,
3658 SocketAddress **retaddr,
3662 SocketAddress *addr = NULL;
3664 addr = g_new0(SocketAddress, 1);
3666 if (strncmp(addrstr, "unix:", 5) == 0) {
3667 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3668 addr->u.q_unix.path = g_strdup(addrstr + 5);
3671 error_setg(errp, "UNIX sockets not supported with websock");
3676 error_setg(errp, "Port range not support with UNIX socket");
3683 unsigned long long baseport = 0;
3684 InetSocketAddress *inet;
3686 port = strrchr(addrstr, ':');
3692 error_setg(errp, "no vnc port specified");
3696 hostlen = port - addrstr;
3698 if (*port == '\0') {
3699 error_setg(errp, "vnc port cannot be empty");
3704 addr->type = SOCKET_ADDRESS_TYPE_INET;
3705 inet = &addr->u.inet;
3706 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3707 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3709 inet->host = g_strndup(addrstr, hostlen);
3711 /* plain VNC port is just an offset, for websocket
3712 * port is absolute */
3714 if (g_str_equal(addrstr, "") ||
3715 g_str_equal(addrstr, "on")) {
3716 if (displaynum == -1) {
3717 error_setg(errp, "explicit websocket port is required");
3720 inet->port = g_strdup_printf(
3721 "%d", displaynum + 5700);
3723 inet->has_to = true;
3724 inet->to = to + 5700;
3727 inet->port = g_strdup(port);
3730 int offset = reverse ? 0 : 5900;
3731 if (parse_uint_full(port, &baseport, 10) < 0) {
3732 error_setg(errp, "can't convert to a number: %s", port);
3735 if (baseport > 65535 ||
3736 baseport + offset > 65535) {
3737 error_setg(errp, "port %s out of range", port);
3740 inet->port = g_strdup_printf(
3741 "%d", (int)baseport + offset);
3744 inet->has_to = true;
3745 inet->to = to + offset;
3750 inet->has_ipv4 = has_ipv4;
3752 inet->has_ipv6 = has_ipv6;
3761 qapi_free_SocketAddress(addr);
3766 static void vnc_free_addresses(SocketAddress ***retsaddr,
3771 for (i = 0; i < *retnsaddr; i++) {
3772 qapi_free_SocketAddress((*retsaddr)[i]);
3780 static int vnc_display_get_addresses(QemuOpts *opts,
3782 SocketAddress ***retsaddr,
3784 SocketAddress ***retwsaddr,
3788 SocketAddress *saddr = NULL;
3789 SocketAddress *wsaddr = NULL;
3790 QemuOptsIter addriter;
3792 int to = qemu_opt_get_number(opts, "to", 0);
3793 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3794 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3795 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3796 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3797 int displaynum = -1;
3805 addr = qemu_opt_get(opts, "vnc");
3806 if (addr == NULL || g_str_equal(addr, "none")) {
3810 if (qemu_opt_get(opts, "websocket") &&
3811 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3813 "SHA1 hash support is required for websockets");
3817 qemu_opt_iter_init(&addriter, opts, "vnc");
3818 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3820 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3827 /* Historical compat - first listen address can be used
3828 * to set the default websocket port
3830 if (displaynum == -1) {
3833 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3834 (*retsaddr)[(*retnsaddr)++] = saddr;
3837 /* If we had multiple primary displays, we don't do defaults
3838 * for websocket, and require explicit config instead. */
3839 if (*retnsaddr > 1) {
3843 qemu_opt_iter_init(&addriter, opts, "websocket");
3844 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3845 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3848 &wsaddr, errp) < 0) {
3852 /* Historical compat - if only a single listen address was
3853 * provided, then this is used to set the default listen
3854 * address for websocket too
3856 if (*retnsaddr == 1 &&
3857 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3858 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3859 g_str_equal(wsaddr->u.inet.host, "") &&
3860 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3861 g_free(wsaddr->u.inet.host);
3862 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3865 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3866 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3872 vnc_free_addresses(retsaddr, retnsaddr);
3873 vnc_free_addresses(retwsaddr, retnwsaddr);
3878 static int vnc_display_connect(VncDisplay *vd,
3879 SocketAddress **saddr,
3881 SocketAddress **wsaddr,
3885 /* connect to viewer */
3886 QIOChannelSocket *sioc = NULL;
3888 error_setg(errp, "Cannot use websockets in reverse mode");
3892 error_setg(errp, "Expected a single address in reverse mode");
3895 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3896 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3897 sioc = qio_channel_socket_new();
3898 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3899 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3900 object_unref(OBJECT(sioc));
3903 vnc_connect(vd, sioc, false, false);
3904 object_unref(OBJECT(sioc));
3909 static int vnc_display_listen(VncDisplay *vd,
3910 SocketAddress **saddr,
3912 SocketAddress **wsaddr,
3919 vd->listener = qio_net_listener_new();
3920 qio_net_listener_set_name(vd->listener, "vnc-listen");
3921 for (i = 0; i < nsaddr; i++) {
3922 if (qio_net_listener_open_sync(vd->listener,
3929 qio_net_listener_set_client_func(vd->listener,
3930 vnc_listen_io, vd, NULL);
3934 vd->wslistener = qio_net_listener_new();
3935 qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3936 for (i = 0; i < nwsaddr; i++) {
3937 if (qio_net_listener_open_sync(vd->wslistener,
3944 qio_net_listener_set_client_func(vd->wslistener,
3945 vnc_listen_io, vd, NULL);
3952 void vnc_display_open(const char *id, Error **errp)
3954 VncDisplay *vd = vnc_display_find(id);
3955 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3956 SocketAddress **saddr = NULL, **wsaddr = NULL;
3957 size_t nsaddr, nwsaddr;
3958 const char *share, *device_id;
3960 bool password = false;
3961 bool reverse = false;
3965 const char *tlsauthz;
3966 const char *saslauthz;
3967 int lock_key_sync = 1;
3969 const char *audiodev;
3970 const char *passwordSecret;
3973 error_setg(errp, "VNC display not active");
3976 vnc_display_close(vd);
3982 reverse = qemu_opt_get_bool(opts, "reverse", false);
3983 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3984 &wsaddr, &nwsaddr, errp) < 0) {
3989 passwordSecret = qemu_opt_get(opts, "password-secret");
3990 if (passwordSecret) {
3991 if (qemu_opt_get(opts, "password")) {
3993 "'password' flag is redundant with 'password-secret'");
3996 vd->password = qcrypto_secret_lookup_as_utf8(passwordSecret,
3998 if (!vd->password) {
4003 password = qemu_opt_get_bool(opts, "password", false);
4006 if (fips_get_state()) {
4008 "VNC password auth disabled due to FIPS mode, "
4009 "consider using the VeNCrypt or SASL authentication "
4010 "methods as an alternative");
4013 if (!qcrypto_cipher_supports(
4014 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
4016 "Cipher backend does not support DES RFB algorithm");
4021 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
4022 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
4023 sasl = qemu_opt_get_bool(opts, "sasl", false);
4024 #ifndef CONFIG_VNC_SASL
4026 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
4029 #endif /* CONFIG_VNC_SASL */
4030 credid = qemu_opt_get(opts, "tls-creds");
4033 creds = object_resolve_path_component(
4034 object_get_objects_root(), credid);
4036 error_setg(errp, "No TLS credentials with id '%s'",
4040 vd->tlscreds = (QCryptoTLSCreds *)
4041 object_dynamic_cast(creds,
4042 TYPE_QCRYPTO_TLS_CREDS);
4043 if (!vd->tlscreds) {
4044 error_setg(errp, "Object with id '%s' is not TLS credentials",
4048 object_ref(OBJECT(vd->tlscreds));
4050 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4052 "Expecting TLS credentials with a server endpoint");
4056 if (qemu_opt_get(opts, "acl")) {
4057 error_report("The 'acl' option to -vnc is deprecated. "
4058 "Please use the 'tls-authz' and 'sasl-authz' "
4061 acl = qemu_opt_get_bool(opts, "acl", false);
4062 tlsauthz = qemu_opt_get(opts, "tls-authz");
4063 if (acl && tlsauthz) {
4064 error_setg(errp, "'acl' option is mutually exclusive with the "
4065 "'tls-authz' option");
4068 if (tlsauthz && !vd->tlscreds) {
4069 error_setg(errp, "'tls-authz' provided but TLS is not enabled");
4073 saslauthz = qemu_opt_get(opts, "sasl-authz");
4074 if (acl && saslauthz) {
4075 error_setg(errp, "'acl' option is mutually exclusive with the "
4076 "'sasl-authz' option");
4079 if (saslauthz && !sasl) {
4080 error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
4084 share = qemu_opt_get(opts, "share");
4086 if (strcmp(share, "ignore") == 0) {
4087 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
4088 } else if (strcmp(share, "allow-exclusive") == 0) {
4089 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4090 } else if (strcmp(share, "force-shared") == 0) {
4091 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
4093 error_setg(errp, "unknown vnc share= option");
4097 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4099 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
4101 #ifdef CONFIG_VNC_JPEG
4102 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
4104 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4105 /* adaptive updates are only used with tight encoding and
4106 * if lossy updates are enabled so we can disable all the
4107 * calculations otherwise */
4109 vd->non_adaptive = true;
4112 vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
4115 vd->tlsauthzid = g_strdup(tlsauthz);
4117 if (strcmp(vd->id, "default") == 0) {
4118 vd->tlsauthzid = g_strdup("vnc.x509dname");
4120 vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
4122 vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
4123 QAUTHZ_LIST_POLICY_DENY,
4126 #ifdef CONFIG_VNC_SASL
4129 vd->sasl.authzid = g_strdup(saslauthz);
4131 if (strcmp(vd->id, "default") == 0) {
4132 vd->sasl.authzid = g_strdup("vnc.username");
4134 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
4136 vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
4137 QAUTHZ_LIST_POLICY_DENY,
4143 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4144 vd->tlscreds, password,
4145 sasl, false, errp) < 0) {
4148 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4150 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4151 vd->tlscreds, password,
4152 sasl, true, errp) < 0) {
4155 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
4157 #ifdef CONFIG_VNC_SASL
4159 int saslErr = sasl_server_init(NULL, "qemu");
4161 if (saslErr != SASL_OK) {
4162 error_setg(errp, "Failed to initialize SASL auth: %s",
4163 sasl_errstring(saslErr, NULL, NULL));
4168 vd->lock_key_sync = lock_key_sync;
4169 if (lock_key_sync) {
4170 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4174 audiodev = qemu_opt_get(opts, "audiodev");
4176 vd->audio_state = audio_state_by_name(audiodev);
4177 if (!vd->audio_state) {
4178 error_setg(errp, "Audiodev '%s' not found", audiodev);
4183 device_id = qemu_opt_get(opts, "display");
4185 int head = qemu_opt_get_number(opts, "head", 0);
4188 con = qemu_console_lookup_by_device_name(device_id, head, &err);
4190 error_propagate(errp, err);
4197 if (con != vd->dcl.con) {
4198 qkbd_state_free(vd->kbd);
4199 unregister_displaychangelistener(&vd->dcl);
4201 register_displaychangelistener(&vd->dcl);
4202 vd->kbd = qkbd_state_init(vd->dcl.con);
4204 qkbd_state_set_delay(vd->kbd, key_delay_ms);
4206 if (saddr == NULL) {
4211 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4215 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4220 if (qemu_opt_get(opts, "to")) {
4221 vnc_display_print_local_addr(vd);
4225 vnc_free_addresses(&saddr, &nsaddr);
4226 vnc_free_addresses(&wsaddr, &nwsaddr);
4230 vnc_display_close(vd);
4234 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4236 VncDisplay *vd = vnc_display_find(id);
4237 QIOChannelSocket *sioc;
4243 sioc = qio_channel_socket_new_fd(csock, NULL);
4245 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4246 vnc_connect(vd, sioc, skipauth, false);
4247 object_unref(OBJECT(sioc));
4251 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4256 id = g_strdup("default");
4257 while (qemu_opts_find(olist, id)) {
4259 id = g_strdup_printf("vnc%d", i++);
4261 qemu_opts_set_id(opts, id);
4264 void vnc_parse(const char *str)
4266 QemuOptsList *olist = qemu_find_opts("vnc");
4267 QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
4274 id = qemu_opts_id(opts);
4276 /* auto-assign id if not present */
4277 vnc_auto_assign_id(olist, opts);
4281 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4283 Error *local_err = NULL;
4284 char *id = (char *)qemu_opts_id(opts);
4287 vnc_display_init(id, &local_err);
4289 error_propagate(errp, local_err);
4292 vnc_display_open(id, &local_err);
4293 if (local_err != NULL) {
4294 error_propagate(errp, local_err);
4300 static void vnc_register_config(void)
4302 qemu_add_opts(&qemu_vnc_opts);
4304 opts_init(vnc_register_config);