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 "sysemu/sysemu.h"
32 #include "qemu/error-report.h"
33 #include "qemu/option.h"
34 #include "qemu/sockets.h"
35 #include "qemu/timer.h"
36 #include "authz/list.h"
37 #include "qemu/config-file.h"
38 #include "qapi/qapi-emit-events.h"
39 #include "qapi/qapi-events-ui.h"
40 #include "qapi/error.h"
41 #include "qapi/qapi-commands-ui.h"
43 #include "crypto/hash.h"
44 #include "crypto/tlscredsanon.h"
45 #include "crypto/tlscredsx509.h"
46 #include "qom/object_interfaces.h"
47 #include "qemu/cutils.h"
48 #include "io/dns-resolver.h"
50 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
51 #define VNC_REFRESH_INTERVAL_INC 50
52 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
53 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
54 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
56 #include "vnc_keysym.h"
57 #include "crypto/cipher.h"
59 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
60 QTAILQ_HEAD_INITIALIZER(vnc_displays);
62 static int vnc_cursor_define(VncState *vs);
63 static void vnc_update_throttle_offset(VncState *vs);
65 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
68 static const char *mn[] = {
70 [VNC_SHARE_MODE_CONNECTING] = "connecting",
71 [VNC_SHARE_MODE_SHARED] = "shared",
72 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
73 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
75 fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
76 vs->ioc, mn[vs->share_mode], mn[mode]);
79 switch (vs->share_mode) {
80 case VNC_SHARE_MODE_CONNECTING:
81 vs->vd->num_connecting--;
83 case VNC_SHARE_MODE_SHARED:
86 case VNC_SHARE_MODE_EXCLUSIVE:
87 vs->vd->num_exclusive--;
93 vs->share_mode = mode;
95 switch (vs->share_mode) {
96 case VNC_SHARE_MODE_CONNECTING:
97 vs->vd->num_connecting++;
99 case VNC_SHARE_MODE_SHARED:
100 vs->vd->num_shared++;
102 case VNC_SHARE_MODE_EXCLUSIVE:
103 vs->vd->num_exclusive++;
111 static void vnc_init_basic_info(SocketAddress *addr,
115 switch (addr->type) {
116 case SOCKET_ADDRESS_TYPE_INET:
117 info->host = g_strdup(addr->u.inet.host);
118 info->service = g_strdup(addr->u.inet.port);
119 if (addr->u.inet.ipv6) {
120 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
122 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
126 case SOCKET_ADDRESS_TYPE_UNIX:
127 info->host = g_strdup("");
128 info->service = g_strdup(addr->u.q_unix.path);
129 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
132 case SOCKET_ADDRESS_TYPE_VSOCK:
133 case SOCKET_ADDRESS_TYPE_FD:
134 error_setg(errp, "Unsupported socket address type %s",
135 SocketAddressType_str(addr->type));
144 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
148 SocketAddress *addr = NULL;
151 error_setg(errp, "No listener socket available");
155 addr = qio_channel_socket_get_local_address(ioc, errp);
160 vnc_init_basic_info(addr, info, errp);
161 qapi_free_SocketAddress(addr);
164 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
168 SocketAddress *addr = NULL;
170 addr = qio_channel_socket_get_remote_address(ioc, errp);
175 vnc_init_basic_info(addr, info, errp);
176 qapi_free_SocketAddress(addr);
179 static const char *vnc_auth_name(VncDisplay *vd) {
181 case VNC_AUTH_INVALID:
197 case VNC_AUTH_VENCRYPT:
198 switch (vd->subauth) {
199 case VNC_AUTH_VENCRYPT_PLAIN:
200 return "vencrypt+plain";
201 case VNC_AUTH_VENCRYPT_TLSNONE:
202 return "vencrypt+tls+none";
203 case VNC_AUTH_VENCRYPT_TLSVNC:
204 return "vencrypt+tls+vnc";
205 case VNC_AUTH_VENCRYPT_TLSPLAIN:
206 return "vencrypt+tls+plain";
207 case VNC_AUTH_VENCRYPT_X509NONE:
208 return "vencrypt+x509+none";
209 case VNC_AUTH_VENCRYPT_X509VNC:
210 return "vencrypt+x509+vnc";
211 case VNC_AUTH_VENCRYPT_X509PLAIN:
212 return "vencrypt+x509+plain";
213 case VNC_AUTH_VENCRYPT_TLSSASL:
214 return "vencrypt+tls+sasl";
215 case VNC_AUTH_VENCRYPT_X509SASL:
216 return "vencrypt+x509+sasl";
226 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
231 if (!vd->listener || !vd->listener->nsioc) {
235 info = g_malloc0(sizeof(*info));
236 vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
237 qapi_VncServerInfo_base(info), &err);
238 info->has_auth = true;
239 info->auth = g_strdup(vnc_auth_name(vd));
241 qapi_free_VncServerInfo(info);
248 static void vnc_client_cache_auth(VncState *client)
255 client->info->x509_dname =
256 qcrypto_tls_session_get_peer_name(client->tls);
257 client->info->has_x509_dname =
258 client->info->x509_dname != NULL;
260 #ifdef CONFIG_VNC_SASL
261 if (client->sasl.conn &&
262 client->sasl.username) {
263 client->info->has_sasl_username = true;
264 client->info->sasl_username = g_strdup(client->sasl.username);
269 static void vnc_client_cache_addr(VncState *client)
273 client->info = g_malloc0(sizeof(*client->info));
274 vnc_init_basic_info_from_remote_addr(client->sioc,
275 qapi_VncClientInfo_base(client->info),
278 qapi_free_VncClientInfo(client->info);
284 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
292 si = vnc_server_info_get(vs->vd);
298 case QAPI_EVENT_VNC_CONNECTED:
299 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
301 case QAPI_EVENT_VNC_INITIALIZED:
302 qapi_event_send_vnc_initialized(si, vs->info);
304 case QAPI_EVENT_VNC_DISCONNECTED:
305 qapi_event_send_vnc_disconnected(si, vs->info);
311 qapi_free_VncServerInfo(si);
314 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
319 info = g_malloc0(sizeof(*info));
321 vnc_init_basic_info_from_remote_addr(client->sioc,
322 qapi_VncClientInfo_base(info),
326 qapi_free_VncClientInfo(info);
330 info->websocket = client->websocket;
333 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
334 info->has_x509_dname = info->x509_dname != NULL;
336 #ifdef CONFIG_VNC_SASL
337 if (client->sasl.conn && client->sasl.username) {
338 info->has_sasl_username = true;
339 info->sasl_username = g_strdup(client->sasl.username);
346 static VncDisplay *vnc_display_find(const char *id)
351 return QTAILQ_FIRST(&vnc_displays);
353 QTAILQ_FOREACH(vd, &vnc_displays, next) {
354 if (strcmp(id, vd->id) == 0) {
361 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
363 VncClientInfoList *cinfo, *prev = NULL;
366 QTAILQ_FOREACH(client, &vd->clients, next) {
367 cinfo = g_new0(VncClientInfoList, 1);
368 cinfo->value = qmp_query_vnc_client(client);
375 VncInfo *qmp_query_vnc(Error **errp)
377 VncInfo *info = g_malloc0(sizeof(*info));
378 VncDisplay *vd = vnc_display_find(NULL);
379 SocketAddress *addr = NULL;
381 if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
382 info->enabled = false;
384 info->enabled = true;
386 /* for compatibility with the original command */
387 info->has_clients = true;
388 info->clients = qmp_query_client_list(vd);
390 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
396 switch (addr->type) {
397 case SOCKET_ADDRESS_TYPE_INET:
398 info->host = g_strdup(addr->u.inet.host);
399 info->service = g_strdup(addr->u.inet.port);
400 if (addr->u.inet.ipv6) {
401 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
403 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
407 case SOCKET_ADDRESS_TYPE_UNIX:
408 info->host = g_strdup("");
409 info->service = g_strdup(addr->u.q_unix.path);
410 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
413 case SOCKET_ADDRESS_TYPE_VSOCK:
414 case SOCKET_ADDRESS_TYPE_FD:
415 error_setg(errp, "Unsupported socket address type %s",
416 SocketAddressType_str(addr->type));
422 info->has_host = true;
423 info->has_service = true;
424 info->has_family = true;
426 info->has_auth = true;
427 info->auth = g_strdup(vnc_auth_name(vd));
430 qapi_free_SocketAddress(addr);
434 qapi_free_SocketAddress(addr);
435 qapi_free_VncInfo(info);
440 static void qmp_query_auth(int auth, int subauth,
441 VncPrimaryAuth *qmp_auth,
442 VncVencryptSubAuth *qmp_vencrypt,
443 bool *qmp_has_vencrypt);
445 static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
449 VncServerInfo2List *prev)
451 VncServerInfo2List *list;
452 VncServerInfo2 *info;
456 addr = qio_channel_socket_get_local_address(ioc, &err);
462 info = g_new0(VncServerInfo2, 1);
463 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
464 qapi_free_SocketAddress(addr);
466 qapi_free_VncServerInfo2(info);
470 info->websocket = websocket;
472 qmp_query_auth(auth, subauth, &info->auth,
473 &info->vencrypt, &info->has_vencrypt);
475 list = g_new0(VncServerInfo2List, 1);
481 static void qmp_query_auth(int auth, int subauth,
482 VncPrimaryAuth *qmp_auth,
483 VncVencryptSubAuth *qmp_vencrypt,
484 bool *qmp_has_vencrypt)
488 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
491 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
494 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
497 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
500 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
503 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
505 case VNC_AUTH_VENCRYPT:
506 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
507 *qmp_has_vencrypt = true;
509 case VNC_AUTH_VENCRYPT_PLAIN:
510 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
512 case VNC_AUTH_VENCRYPT_TLSNONE:
513 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
515 case VNC_AUTH_VENCRYPT_TLSVNC:
516 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
518 case VNC_AUTH_VENCRYPT_TLSPLAIN:
519 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
521 case VNC_AUTH_VENCRYPT_X509NONE:
522 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
524 case VNC_AUTH_VENCRYPT_X509VNC:
525 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
527 case VNC_AUTH_VENCRYPT_X509PLAIN:
528 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
530 case VNC_AUTH_VENCRYPT_TLSSASL:
531 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
533 case VNC_AUTH_VENCRYPT_X509SASL:
534 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
537 *qmp_has_vencrypt = false;
542 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
546 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
551 VncInfo2List *qmp_query_vnc_servers(Error **errp)
553 VncInfo2List *item, *prev = NULL;
559 QTAILQ_FOREACH(vd, &vnc_displays, next) {
560 info = g_new0(VncInfo2, 1);
561 info->id = g_strdup(vd->id);
562 info->clients = qmp_query_client_list(vd);
563 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
564 &info->vencrypt, &info->has_vencrypt);
566 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
568 info->has_display = true;
569 info->display = g_strdup(dev->id);
571 for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
572 info->server = qmp_query_server_entry(
573 vd->listener->sioc[i], false, vd->auth, vd->subauth,
576 for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
577 info->server = qmp_query_server_entry(
578 vd->wslistener->sioc[i], true, vd->ws_auth,
579 vd->ws_subauth, info->server);
582 item = g_new0(VncInfo2List, 1);
591 1) Get the queue working for IO.
592 2) there is some weirdness when using the -S option (the screen is grey
593 and not totally invalidated
594 3) resolutions > 1024
597 static int vnc_update_client(VncState *vs, int has_dirty);
598 static void vnc_disconnect_start(VncState *vs);
600 static void vnc_colordepth(VncState *vs);
601 static void framebuffer_update_request(VncState *vs, int incremental,
602 int x_position, int y_position,
604 static void vnc_refresh(DisplayChangeListener *dcl);
605 static int vnc_refresh_server_surface(VncDisplay *vd);
607 static int vnc_width(VncDisplay *vd)
609 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
610 VNC_DIRTY_PIXELS_PER_BIT));
613 static int vnc_height(VncDisplay *vd)
615 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
618 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
619 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
621 int x, int y, int w, int h)
623 int width = vnc_width(vd);
624 int height = vnc_height(vd);
626 /* this is needed this to ensure we updated all affected
627 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
628 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
629 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
633 w = MIN(x + w, width) - x;
634 h = MIN(y + h, height);
637 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
638 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
642 static void vnc_dpy_update(DisplayChangeListener *dcl,
643 int x, int y, int w, int h)
645 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
646 struct VncSurface *s = &vd->guest;
648 vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
651 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
654 vnc_write_u16(vs, x);
655 vnc_write_u16(vs, y);
656 vnc_write_u16(vs, w);
657 vnc_write_u16(vs, h);
659 vnc_write_s32(vs, encoding);
663 static void vnc_desktop_resize(VncState *vs)
665 if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
668 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
669 vs->client_height == pixman_image_get_height(vs->vd->server)) {
673 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
674 pixman_image_get_width(vs->vd->server) >= 0);
675 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
676 pixman_image_get_height(vs->vd->server) >= 0);
677 vs->client_width = pixman_image_get_width(vs->vd->server);
678 vs->client_height = pixman_image_get_height(vs->vd->server);
680 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
682 vnc_write_u16(vs, 1); /* number of rects */
683 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
684 VNC_ENCODING_DESKTOPRESIZE);
685 vnc_unlock_output(vs);
689 static void vnc_abort_display_jobs(VncDisplay *vd)
693 QTAILQ_FOREACH(vs, &vd->clients, next) {
696 vnc_unlock_output(vs);
698 QTAILQ_FOREACH(vs, &vd->clients, next) {
701 QTAILQ_FOREACH(vs, &vd->clients, next) {
704 vnc_unlock_output(vs);
708 int vnc_server_fb_stride(VncDisplay *vd)
710 return pixman_image_get_stride(vd->server);
713 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
717 ptr = (uint8_t *)pixman_image_get_data(vd->server);
718 ptr += y * vnc_server_fb_stride(vd);
719 ptr += x * VNC_SERVER_FB_BYTES;
723 static void vnc_update_server_surface(VncDisplay *vd)
727 qemu_pixman_image_unref(vd->server);
730 if (QTAILQ_EMPTY(&vd->clients)) {
734 width = vnc_width(vd);
735 height = vnc_height(vd);
736 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
740 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
741 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
745 static bool vnc_check_pageflip(DisplaySurface *s1,
748 return (s1 != NULL &&
750 surface_width(s1) == surface_width(s2) &&
751 surface_height(s1) == surface_height(s2) &&
752 surface_format(s1) == surface_format(s2));
756 static void vnc_dpy_switch(DisplayChangeListener *dcl,
757 DisplaySurface *surface)
759 static const char placeholder_msg[] =
760 "Display output is not active.";
761 static DisplaySurface *placeholder;
762 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
763 bool pageflip = vnc_check_pageflip(vd->ds, surface);
766 if (surface == NULL) {
767 if (placeholder == NULL) {
768 placeholder = qemu_create_message_surface(640, 480, placeholder_msg);
770 surface = placeholder;
773 vnc_abort_display_jobs(vd);
777 qemu_pixman_image_unref(vd->guest.fb);
778 vd->guest.fb = pixman_image_ref(surface->image);
779 vd->guest.format = surface->format;
782 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
783 surface_width(surface),
784 surface_height(surface));
789 vnc_update_server_surface(vd);
791 QTAILQ_FOREACH(vs, &vd->clients, next) {
793 vnc_desktop_resize(vs);
794 if (vs->vd->cursor) {
795 vnc_cursor_define(vs);
797 memset(vs->dirty, 0x00, sizeof(vs->dirty));
798 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
801 vnc_update_throttle_offset(vs);
806 static void vnc_write_pixels_copy(VncState *vs,
807 void *pixels, int size)
809 vnc_write(vs, pixels, size);
812 /* slowest but generic code. */
813 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
817 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
818 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
819 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
820 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
822 # error need some bits here if you change VNC_SERVER_FB_FORMAT
824 v = (r << vs->client_pf.rshift) |
825 (g << vs->client_pf.gshift) |
826 (b << vs->client_pf.bshift);
827 switch (vs->client_pf.bytes_per_pixel) {
857 static void vnc_write_pixels_generic(VncState *vs,
858 void *pixels1, int size)
862 if (VNC_SERVER_FB_BYTES == 4) {
863 uint32_t *pixels = pixels1;
866 for (i = 0; i < n; i++) {
867 vnc_convert_pixel(vs, buf, pixels[i]);
868 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
873 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
877 VncDisplay *vd = vs->vd;
879 row = vnc_server_fb_ptr(vd, x, y);
880 for (i = 0; i < h; i++) {
881 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
882 row += vnc_server_fb_stride(vd);
887 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
890 bool encode_raw = false;
891 size_t saved_offs = vs->output.offset;
893 switch(vs->vnc_encoding) {
894 case VNC_ENCODING_ZLIB:
895 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
897 case VNC_ENCODING_HEXTILE:
898 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
899 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
901 case VNC_ENCODING_TIGHT:
902 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
904 case VNC_ENCODING_TIGHT_PNG:
905 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
907 case VNC_ENCODING_ZRLE:
908 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
910 case VNC_ENCODING_ZYWRLE:
911 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
918 /* If the client has the same pixel format as our internal buffer and
919 * a RAW encoding would need less space fall back to RAW encoding to
920 * save bandwidth and processing power in the client. */
921 if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
922 12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
923 vs->output.offset = saved_offs;
928 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
929 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
935 static void vnc_mouse_set(DisplayChangeListener *dcl,
936 int x, int y, int visible)
938 /* can we ask the client(s) to move the pointer ??? */
941 static int vnc_cursor_define(VncState *vs)
943 QEMUCursor *c = vs->vd->cursor;
946 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
948 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
949 vnc_write_u8(vs, 0); /* padding */
950 vnc_write_u16(vs, 1); /* # of rects */
951 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
952 VNC_ENCODING_RICH_CURSOR);
953 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
954 vnc_write_pixels_generic(vs, c->data, isize);
955 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
956 vnc_unlock_output(vs);
962 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
965 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
968 cursor_put(vd->cursor);
969 g_free(vd->cursor_mask);
972 cursor_get(vd->cursor);
973 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
974 vd->cursor_mask = g_malloc0(vd->cursor_msize);
975 cursor_get_mono_mask(c, 0, vd->cursor_mask);
977 QTAILQ_FOREACH(vs, &vd->clients, next) {
978 vnc_cursor_define(vs);
982 static int find_and_clear_dirty_height(VncState *vs,
983 int y, int last_x, int x, int height)
987 for (h = 1; h < (height - y); h++) {
988 if (!test_bit(last_x, vs->dirty[y + h])) {
991 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
998 * Figure out how much pending data we should allow in the output
999 * buffer before we throttle incremental display updates, and/or
1000 * drop audio samples.
1002 * We allow for equiv of 1 full display's worth of FB updates,
1003 * and 1 second of audio samples. If audio backlog was larger
1004 * than that the client would already suffering awful audio
1005 * glitches, so dropping samples is no worse really).
1007 static void vnc_update_throttle_offset(VncState *vs)
1010 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1012 if (vs->audio_cap) {
1014 switch (vs->as.fmt) {
1029 offset += vs->as.freq * bps * vs->as.nchannels;
1032 /* Put a floor of 1MB on offset, so that if we have a large pending
1033 * buffer and the display is resized to a small size & back again
1034 * we don't suddenly apply a tiny send limit
1036 offset = MAX(offset, 1024 * 1024);
1038 if (vs->throttle_output_offset != offset) {
1039 trace_vnc_client_throttle_threshold(
1040 vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1041 vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1044 vs->throttle_output_offset = offset;
1047 static bool vnc_should_update(VncState *vs)
1049 switch (vs->update) {
1050 case VNC_STATE_UPDATE_NONE:
1052 case VNC_STATE_UPDATE_INCREMENTAL:
1053 /* Only allow incremental updates if the pending send queue
1054 * is less than the permitted threshold, and the job worker
1055 * is completely idle.
1057 if (vs->output.offset < vs->throttle_output_offset &&
1058 vs->job_update == VNC_STATE_UPDATE_NONE) {
1061 trace_vnc_client_throttle_incremental(
1062 vs, vs->ioc, vs->job_update, vs->output.offset);
1064 case VNC_STATE_UPDATE_FORCE:
1065 /* Only allow forced updates if the pending send queue
1066 * does not contain a previous forced update, and the
1067 * job worker is completely idle.
1069 * Note this means we'll queue a forced update, even if
1070 * the output buffer size is otherwise over the throttle
1073 if (vs->force_update_offset == 0 &&
1074 vs->job_update == VNC_STATE_UPDATE_NONE) {
1077 trace_vnc_client_throttle_forced(
1078 vs, vs->ioc, vs->job_update, vs->force_update_offset);
1084 static int vnc_update_client(VncState *vs, int has_dirty)
1086 VncDisplay *vd = vs->vd;
1092 if (vs->disconnecting) {
1093 vnc_disconnect_finish(vs);
1097 vs->has_dirty += has_dirty;
1098 if (!vnc_should_update(vs)) {
1102 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1107 * Send screen updates to the vnc client using the server
1108 * surface and server dirty map. guest surface updates
1109 * happening in parallel don't disturb us, the next pass will
1110 * send them to the client.
1112 job = vnc_job_new(vs);
1114 height = pixman_image_get_height(vd->server);
1115 width = pixman_image_get_width(vd->server);
1121 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1122 height * VNC_DIRTY_BPL(vs),
1123 y * VNC_DIRTY_BPL(vs));
1124 if (offset == height * VNC_DIRTY_BPL(vs)) {
1125 /* no more dirty bits */
1128 y = offset / VNC_DIRTY_BPL(vs);
1129 x = offset % VNC_DIRTY_BPL(vs);
1130 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1131 VNC_DIRTY_BPL(vs), x);
1132 bitmap_clear(vs->dirty[y], x, x2 - x);
1133 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1134 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1136 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1137 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1139 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1147 vs->job_update = vs->update;
1148 vs->update = VNC_STATE_UPDATE_NONE;
1155 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1157 VncState *vs = opaque;
1159 assert(vs->magic == VNC_MAGIC);
1161 case AUD_CNOTIFY_DISABLE:
1162 vnc_lock_output(vs);
1163 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1164 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1165 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1166 vnc_unlock_output(vs);
1170 case AUD_CNOTIFY_ENABLE:
1171 vnc_lock_output(vs);
1172 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1173 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1174 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1175 vnc_unlock_output(vs);
1181 static void audio_capture_destroy(void *opaque)
1185 static void audio_capture(void *opaque, void *buf, int size)
1187 VncState *vs = opaque;
1189 assert(vs->magic == VNC_MAGIC);
1190 vnc_lock_output(vs);
1191 if (vs->output.offset < vs->throttle_output_offset) {
1192 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1193 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1194 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1195 vnc_write_u32(vs, size);
1196 vnc_write(vs, buf, size);
1198 trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1200 vnc_unlock_output(vs);
1204 static void audio_add(VncState *vs)
1206 struct audio_capture_ops ops;
1208 if (vs->audio_cap) {
1209 error_report("audio already running");
1213 ops.notify = audio_capture_notify;
1214 ops.destroy = audio_capture_destroy;
1215 ops.capture = audio_capture;
1217 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1218 if (!vs->audio_cap) {
1219 error_report("Failed to add audio capture");
1223 static void audio_del(VncState *vs)
1225 if (vs->audio_cap) {
1226 AUD_del_capture(vs->audio_cap, vs);
1227 vs->audio_cap = NULL;
1231 static void vnc_disconnect_start(VncState *vs)
1233 if (vs->disconnecting) {
1236 trace_vnc_client_disconnect_start(vs, vs->ioc);
1237 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1239 g_source_remove(vs->ioc_tag);
1242 qio_channel_close(vs->ioc, NULL);
1243 vs->disconnecting = TRUE;
1246 void vnc_disconnect_finish(VncState *vs)
1250 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1252 vnc_jobs_join(vs); /* Wait encoding jobs */
1254 vnc_lock_output(vs);
1255 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1257 buffer_free(&vs->input);
1258 buffer_free(&vs->output);
1260 qapi_free_VncClientInfo(vs->info);
1263 vnc_tight_clear(vs);
1266 #ifdef CONFIG_VNC_SASL
1267 vnc_sasl_client_cleanup(vs);
1268 #endif /* CONFIG_VNC_SASL */
1270 qkbd_state_lift_all_keys(vs->vd->kbd);
1272 if (vs->mouse_mode_notifier.notify != NULL) {
1273 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1275 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1276 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1277 /* last client gone */
1278 vnc_update_server_surface(vs->vd);
1281 vnc_unlock_output(vs);
1283 qemu_mutex_destroy(&vs->output_mutex);
1284 if (vs->bh != NULL) {
1285 qemu_bh_delete(vs->bh);
1287 buffer_free(&vs->jobs_buffer);
1289 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1290 g_free(vs->lossy_rect[i]);
1292 g_free(vs->lossy_rect);
1294 object_unref(OBJECT(vs->ioc));
1296 object_unref(OBJECT(vs->sioc));
1302 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
1306 trace_vnc_client_eof(vs, vs->ioc);
1307 vnc_disconnect_start(vs);
1308 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1309 trace_vnc_client_io_error(vs, vs->ioc,
1310 errp ? error_get_pretty(*errp) :
1312 vnc_disconnect_start(vs);
1325 void vnc_client_error(VncState *vs)
1327 VNC_DEBUG("Closing down client sock: protocol error\n");
1328 vnc_disconnect_start(vs);
1333 * Called to write a chunk of data to the client socket. The data may
1334 * be the raw data, or may have already been encoded by SASL.
1335 * The data will be written either straight onto the socket, or
1336 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1338 * NB, it is theoretically possible to have 2 layers of encryption,
1339 * both SASL, and this TLS layer. It is highly unlikely in practice
1340 * though, since SASL encryption will typically be a no-op if TLS
1343 * Returns the number of bytes written, which may be less than
1344 * the requested 'datalen' if the socket would block. Returns
1345 * 0 on I/O error, and disconnects the client socket.
1347 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1351 ret = qio_channel_write(
1352 vs->ioc, (const char *)data, datalen, &err);
1353 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1354 return vnc_client_io_error(vs, ret, &err);
1359 * Called to write buffered data to the client socket, when not
1360 * using any SASL SSF encryption layers. Will write as much data
1361 * as possible without blocking. If all buffered data is written,
1362 * will switch the FD poll() handler back to read monitoring.
1364 * Returns the number of bytes written, which may be less than
1365 * the buffered output data if the socket would block. Returns
1366 * 0 on I/O error, and disconnects the client socket.
1368 static size_t vnc_client_write_plain(VncState *vs)
1373 #ifdef CONFIG_VNC_SASL
1374 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1375 vs->output.buffer, vs->output.capacity, vs->output.offset,
1376 vs->sasl.waitWriteSSF);
1378 if (vs->sasl.conn &&
1380 vs->sasl.waitWriteSSF) {
1381 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1383 vs->sasl.waitWriteSSF -= ret;
1385 #endif /* CONFIG_VNC_SASL */
1386 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1390 if (ret >= vs->force_update_offset) {
1391 if (vs->force_update_offset != 0) {
1392 trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1394 vs->force_update_offset = 0;
1396 vs->force_update_offset -= ret;
1398 offset = vs->output.offset;
1399 buffer_advance(&vs->output, ret);
1400 if (offset >= vs->throttle_output_offset &&
1401 vs->output.offset < vs->throttle_output_offset) {
1402 trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1405 if (vs->output.offset == 0) {
1407 g_source_remove(vs->ioc_tag);
1409 vs->ioc_tag = qio_channel_add_watch(
1410 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1418 * First function called whenever there is data to be written to
1419 * the client socket. Will delegate actual work according to whether
1420 * SASL SSF layers are enabled (thus requiring encryption calls)
1422 static void vnc_client_write_locked(VncState *vs)
1424 #ifdef CONFIG_VNC_SASL
1425 if (vs->sasl.conn &&
1427 !vs->sasl.waitWriteSSF) {
1428 vnc_client_write_sasl(vs);
1430 #endif /* CONFIG_VNC_SASL */
1432 vnc_client_write_plain(vs);
1436 static void vnc_client_write(VncState *vs)
1438 assert(vs->magic == VNC_MAGIC);
1439 vnc_lock_output(vs);
1440 if (vs->output.offset) {
1441 vnc_client_write_locked(vs);
1442 } else if (vs->ioc != NULL) {
1444 g_source_remove(vs->ioc_tag);
1446 vs->ioc_tag = qio_channel_add_watch(
1447 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1449 vnc_unlock_output(vs);
1452 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1454 vs->read_handler = func;
1455 vs->read_handler_expect = expecting;
1460 * Called to read a chunk of data from the client socket. The data may
1461 * be the raw data, or may need to be further decoded by SASL.
1462 * The data will be read either straight from to the socket, or
1463 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1465 * NB, it is theoretically possible to have 2 layers of encryption,
1466 * both SASL, and this TLS layer. It is highly unlikely in practice
1467 * though, since SASL encryption will typically be a no-op if TLS
1470 * Returns the number of bytes read, which may be less than
1471 * the requested 'datalen' if the socket would block. Returns
1472 * 0 on I/O error or EOF, and disconnects the client socket.
1474 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1478 ret = qio_channel_read(
1479 vs->ioc, (char *)data, datalen, &err);
1480 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1481 return vnc_client_io_error(vs, ret, &err);
1486 * Called to read data from the client socket to the input buffer,
1487 * when not using any SASL SSF encryption layers. Will read as much
1488 * data as possible without blocking.
1490 * Returns the number of bytes read, which may be less than
1491 * the requested 'datalen' if the socket would block. Returns
1492 * 0 on I/O error or EOF, and disconnects the client socket.
1494 static size_t vnc_client_read_plain(VncState *vs)
1497 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1498 vs->input.buffer, vs->input.capacity, vs->input.offset);
1499 buffer_reserve(&vs->input, 4096);
1500 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1503 vs->input.offset += ret;
1507 static void vnc_jobs_bh(void *opaque)
1509 VncState *vs = opaque;
1511 assert(vs->magic == VNC_MAGIC);
1512 vnc_jobs_consume_buffer(vs);
1516 * First function called whenever there is more data to be read from
1517 * the client socket. Will delegate actual work according to whether
1518 * SASL SSF layers are enabled (thus requiring decryption calls)
1519 * Returns 0 on success, -1 if client disconnected
1521 static int vnc_client_read(VncState *vs)
1525 #ifdef CONFIG_VNC_SASL
1526 if (vs->sasl.conn && vs->sasl.runSSF)
1527 ret = vnc_client_read_sasl(vs);
1529 #endif /* CONFIG_VNC_SASL */
1530 ret = vnc_client_read_plain(vs);
1532 if (vs->disconnecting) {
1533 vnc_disconnect_finish(vs);
1539 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1540 size_t len = vs->read_handler_expect;
1543 ret = vs->read_handler(vs, vs->input.buffer, len);
1544 if (vs->disconnecting) {
1545 vnc_disconnect_finish(vs);
1550 buffer_advance(&vs->input, len);
1552 vs->read_handler_expect = ret;
1558 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1559 GIOCondition condition, void *opaque)
1561 VncState *vs = opaque;
1563 assert(vs->magic == VNC_MAGIC);
1564 if (condition & G_IO_IN) {
1565 if (vnc_client_read(vs) < 0) {
1566 /* vs is free()ed here */
1570 if (condition & G_IO_OUT) {
1571 vnc_client_write(vs);
1574 if (vs->disconnecting) {
1575 if (vs->ioc_tag != 0) {
1576 g_source_remove(vs->ioc_tag);
1585 * Scale factor to apply to vs->throttle_output_offset when checking for
1586 * hard limit. Worst case normal usage could be x2, if we have a complete
1587 * incremental update and complete forced update in the output buffer.
1588 * So x3 should be good enough, but we pick x5 to be conservative and thus
1589 * (hopefully) never trigger incorrectly.
1591 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1593 void vnc_write(VncState *vs, const void *data, size_t len)
1595 assert(vs->magic == VNC_MAGIC);
1596 if (vs->disconnecting) {
1599 /* Protection against malicious client/guest to prevent our output
1600 * buffer growing without bound if client stops reading data. This
1601 * should rarely trigger, because we have earlier throttling code
1602 * which stops issuing framebuffer updates and drops audio data
1603 * if the throttle_output_offset value is exceeded. So we only reach
1604 * this higher level if a huge number of pseudo-encodings get
1605 * triggered while data can't be sent on the socket.
1607 * NB throttle_output_offset can be zero during early protocol
1608 * handshake, or from the job thread's VncState clone
1610 if (vs->throttle_output_offset != 0 &&
1611 (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1612 vs->throttle_output_offset) {
1613 trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1614 vs->throttle_output_offset);
1615 vnc_disconnect_start(vs);
1618 buffer_reserve(&vs->output, len);
1620 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1622 g_source_remove(vs->ioc_tag);
1624 vs->ioc_tag = qio_channel_add_watch(
1625 vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1628 buffer_append(&vs->output, data, len);
1631 void vnc_write_s32(VncState *vs, int32_t value)
1633 vnc_write_u32(vs, *(uint32_t *)&value);
1636 void vnc_write_u32(VncState *vs, uint32_t value)
1640 buf[0] = (value >> 24) & 0xFF;
1641 buf[1] = (value >> 16) & 0xFF;
1642 buf[2] = (value >> 8) & 0xFF;
1643 buf[3] = value & 0xFF;
1645 vnc_write(vs, buf, 4);
1648 void vnc_write_u16(VncState *vs, uint16_t value)
1652 buf[0] = (value >> 8) & 0xFF;
1653 buf[1] = value & 0xFF;
1655 vnc_write(vs, buf, 2);
1658 void vnc_write_u8(VncState *vs, uint8_t value)
1660 vnc_write(vs, (char *)&value, 1);
1663 void vnc_flush(VncState *vs)
1665 vnc_lock_output(vs);
1666 if (vs->ioc != NULL && vs->output.offset) {
1667 vnc_client_write_locked(vs);
1669 if (vs->disconnecting) {
1670 if (vs->ioc_tag != 0) {
1671 g_source_remove(vs->ioc_tag);
1675 vnc_unlock_output(vs);
1678 static uint8_t read_u8(uint8_t *data, size_t offset)
1680 return data[offset];
1683 static uint16_t read_u16(uint8_t *data, size_t offset)
1685 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1688 static int32_t read_s32(uint8_t *data, size_t offset)
1690 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1691 (data[offset + 2] << 8) | data[offset + 3]);
1694 uint32_t read_u32(uint8_t *data, size_t offset)
1696 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1697 (data[offset + 2] << 8) | data[offset + 3]);
1700 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1704 static void check_pointer_type_change(Notifier *notifier, void *data)
1706 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1707 int absolute = qemu_input_is_absolute();
1709 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1710 vnc_lock_output(vs);
1711 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1712 vnc_write_u8(vs, 0);
1713 vnc_write_u16(vs, 1);
1714 vnc_framebuffer_update(vs, absolute, 0,
1715 pixman_image_get_width(vs->vd->server),
1716 pixman_image_get_height(vs->vd->server),
1717 VNC_ENCODING_POINTER_TYPE_CHANGE);
1718 vnc_unlock_output(vs);
1721 vs->absolute = absolute;
1724 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1726 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1727 [INPUT_BUTTON_LEFT] = 0x01,
1728 [INPUT_BUTTON_MIDDLE] = 0x02,
1729 [INPUT_BUTTON_RIGHT] = 0x04,
1730 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1731 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1733 QemuConsole *con = vs->vd->dcl.con;
1734 int width = pixman_image_get_width(vs->vd->server);
1735 int height = pixman_image_get_height(vs->vd->server);
1737 if (vs->last_bmask != button_mask) {
1738 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1739 vs->last_bmask = button_mask;
1743 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1744 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1745 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1746 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1747 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1749 if (vs->last_x != -1) {
1750 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1751 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1756 qemu_input_event_sync();
1759 static void press_key(VncState *vs, QKeyCode qcode)
1761 qkbd_state_key_event(vs->vd->kbd, qcode, true);
1762 qkbd_state_key_event(vs->vd->kbd, qcode, false);
1765 static void vnc_led_state_change(VncState *vs)
1767 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1771 vnc_lock_output(vs);
1772 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1773 vnc_write_u8(vs, 0);
1774 vnc_write_u16(vs, 1);
1775 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1776 vnc_write_u8(vs, vs->vd->ledstate);
1777 vnc_unlock_output(vs);
1781 static void kbd_leds(void *opaque, int ledstate)
1783 VncDisplay *vd = opaque;
1786 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1787 (ledstate & QEMU_NUM_LOCK_LED),
1788 (ledstate & QEMU_SCROLL_LOCK_LED));
1790 if (ledstate == vd->ledstate) {
1794 vd->ledstate = ledstate;
1796 QTAILQ_FOREACH(client, &vd->clients, next) {
1797 vnc_led_state_change(client);
1801 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1803 QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1805 /* QEMU console switch */
1807 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1808 if (vs->vd->dcl.con == NULL && down &&
1809 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1810 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1811 /* Reset the modifiers sent to the current console */
1812 qkbd_state_lift_all_keys(vs->vd->kbd);
1813 console_select(qcode - Q_KEY_CODE_1);
1820 /* Turn off the lock state sync logic if the client support the led
1823 if (down && vs->vd->lock_key_sync &&
1824 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1825 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1826 /* If the numlock state needs to change then simulate an additional
1827 keypress before sending this one. This will happen if the user
1828 toggles numlock away from the VNC window.
1830 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1831 if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1832 trace_vnc_key_sync_numlock(true);
1833 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1836 if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1837 trace_vnc_key_sync_numlock(false);
1838 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1843 if (down && vs->vd->lock_key_sync &&
1844 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1845 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1846 /* If the capslock state needs to change then simulate an additional
1847 keypress before sending this one. This will happen if the user
1848 toggles capslock away from the VNC window.
1850 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1851 bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1852 bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1854 if (uppercase == shift) {
1855 trace_vnc_key_sync_capslock(false);
1856 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1859 if (uppercase != shift) {
1860 trace_vnc_key_sync_capslock(true);
1861 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1866 qkbd_state_key_event(vs->vd->kbd, qcode, down);
1867 if (!qemu_console_is_graphic(NULL)) {
1868 bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1869 bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1870 /* QEMU console emulation */
1873 case 0x2a: /* Left Shift */
1874 case 0x36: /* Right Shift */
1875 case 0x1d: /* Left CTRL */
1876 case 0x9d: /* Right CTRL */
1877 case 0x38: /* Left ALT */
1878 case 0xb8: /* Right ALT */
1881 kbd_put_keysym(QEMU_KEY_UP);
1884 kbd_put_keysym(QEMU_KEY_DOWN);
1887 kbd_put_keysym(QEMU_KEY_LEFT);
1890 kbd_put_keysym(QEMU_KEY_RIGHT);
1893 kbd_put_keysym(QEMU_KEY_DELETE);
1896 kbd_put_keysym(QEMU_KEY_HOME);
1899 kbd_put_keysym(QEMU_KEY_END);
1902 kbd_put_keysym(QEMU_KEY_PAGEUP);
1905 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1909 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1912 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1915 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1918 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1921 kbd_put_keysym('5');
1924 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1927 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1930 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1933 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1936 kbd_put_keysym('0');
1939 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1943 kbd_put_keysym('/');
1946 kbd_put_keysym('*');
1949 kbd_put_keysym('-');
1952 kbd_put_keysym('+');
1955 kbd_put_keysym('\n');
1960 kbd_put_keysym(sym & 0x1f);
1962 kbd_put_keysym(sym);
1970 static const char *code2name(int keycode)
1972 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
1975 static void key_event(VncState *vs, int down, uint32_t sym)
1980 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1981 lsym = lsym - 'A' + 'a';
1984 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
1985 vs->vd->kbd, down) & SCANCODE_KEYMASK;
1986 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1987 do_key_event(vs, down, keycode, sym);
1990 static void ext_key_event(VncState *vs, int down,
1991 uint32_t sym, uint16_t keycode)
1993 /* if the user specifies a keyboard layout, always use it */
1994 if (keyboard_layout) {
1995 key_event(vs, down, sym);
1997 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
1998 do_key_event(vs, down, keycode, sym);
2002 static void framebuffer_update_request(VncState *vs, int incremental,
2003 int x, int y, int w, int h)
2006 if (vs->update != VNC_STATE_UPDATE_FORCE) {
2007 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2010 vs->update = VNC_STATE_UPDATE_FORCE;
2011 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2015 static void send_ext_key_event_ack(VncState *vs)
2017 vnc_lock_output(vs);
2018 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2019 vnc_write_u8(vs, 0);
2020 vnc_write_u16(vs, 1);
2021 vnc_framebuffer_update(vs, 0, 0,
2022 pixman_image_get_width(vs->vd->server),
2023 pixman_image_get_height(vs->vd->server),
2024 VNC_ENCODING_EXT_KEY_EVENT);
2025 vnc_unlock_output(vs);
2029 static void send_ext_audio_ack(VncState *vs)
2031 vnc_lock_output(vs);
2032 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2033 vnc_write_u8(vs, 0);
2034 vnc_write_u16(vs, 1);
2035 vnc_framebuffer_update(vs, 0, 0,
2036 pixman_image_get_width(vs->vd->server),
2037 pixman_image_get_height(vs->vd->server),
2038 VNC_ENCODING_AUDIO);
2039 vnc_unlock_output(vs);
2043 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2046 unsigned int enc = 0;
2049 vs->vnc_encoding = 0;
2050 vs->tight.compression = 9;
2051 vs->tight.quality = -1; /* Lossless by default */
2055 * Start from the end because the encodings are sent in order of preference.
2056 * This way the preferred encoding (first encoding defined in the array)
2057 * will be set at the end of the loop.
2059 for (i = n_encodings - 1; i >= 0; i--) {
2062 case VNC_ENCODING_RAW:
2063 vs->vnc_encoding = enc;
2065 case VNC_ENCODING_COPYRECT:
2066 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2068 case VNC_ENCODING_HEXTILE:
2069 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2070 vs->vnc_encoding = enc;
2072 case VNC_ENCODING_TIGHT:
2073 vs->features |= VNC_FEATURE_TIGHT_MASK;
2074 vs->vnc_encoding = enc;
2076 #ifdef CONFIG_VNC_PNG
2077 case VNC_ENCODING_TIGHT_PNG:
2078 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2079 vs->vnc_encoding = enc;
2082 case VNC_ENCODING_ZLIB:
2083 vs->features |= VNC_FEATURE_ZLIB_MASK;
2084 vs->vnc_encoding = enc;
2086 case VNC_ENCODING_ZRLE:
2087 vs->features |= VNC_FEATURE_ZRLE_MASK;
2088 vs->vnc_encoding = enc;
2090 case VNC_ENCODING_ZYWRLE:
2091 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2092 vs->vnc_encoding = enc;
2094 case VNC_ENCODING_DESKTOPRESIZE:
2095 vs->features |= VNC_FEATURE_RESIZE_MASK;
2097 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2098 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2100 case VNC_ENCODING_RICH_CURSOR:
2101 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2102 if (vs->vd->cursor) {
2103 vnc_cursor_define(vs);
2106 case VNC_ENCODING_EXT_KEY_EVENT:
2107 send_ext_key_event_ack(vs);
2109 case VNC_ENCODING_AUDIO:
2110 send_ext_audio_ack(vs);
2112 case VNC_ENCODING_WMVi:
2113 vs->features |= VNC_FEATURE_WMVI_MASK;
2115 case VNC_ENCODING_LED_STATE:
2116 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2118 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2119 vs->tight.compression = (enc & 0x0F);
2121 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2122 if (vs->vd->lossy) {
2123 vs->tight.quality = (enc & 0x0F);
2127 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2131 vnc_desktop_resize(vs);
2132 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2133 vnc_led_state_change(vs);
2136 static void set_pixel_conversion(VncState *vs)
2138 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2140 if (fmt == VNC_SERVER_FB_FORMAT) {
2141 vs->write_pixels = vnc_write_pixels_copy;
2142 vnc_hextile_set_pixel_conversion(vs, 0);
2144 vs->write_pixels = vnc_write_pixels_generic;
2145 vnc_hextile_set_pixel_conversion(vs, 1);
2149 static void send_color_map(VncState *vs)
2153 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2154 vnc_write_u8(vs, 0); /* padding */
2155 vnc_write_u16(vs, 0); /* first color */
2156 vnc_write_u16(vs, 256); /* # of colors */
2158 for (i = 0; i < 256; i++) {
2159 PixelFormat *pf = &vs->client_pf;
2161 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2162 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2163 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2167 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2168 int big_endian_flag, int true_color_flag,
2169 int red_max, int green_max, int blue_max,
2170 int red_shift, int green_shift, int blue_shift)
2172 if (!true_color_flag) {
2173 /* Expose a reasonable default 256 color map */
2183 switch (bits_per_pixel) {
2189 vnc_client_error(vs);
2193 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2194 vs->client_pf.rbits = ctpopl(red_max);
2195 vs->client_pf.rshift = red_shift;
2196 vs->client_pf.rmask = red_max << red_shift;
2197 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2198 vs->client_pf.gbits = ctpopl(green_max);
2199 vs->client_pf.gshift = green_shift;
2200 vs->client_pf.gmask = green_max << green_shift;
2201 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2202 vs->client_pf.bbits = ctpopl(blue_max);
2203 vs->client_pf.bshift = blue_shift;
2204 vs->client_pf.bmask = blue_max << blue_shift;
2205 vs->client_pf.bits_per_pixel = bits_per_pixel;
2206 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2207 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2208 vs->client_be = big_endian_flag;
2210 if (!true_color_flag) {
2214 set_pixel_conversion(vs);
2216 graphic_hw_invalidate(vs->vd->dcl.con);
2217 graphic_hw_update(vs->vd->dcl.con);
2220 static void pixel_format_message (VncState *vs) {
2221 char pad[3] = { 0, 0, 0 };
2223 vs->client_pf = qemu_default_pixelformat(32);
2225 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2226 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2228 #ifdef HOST_WORDS_BIGENDIAN
2229 vnc_write_u8(vs, 1); /* big-endian-flag */
2231 vnc_write_u8(vs, 0); /* big-endian-flag */
2233 vnc_write_u8(vs, 1); /* true-color-flag */
2234 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2235 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2236 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2237 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2238 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2239 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2240 vnc_write(vs, pad, 3); /* padding */
2242 vnc_hextile_set_pixel_conversion(vs, 0);
2243 vs->write_pixels = vnc_write_pixels_copy;
2246 static void vnc_colordepth(VncState *vs)
2248 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2249 /* Sending a WMVi message to notify the client*/
2250 vnc_lock_output(vs);
2251 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2252 vnc_write_u8(vs, 0);
2253 vnc_write_u16(vs, 1); /* number of rects */
2254 vnc_framebuffer_update(vs, 0, 0,
2255 pixman_image_get_width(vs->vd->server),
2256 pixman_image_get_height(vs->vd->server),
2258 pixel_format_message(vs);
2259 vnc_unlock_output(vs);
2262 set_pixel_conversion(vs);
2266 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2271 VncDisplay *vd = vs->vd;
2274 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2278 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2282 set_pixel_format(vs, read_u8(data, 4),
2283 read_u8(data, 6), read_u8(data, 7),
2284 read_u16(data, 8), read_u16(data, 10),
2285 read_u16(data, 12), read_u8(data, 14),
2286 read_u8(data, 15), read_u8(data, 16));
2288 case VNC_MSG_CLIENT_SET_ENCODINGS:
2293 limit = read_u16(data, 2);
2295 return 4 + (limit * 4);
2297 limit = read_u16(data, 2);
2299 for (i = 0; i < limit; i++) {
2300 int32_t val = read_s32(data, 4 + (i * 4));
2301 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2304 set_encodings(vs, (int32_t *)(data + 4), limit);
2306 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2310 framebuffer_update_request(vs,
2311 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2312 read_u16(data, 6), read_u16(data, 8));
2314 case VNC_MSG_CLIENT_KEY_EVENT:
2318 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2320 case VNC_MSG_CLIENT_POINTER_EVENT:
2324 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2326 case VNC_MSG_CLIENT_CUT_TEXT:
2331 uint32_t dlen = read_u32(data, 4);
2332 if (dlen > (1 << 20)) {
2333 error_report("vnc: client_cut_text msg payload has %u bytes"
2334 " which exceeds our limit of 1MB.", dlen);
2335 vnc_client_error(vs);
2343 client_cut_text(vs, read_u32(data, 4), data + 8);
2345 case VNC_MSG_CLIENT_QEMU:
2349 switch (read_u8(data, 1)) {
2350 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2354 ext_key_event(vs, read_u16(data, 2),
2355 read_u32(data, 4), read_u32(data, 8));
2357 case VNC_MSG_CLIENT_QEMU_AUDIO:
2361 switch (read_u16 (data, 2)) {
2362 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2365 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2368 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2371 switch (read_u8(data, 4)) {
2372 case 0: vs->as.fmt = AUD_FMT_U8; break;
2373 case 1: vs->as.fmt = AUD_FMT_S8; break;
2374 case 2: vs->as.fmt = AUD_FMT_U16; break;
2375 case 3: vs->as.fmt = AUD_FMT_S16; break;
2376 case 4: vs->as.fmt = AUD_FMT_U32; break;
2377 case 5: vs->as.fmt = AUD_FMT_S32; break;
2379 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2380 vnc_client_error(vs);
2383 vs->as.nchannels = read_u8(data, 5);
2384 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2385 VNC_DEBUG("Invalid audio channel count %d\n",
2387 vnc_client_error(vs);
2390 freq = read_u32(data, 6);
2391 /* No official limit for protocol, but 48khz is a sensible
2392 * upper bound for trustworthy clients, and this limit
2393 * protects calculations involving 'vs->as.freq' later.
2396 VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2397 vnc_client_error(vs);
2403 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2404 vnc_client_error(vs);
2410 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2411 vnc_client_error(vs);
2416 VNC_DEBUG("Msg: %d\n", data[0]);
2417 vnc_client_error(vs);
2421 vnc_update_throttle_offset(vs);
2422 vnc_read_when(vs, protocol_client_msg, 1);
2426 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2432 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2433 switch (vs->vd->share_policy) {
2434 case VNC_SHARE_POLICY_IGNORE:
2436 * Ignore the shared flag. Nothing to do here.
2438 * Doesn't conform to the rfb spec but is traditional qemu
2439 * behavior, thus left here as option for compatibility
2443 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2445 * Policy: Allow clients ask for exclusive access.
2447 * Implementation: When a client asks for exclusive access,
2448 * disconnect all others. Shared connects are allowed as long
2449 * as no exclusive connection exists.
2451 * This is how the rfb spec suggests to handle the shared flag.
2453 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2455 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2459 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2460 client->share_mode != VNC_SHARE_MODE_SHARED) {
2463 vnc_disconnect_start(client);
2466 if (mode == VNC_SHARE_MODE_SHARED) {
2467 if (vs->vd->num_exclusive > 0) {
2468 vnc_disconnect_start(vs);
2473 case VNC_SHARE_POLICY_FORCE_SHARED:
2475 * Policy: Shared connects only.
2476 * Implementation: Disallow clients asking for exclusive access.
2478 * Useful for shared desktop sessions where you don't want
2479 * someone forgetting to say -shared when running the vnc
2480 * client disconnect everybody else.
2482 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2483 vnc_disconnect_start(vs);
2488 vnc_set_share_mode(vs, mode);
2490 if (vs->vd->num_shared > vs->vd->connections_limit) {
2491 vnc_disconnect_start(vs);
2495 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2496 pixman_image_get_width(vs->vd->server) >= 0);
2497 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2498 pixman_image_get_height(vs->vd->server) >= 0);
2499 vs->client_width = pixman_image_get_width(vs->vd->server);
2500 vs->client_height = pixman_image_get_height(vs->vd->server);
2501 vnc_write_u16(vs, vs->client_width);
2502 vnc_write_u16(vs, vs->client_height);
2504 pixel_format_message(vs);
2507 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2508 if (size > sizeof(buf)) {
2512 size = snprintf(buf, sizeof(buf), "QEMU");
2515 vnc_write_u32(vs, size);
2516 vnc_write(vs, buf, size);
2519 vnc_client_cache_auth(vs);
2520 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2522 vnc_read_when(vs, protocol_client_msg, 1);
2527 void start_client_init(VncState *vs)
2529 vnc_read_when(vs, protocol_client_init, 1);
2532 static void make_challenge(VncState *vs)
2536 srand(time(NULL)+getpid()+getpid()*987654+rand());
2538 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2539 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2542 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2544 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2546 unsigned char key[8];
2547 time_t now = time(NULL);
2548 QCryptoCipher *cipher = NULL;
2551 if (!vs->vd->password) {
2552 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2555 if (vs->vd->expires < now) {
2556 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2560 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2562 /* Calculate the expected challenge response */
2563 pwlen = strlen(vs->vd->password);
2564 for (i=0; i<sizeof(key); i++)
2565 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2567 cipher = qcrypto_cipher_new(
2568 QCRYPTO_CIPHER_ALG_DES_RFB,
2569 QCRYPTO_CIPHER_MODE_ECB,
2570 key, G_N_ELEMENTS(key),
2573 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2574 error_get_pretty(err));
2579 if (qcrypto_cipher_encrypt(cipher,
2582 VNC_AUTH_CHALLENGE_SIZE,
2584 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2585 error_get_pretty(err));
2590 /* Compare expected vs actual challenge response */
2591 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2592 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2595 trace_vnc_auth_pass(vs, vs->auth);
2596 vnc_write_u32(vs, 0); /* Accept auth */
2599 start_client_init(vs);
2602 qcrypto_cipher_free(cipher);
2606 vnc_write_u32(vs, 1); /* Reject auth */
2607 if (vs->minor >= 8) {
2608 static const char err[] = "Authentication failed";
2609 vnc_write_u32(vs, sizeof(err));
2610 vnc_write(vs, err, sizeof(err));
2613 vnc_client_error(vs);
2614 qcrypto_cipher_free(cipher);
2618 void start_auth_vnc(VncState *vs)
2621 /* Send client a 'random' challenge */
2622 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2625 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2629 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2631 /* We only advertise 1 auth scheme at a time, so client
2632 * must pick the one we sent. Verify this */
2633 if (data[0] != vs->auth) { /* Reject auth */
2634 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2635 vnc_write_u32(vs, 1);
2636 if (vs->minor >= 8) {
2637 static const char err[] = "Authentication failed";
2638 vnc_write_u32(vs, sizeof(err));
2639 vnc_write(vs, err, sizeof(err));
2641 vnc_client_error(vs);
2642 } else { /* Accept requested auth */
2643 trace_vnc_auth_start(vs, vs->auth);
2646 if (vs->minor >= 8) {
2647 vnc_write_u32(vs, 0); /* Accept auth completion */
2650 trace_vnc_auth_pass(vs, vs->auth);
2651 start_client_init(vs);
2658 case VNC_AUTH_VENCRYPT:
2659 start_auth_vencrypt(vs);
2662 #ifdef CONFIG_VNC_SASL
2664 start_auth_sasl(vs);
2666 #endif /* CONFIG_VNC_SASL */
2668 default: /* Should not be possible, but just in case */
2669 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2670 vnc_write_u8(vs, 1);
2671 if (vs->minor >= 8) {
2672 static const char err[] = "Authentication failed";
2673 vnc_write_u32(vs, sizeof(err));
2674 vnc_write(vs, err, sizeof(err));
2676 vnc_client_error(vs);
2682 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2686 memcpy(local, version, 12);
2689 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2690 VNC_DEBUG("Malformed protocol version %s\n", local);
2691 vnc_client_error(vs);
2694 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2695 if (vs->major != 3 ||
2701 VNC_DEBUG("Unsupported client version\n");
2702 vnc_write_u32(vs, VNC_AUTH_INVALID);
2704 vnc_client_error(vs);
2707 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2708 * as equivalent to v3.3 by servers
2710 if (vs->minor == 4 || vs->minor == 5)
2713 if (vs->minor == 3) {
2714 trace_vnc_auth_start(vs, vs->auth);
2715 if (vs->auth == VNC_AUTH_NONE) {
2716 vnc_write_u32(vs, vs->auth);
2718 trace_vnc_auth_pass(vs, vs->auth);
2719 start_client_init(vs);
2720 } else if (vs->auth == VNC_AUTH_VNC) {
2721 VNC_DEBUG("Tell client VNC auth\n");
2722 vnc_write_u32(vs, vs->auth);
2726 trace_vnc_auth_fail(vs, vs->auth,
2727 "Unsupported auth method for v3.3", "");
2728 vnc_write_u32(vs, VNC_AUTH_INVALID);
2730 vnc_client_error(vs);
2733 vnc_write_u8(vs, 1); /* num auth */
2734 vnc_write_u8(vs, vs->auth);
2735 vnc_read_when(vs, protocol_client_auth, 1);
2742 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2744 struct VncSurface *vs = &vd->guest;
2746 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2749 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2753 w = (x + w) / VNC_STAT_RECT;
2754 h = (y + h) / VNC_STAT_RECT;
2758 for (j = y; j <= h; j++) {
2759 for (i = x; i <= w; i++) {
2760 vs->lossy_rect[j][i] = 1;
2765 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2768 int sty = y / VNC_STAT_RECT;
2769 int stx = x / VNC_STAT_RECT;
2772 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2773 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2775 QTAILQ_FOREACH(vs, &vd->clients, next) {
2778 /* kernel send buffers are full -> refresh later */
2779 if (vs->output.offset) {
2783 if (!vs->lossy_rect[sty][stx]) {
2787 vs->lossy_rect[sty][stx] = 0;
2788 for (j = 0; j < VNC_STAT_RECT; ++j) {
2789 bitmap_set(vs->dirty[y + j],
2790 x / VNC_DIRTY_PIXELS_PER_BIT,
2791 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2799 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2801 int width = MIN(pixman_image_get_width(vd->guest.fb),
2802 pixman_image_get_width(vd->server));
2803 int height = MIN(pixman_image_get_height(vd->guest.fb),
2804 pixman_image_get_height(vd->server));
2809 for (y = 0; y < height; y += VNC_STAT_RECT) {
2810 for (x = 0; x < width; x += VNC_STAT_RECT) {
2811 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2813 rect->updated = false;
2817 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2819 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2822 vd->guest.last_freq_check = *tv;
2824 for (y = 0; y < height; y += VNC_STAT_RECT) {
2825 for (x = 0; x < width; x += VNC_STAT_RECT) {
2826 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2827 int count = ARRAY_SIZE(rect->times);
2828 struct timeval min, max;
2830 if (!timerisset(&rect->times[count - 1])) {
2834 max = rect->times[(rect->idx + count - 1) % count];
2835 qemu_timersub(tv, &max, &res);
2837 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2839 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2840 memset(rect->times, 0, sizeof (rect->times));
2844 min = rect->times[rect->idx];
2845 max = rect->times[(rect->idx + count - 1) % count];
2846 qemu_timersub(&max, &min, &res);
2848 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2849 rect->freq /= count;
2850 rect->freq = 1. / rect->freq;
2856 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2862 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2863 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2865 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2866 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2867 total += vnc_stat_rect(vs->vd, i, j)->freq;
2879 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2883 rect = vnc_stat_rect(vd, x, y);
2884 if (rect->updated) {
2887 rect->times[rect->idx] = *tv;
2888 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2889 rect->updated = true;
2892 static int vnc_refresh_server_surface(VncDisplay *vd)
2894 int width = MIN(pixman_image_get_width(vd->guest.fb),
2895 pixman_image_get_width(vd->server));
2896 int height = MIN(pixman_image_get_height(vd->guest.fb),
2897 pixman_image_get_height(vd->server));
2898 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2899 uint8_t *guest_row0 = NULL, *server_row0;
2902 pixman_image_t *tmpbuf = NULL;
2904 struct timeval tv = { 0, 0 };
2906 if (!vd->non_adaptive) {
2907 gettimeofday(&tv, NULL);
2908 has_dirty = vnc_update_stats(vd, &tv);
2912 * Walk through the guest dirty map.
2913 * Check and copy modified bits from guest to server surface.
2914 * Update server dirty map.
2916 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2917 server_stride = guest_stride = guest_ll =
2918 pixman_image_get_stride(vd->server);
2919 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2921 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2922 int width = pixman_image_get_width(vd->server);
2923 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2926 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2927 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2928 guest_stride = pixman_image_get_stride(vd->guest.fb);
2929 guest_ll = pixman_image_get_width(vd->guest.fb)
2930 * DIV_ROUND_UP(guest_bpp, 8);
2932 line_bytes = MIN(server_stride, guest_ll);
2936 uint8_t *guest_ptr, *server_ptr;
2937 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2938 height * VNC_DIRTY_BPL(&vd->guest),
2939 y * VNC_DIRTY_BPL(&vd->guest));
2940 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2941 /* no more dirty bits */
2944 y = offset / VNC_DIRTY_BPL(&vd->guest);
2945 x = offset % VNC_DIRTY_BPL(&vd->guest);
2947 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2949 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2950 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2951 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2953 guest_ptr = guest_row0 + y * guest_stride;
2955 guest_ptr += x * cmp_bytes;
2957 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2958 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2959 int _cmp_bytes = cmp_bytes;
2960 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2963 if ((x + 1) * cmp_bytes > line_bytes) {
2964 _cmp_bytes = line_bytes - x * cmp_bytes;
2966 assert(_cmp_bytes >= 0);
2967 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2970 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2971 if (!vd->non_adaptive) {
2972 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2975 QTAILQ_FOREACH(vs, &vd->clients, next) {
2976 set_bit(x, vs->dirty[y]);
2983 qemu_pixman_image_unref(tmpbuf);
2987 static void vnc_refresh(DisplayChangeListener *dcl)
2989 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2991 int has_dirty, rects = 0;
2993 if (QTAILQ_EMPTY(&vd->clients)) {
2994 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2998 graphic_hw_update(vd->dcl.con);
3000 if (vnc_trylock_display(vd)) {
3001 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3005 has_dirty = vnc_refresh_server_surface(vd);
3006 vnc_unlock_display(vd);
3008 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3009 rects += vnc_update_client(vs, has_dirty);
3010 /* vs might be free()ed here */
3013 if (has_dirty && rects) {
3014 vd->dcl.update_interval /= 2;
3015 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3016 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3019 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3020 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3021 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3026 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3027 bool skipauth, bool websocket)
3029 VncState *vs = g_new0(VncState, 1);
3030 bool first_client = QTAILQ_EMPTY(&vd->clients);
3033 trace_vnc_client_connect(vs, sioc);
3034 vs->magic = VNC_MAGIC;
3036 object_ref(OBJECT(vs->sioc));
3037 vs->ioc = QIO_CHANNEL(sioc);
3038 object_ref(OBJECT(vs->ioc));
3041 buffer_init(&vs->input, "vnc-input/%p", sioc);
3042 buffer_init(&vs->output, "vnc-output/%p", sioc);
3043 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
3045 buffer_init(&vs->tight.tight, "vnc-tight/%p", sioc);
3046 buffer_init(&vs->tight.zlib, "vnc-tight-zlib/%p", sioc);
3047 buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
3048 #ifdef CONFIG_VNC_JPEG
3049 buffer_init(&vs->tight.jpeg, "vnc-tight-jpeg/%p", sioc);
3051 #ifdef CONFIG_VNC_PNG
3052 buffer_init(&vs->tight.png, "vnc-tight-png/%p", sioc);
3054 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
3055 buffer_init(&vs->zrle.zrle, "vnc-zrle/%p", sioc);
3056 buffer_init(&vs->zrle.fb, "vnc-zrle-fb/%p", sioc);
3057 buffer_init(&vs->zrle.zlib, "vnc-zrle-zlib/%p", sioc);
3060 vs->auth = VNC_AUTH_NONE;
3061 vs->subauth = VNC_AUTH_INVALID;
3064 vs->auth = vd->ws_auth;
3065 vs->subauth = VNC_AUTH_INVALID;
3067 vs->auth = vd->auth;
3068 vs->subauth = vd->subauth;
3071 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3072 sioc, websocket, vs->auth, vs->subauth);
3074 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3075 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3076 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3079 VNC_DEBUG("New client on socket %p\n", vs->sioc);
3080 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3081 qio_channel_set_blocking(vs->ioc, false, NULL);
3083 g_source_remove(vs->ioc_tag);
3088 vs->ioc_tag = qio_channel_add_watch(
3089 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
3091 vs->ioc_tag = qio_channel_add_watch(
3092 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
3095 vs->ioc_tag = qio_channel_add_watch(
3096 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
3099 vnc_client_cache_addr(vs);
3100 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3101 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3106 vs->as.freq = 44100;
3107 vs->as.nchannels = 2;
3108 vs->as.fmt = AUD_FMT_S16;
3109 vs->as.endianness = 0;
3111 qemu_mutex_init(&vs->output_mutex);
3112 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3114 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3116 vnc_update_server_surface(vd);
3119 graphic_hw_update(vd->dcl.con);
3121 if (!vs->websocket) {
3122 vnc_start_protocol(vs);
3125 if (vd->num_connecting > vd->connections_limit) {
3126 QTAILQ_FOREACH(vs, &vd->clients, next) {
3127 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3128 vnc_disconnect_start(vs);
3135 void vnc_start_protocol(VncState *vs)
3137 vnc_write(vs, "RFB 003.008\n", 12);
3139 vnc_read_when(vs, protocol_version, 12);
3141 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3142 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3145 static void vnc_listen_io(QIONetListener *listener,
3146 QIOChannelSocket *cioc,
3149 VncDisplay *vd = opaque;
3150 bool isWebsock = listener == vd->wslistener;
3152 qio_channel_set_name(QIO_CHANNEL(cioc),
3153 isWebsock ? "vnc-ws-server" : "vnc-server");
3154 qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3155 vnc_connect(vd, cioc, false, isWebsock);
3158 static const DisplayChangeListenerOps dcl_ops = {
3160 .dpy_refresh = vnc_refresh,
3161 .dpy_gfx_update = vnc_dpy_update,
3162 .dpy_gfx_switch = vnc_dpy_switch,
3163 .dpy_gfx_check_format = qemu_pixman_check_format,
3164 .dpy_mouse_set = vnc_mouse_set,
3165 .dpy_cursor_define = vnc_dpy_cursor_define,
3168 void vnc_display_init(const char *id, Error **errp)
3172 if (vnc_display_find(id) != NULL) {
3175 vd = g_malloc0(sizeof(*vd));
3177 vd->id = strdup(id);
3178 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3180 QTAILQ_INIT(&vd->clients);
3181 vd->expires = TIME_MAX;
3183 if (keyboard_layout) {
3184 trace_vnc_key_map_init(keyboard_layout);
3185 vd->kbd_layout = init_keyboard_layout(name2keysym,
3186 keyboard_layout, errp);
3188 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3191 if (!vd->kbd_layout) {
3195 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3196 vd->connections_limit = 32;
3198 qemu_mutex_init(&vd->mutex);
3199 vnc_start_worker_thread();
3201 vd->dcl.ops = &dcl_ops;
3202 register_displaychangelistener(&vd->dcl);
3203 vd->kbd = qkbd_state_init(vd->dcl.con);
3207 static void vnc_display_close(VncDisplay *vd)
3212 vd->is_unix = false;
3215 qio_net_listener_disconnect(vd->listener);
3216 object_unref(OBJECT(vd->listener));
3218 vd->listener = NULL;
3220 if (vd->wslistener) {
3221 qio_net_listener_disconnect(vd->wslistener);
3222 object_unref(OBJECT(vd->wslistener));
3224 vd->wslistener = NULL;
3226 vd->auth = VNC_AUTH_INVALID;
3227 vd->subauth = VNC_AUTH_INVALID;
3229 object_unparent(OBJECT(vd->tlscreds));
3230 vd->tlscreds = NULL;
3233 object_unparent(OBJECT(vd->tlsauthz));
3234 vd->tlsauthz = NULL;
3236 g_free(vd->tlsauthzid);
3237 vd->tlsauthzid = NULL;
3238 if (vd->lock_key_sync) {
3239 qemu_remove_led_event_handler(vd->led);
3242 #ifdef CONFIG_VNC_SASL
3243 if (vd->sasl.authz) {
3244 object_unparent(OBJECT(vd->sasl.authz));
3245 vd->sasl.authz = NULL;
3247 g_free(vd->sasl.authzid);
3248 vd->sasl.authzid = NULL;
3252 int vnc_display_password(const char *id, const char *password)
3254 VncDisplay *vd = vnc_display_find(id);
3259 if (vd->auth == VNC_AUTH_NONE) {
3260 error_printf_unless_qmp("If you want use passwords please enable "
3261 "password auth using '-vnc ${dpy},password'.\n");
3265 g_free(vd->password);
3266 vd->password = g_strdup(password);
3271 int vnc_display_pw_expire(const char *id, time_t expires)
3273 VncDisplay *vd = vnc_display_find(id);
3279 vd->expires = expires;
3283 static void vnc_display_print_local_addr(VncDisplay *vd)
3285 SocketAddress *addr;
3288 if (!vd->listener || !vd->listener->nsioc) {
3292 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], &err);
3297 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3298 qapi_free_SocketAddress(addr);
3301 error_printf_unless_qmp("VNC server running on %s:%s\n",
3304 qapi_free_SocketAddress(addr);
3307 static QemuOptsList qemu_vnc_opts = {
3309 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3310 .implied_opt_name = "vnc",
3314 .type = QEMU_OPT_STRING,
3316 .name = "websocket",
3317 .type = QEMU_OPT_STRING,
3319 .name = "tls-creds",
3320 .type = QEMU_OPT_STRING,
3323 .type = QEMU_OPT_STRING,
3326 .type = QEMU_OPT_STRING,
3329 .type = QEMU_OPT_NUMBER,
3331 .name = "connections",
3332 .type = QEMU_OPT_NUMBER,
3335 .type = QEMU_OPT_NUMBER,
3338 .type = QEMU_OPT_BOOL,
3341 .type = QEMU_OPT_BOOL,
3344 .type = QEMU_OPT_BOOL,
3347 .type = QEMU_OPT_BOOL,
3349 .name = "lock-key-sync",
3350 .type = QEMU_OPT_BOOL,
3352 .name = "key-delay-ms",
3353 .type = QEMU_OPT_NUMBER,
3356 .type = QEMU_OPT_BOOL,
3359 .type = QEMU_OPT_BOOL,
3362 .type = QEMU_OPT_BOOL,
3364 .name = "non-adaptive",
3365 .type = QEMU_OPT_BOOL,
3367 { /* end of list */ }
3373 vnc_display_setup_auth(int *auth,
3375 QCryptoTLSCreds *tlscreds,
3382 * We have a choice of 3 authentication options
3388 * The channel can be run in 2 modes
3393 * And TLS can use 2 types of credentials
3398 * We thus have 9 possible logical combinations
3403 * 4. tls + anon + none
3404 * 5. tls + anon + vnc
3405 * 6. tls + anon + sasl
3406 * 7. tls + x509 + none
3407 * 8. tls + x509 + vnc
3408 * 9. tls + x509 + sasl
3410 * These need to be mapped into the VNC auth schemes
3411 * in an appropriate manner. In regular VNC, all the
3412 * TLS options get mapped into VNC_AUTH_VENCRYPT
3415 * In websockets, the https:// protocol already provides
3416 * TLS support, so there is no need to make use of the
3417 * VeNCrypt extension. Furthermore, websockets browser
3418 * clients could not use VeNCrypt even if they wanted to,
3419 * as they cannot control when the TLS handshake takes
3420 * place. Thus there is no option but to rely on https://,
3421 * meaning combinations 4->6 and 7->9 will be mapped to
3422 * VNC auth schemes in the same way as combos 1->3.
3424 * Regardless of fact that we have a different mapping to
3425 * VNC auth mechs for plain VNC vs websockets VNC, the end
3426 * result has the same security characteristics.
3428 if (websocket || !tlscreds) {
3430 VNC_DEBUG("Initializing VNC server with password auth\n");
3431 *auth = VNC_AUTH_VNC;
3433 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3434 *auth = VNC_AUTH_SASL;
3436 VNC_DEBUG("Initializing VNC server with no auth\n");
3437 *auth = VNC_AUTH_NONE;
3439 *subauth = VNC_AUTH_INVALID;
3441 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3442 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3443 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3444 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3446 if (!is_x509 && !is_anon) {
3448 "Unsupported TLS cred type %s",
3449 object_get_typename(OBJECT(tlscreds)));
3452 *auth = VNC_AUTH_VENCRYPT;
3455 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3456 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3458 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3459 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3464 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3465 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3467 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3468 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3472 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3473 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3475 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3476 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3484 static int vnc_display_get_address(const char *addrstr,
3493 SocketAddress **retaddr,
3497 SocketAddress *addr = NULL;
3499 addr = g_new0(SocketAddress, 1);
3501 if (strncmp(addrstr, "unix:", 5) == 0) {
3502 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3503 addr->u.q_unix.path = g_strdup(addrstr + 5);
3506 error_setg(errp, "UNIX sockets not supported with websock");
3511 error_setg(errp, "Port range not support with UNIX socket");
3518 unsigned long long baseport = 0;
3519 InetSocketAddress *inet;
3521 port = strrchr(addrstr, ':');
3527 error_setg(errp, "no vnc port specified");
3531 hostlen = port - addrstr;
3533 if (*port == '\0') {
3534 error_setg(errp, "vnc port cannot be empty");
3539 addr->type = SOCKET_ADDRESS_TYPE_INET;
3540 inet = &addr->u.inet;
3541 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3542 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3544 inet->host = g_strndup(addrstr, hostlen);
3546 /* plain VNC port is just an offset, for websocket
3547 * port is absolute */
3549 if (g_str_equal(addrstr, "") ||
3550 g_str_equal(addrstr, "on")) {
3551 if (displaynum == -1) {
3552 error_setg(errp, "explicit websocket port is required");
3555 inet->port = g_strdup_printf(
3556 "%d", displaynum + 5700);
3558 inet->has_to = true;
3559 inet->to = to + 5700;
3562 inet->port = g_strdup(port);
3565 int offset = reverse ? 0 : 5900;
3566 if (parse_uint_full(port, &baseport, 10) < 0) {
3567 error_setg(errp, "can't convert to a number: %s", port);
3570 if (baseport > 65535 ||
3571 baseport + offset > 65535) {
3572 error_setg(errp, "port %s out of range", port);
3575 inet->port = g_strdup_printf(
3576 "%d", (int)baseport + offset);
3579 inet->has_to = true;
3580 inet->to = to + offset;
3585 inet->has_ipv4 = has_ipv4;
3587 inet->has_ipv6 = has_ipv6;
3596 qapi_free_SocketAddress(addr);
3601 static void vnc_free_addresses(SocketAddress ***retsaddr,
3606 for (i = 0; i < *retnsaddr; i++) {
3607 qapi_free_SocketAddress((*retsaddr)[i]);
3615 static int vnc_display_get_addresses(QemuOpts *opts,
3617 SocketAddress ***retsaddr,
3619 SocketAddress ***retwsaddr,
3623 SocketAddress *saddr = NULL;
3624 SocketAddress *wsaddr = NULL;
3625 QemuOptsIter addriter;
3627 int to = qemu_opt_get_number(opts, "to", 0);
3628 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3629 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3630 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3631 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3632 int displaynum = -1;
3640 addr = qemu_opt_get(opts, "vnc");
3641 if (addr == NULL || g_str_equal(addr, "none")) {
3645 if (qemu_opt_get(opts, "websocket") &&
3646 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3648 "SHA1 hash support is required for websockets");
3652 qemu_opt_iter_init(&addriter, opts, "vnc");
3653 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3655 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3662 /* Historical compat - first listen address can be used
3663 * to set the default websocket port
3665 if (displaynum == -1) {
3668 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3669 (*retsaddr)[(*retnsaddr)++] = saddr;
3672 /* If we had multiple primary displays, we don't do defaults
3673 * for websocket, and require explicit config instead. */
3674 if (*retnsaddr > 1) {
3678 qemu_opt_iter_init(&addriter, opts, "websocket");
3679 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3680 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3683 &wsaddr, errp) < 0) {
3687 /* Historical compat - if only a single listen address was
3688 * provided, then this is used to set the default listen
3689 * address for websocket too
3691 if (*retnsaddr == 1 &&
3692 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3693 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3694 g_str_equal(wsaddr->u.inet.host, "") &&
3695 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3696 g_free(wsaddr->u.inet.host);
3697 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3700 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3701 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3707 vnc_free_addresses(retsaddr, retnsaddr);
3708 vnc_free_addresses(retwsaddr, retnwsaddr);
3713 static int vnc_display_connect(VncDisplay *vd,
3714 SocketAddress **saddr,
3716 SocketAddress **wsaddr,
3720 /* connect to viewer */
3721 QIOChannelSocket *sioc = NULL;
3723 error_setg(errp, "Cannot use websockets in reverse mode");
3727 error_setg(errp, "Expected a single address in reverse mode");
3730 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3731 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3732 sioc = qio_channel_socket_new();
3733 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3734 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3737 vnc_connect(vd, sioc, false, false);
3738 object_unref(OBJECT(sioc));
3743 static int vnc_display_listen(VncDisplay *vd,
3744 SocketAddress **saddr,
3746 SocketAddress **wsaddr,
3753 vd->listener = qio_net_listener_new();
3754 qio_net_listener_set_name(vd->listener, "vnc-listen");
3755 for (i = 0; i < nsaddr; i++) {
3756 if (qio_net_listener_open_sync(vd->listener,
3763 qio_net_listener_set_client_func(vd->listener,
3764 vnc_listen_io, vd, NULL);
3768 vd->wslistener = qio_net_listener_new();
3769 qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3770 for (i = 0; i < nwsaddr; i++) {
3771 if (qio_net_listener_open_sync(vd->wslistener,
3778 qio_net_listener_set_client_func(vd->wslistener,
3779 vnc_listen_io, vd, NULL);
3786 void vnc_display_open(const char *id, Error **errp)
3788 VncDisplay *vd = vnc_display_find(id);
3789 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3790 SocketAddress **saddr = NULL, **wsaddr = NULL;
3791 size_t nsaddr, nwsaddr;
3792 const char *share, *device_id;
3794 bool password = false;
3795 bool reverse = false;
3799 int lock_key_sync = 1;
3803 error_setg(errp, "VNC display not active");
3806 vnc_display_close(vd);
3812 reverse = qemu_opt_get_bool(opts, "reverse", false);
3813 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3814 &wsaddr, &nwsaddr, errp) < 0) {
3818 password = qemu_opt_get_bool(opts, "password", false);
3820 if (fips_get_state()) {
3822 "VNC password auth disabled due to FIPS mode, "
3823 "consider using the VeNCrypt or SASL authentication "
3824 "methods as an alternative");
3827 if (!qcrypto_cipher_supports(
3828 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3830 "Cipher backend does not support DES RFB algorithm");
3835 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3836 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3837 sasl = qemu_opt_get_bool(opts, "sasl", false);
3838 #ifndef CONFIG_VNC_SASL
3840 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3843 #endif /* CONFIG_VNC_SASL */
3844 credid = qemu_opt_get(opts, "tls-creds");
3847 creds = object_resolve_path_component(
3848 object_get_objects_root(), credid);
3850 error_setg(errp, "No TLS credentials with id '%s'",
3854 vd->tlscreds = (QCryptoTLSCreds *)
3855 object_dynamic_cast(creds,
3856 TYPE_QCRYPTO_TLS_CREDS);
3857 if (!vd->tlscreds) {
3858 error_setg(errp, "Object with id '%s' is not TLS credentials",
3862 object_ref(OBJECT(vd->tlscreds));
3864 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3866 "Expecting TLS credentials with a server endpoint");
3870 acl = qemu_opt_get_bool(opts, "acl", false);
3872 share = qemu_opt_get(opts, "share");
3874 if (strcmp(share, "ignore") == 0) {
3875 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
3876 } else if (strcmp(share, "allow-exclusive") == 0) {
3877 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3878 } else if (strcmp(share, "force-shared") == 0) {
3879 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3881 error_setg(errp, "unknown vnc share= option");
3885 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3887 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3889 #ifdef CONFIG_VNC_JPEG
3890 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
3892 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3893 /* adaptive updates are only used with tight encoding and
3894 * if lossy updates are enabled so we can disable all the
3895 * calculations otherwise */
3897 vd->non_adaptive = true;
3901 if (strcmp(vd->id, "default") == 0) {
3902 vd->tlsauthzid = g_strdup("vnc.x509dname");
3904 vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
3906 vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
3907 QAUTHZ_LIST_POLICY_DENY,
3910 #ifdef CONFIG_VNC_SASL
3912 if (strcmp(vd->id, "default") == 0) {
3913 vd->sasl.authzid = g_strdup("vnc.username");
3915 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
3917 vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
3918 QAUTHZ_LIST_POLICY_DENY,
3923 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
3924 vd->tlscreds, password,
3925 sasl, false, errp) < 0) {
3928 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
3930 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
3931 vd->tlscreds, password,
3932 sasl, true, errp) < 0) {
3935 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
3937 #ifdef CONFIG_VNC_SASL
3939 int saslErr = sasl_server_init(NULL, "qemu");
3941 if (saslErr != SASL_OK) {
3942 error_setg(errp, "Failed to initialize SASL auth: %s",
3943 sasl_errstring(saslErr, NULL, NULL));
3948 vd->lock_key_sync = lock_key_sync;
3949 if (lock_key_sync) {
3950 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
3954 device_id = qemu_opt_get(opts, "display");
3956 int head = qemu_opt_get_number(opts, "head", 0);
3959 con = qemu_console_lookup_by_device_name(device_id, head, &err);
3961 error_propagate(errp, err);
3968 if (con != vd->dcl.con) {
3969 qkbd_state_free(vd->kbd);
3970 unregister_displaychangelistener(&vd->dcl);
3972 register_displaychangelistener(&vd->dcl);
3973 vd->kbd = qkbd_state_init(vd->dcl.con);
3975 qkbd_state_set_delay(vd->kbd, key_delay_ms);
3977 if (saddr == NULL) {
3982 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
3986 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
3991 if (qemu_opt_get(opts, "to")) {
3992 vnc_display_print_local_addr(vd);
3996 vnc_free_addresses(&saddr, &nsaddr);
3997 vnc_free_addresses(&wsaddr, &nwsaddr);
4001 vnc_display_close(vd);
4005 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4007 VncDisplay *vd = vnc_display_find(id);
4008 QIOChannelSocket *sioc;
4014 sioc = qio_channel_socket_new_fd(csock, NULL);
4016 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4017 vnc_connect(vd, sioc, skipauth, false);
4018 object_unref(OBJECT(sioc));
4022 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4027 id = g_strdup("default");
4028 while (qemu_opts_find(olist, id)) {
4030 id = g_strdup_printf("vnc%d", i++);
4032 qemu_opts_set_id(opts, id);
4035 QemuOpts *vnc_parse(const char *str, Error **errp)
4037 QemuOptsList *olist = qemu_find_opts("vnc");
4038 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
4045 id = qemu_opts_id(opts);
4047 /* auto-assign id if not present */
4048 vnc_auto_assign_id(olist, opts);
4053 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4055 Error *local_err = NULL;
4056 char *id = (char *)qemu_opts_id(opts);
4059 vnc_display_init(id, &local_err);
4061 error_propagate(errp, local_err);
4064 vnc_display_open(id, &local_err);
4065 if (local_err != NULL) {
4066 error_propagate(errp, local_err);
4072 static void vnc_register_config(void)
4074 qemu_add_opts(&qemu_vnc_opts);
4076 opts_init(vnc_register_config);