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/sockets.h"
34 #include "qemu/timer.h"
36 #include "qemu/config-file.h"
37 #include "qapi/qmp/qerror.h"
38 #include "qapi/qmp/types.h"
39 #include "qmp-commands.h"
41 #include "qapi-event.h"
42 #include "crypto/hash.h"
43 #include "crypto/tlscredsanon.h"
44 #include "crypto/tlscredsx509.h"
45 #include "qom/object_interfaces.h"
46 #include "qemu/cutils.h"
47 #include "io/dns-resolver.h"
49 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
50 #define VNC_REFRESH_INTERVAL_INC 50
51 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
52 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
53 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
55 #include "vnc_keysym.h"
56 #include "crypto/cipher.h"
58 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
59 QTAILQ_HEAD_INITIALIZER(vnc_displays);
61 static int vnc_cursor_define(VncState *vs);
62 static void vnc_release_modifiers(VncState *vs);
63 static void vnc_update_throttle_offset(VncState *vs);
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)
235 info = g_malloc0(sizeof(*info));
236 vnc_init_basic_info_from_server_addr(vd->lsock[0],
237 qapi_VncServerInfo_base(info), &err);
238 info->has_auth = true;
239 info->auth = g_strdup(vnc_auth_name(vd));
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),
302 case QAPI_EVENT_VNC_INITIALIZED:
303 qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
305 case QAPI_EVENT_VNC_DISCONNECTED:
306 qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
312 qapi_free_VncServerInfo(si);
315 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
320 info = g_malloc0(sizeof(*info));
322 vnc_init_basic_info_from_remote_addr(client->sioc,
323 qapi_VncClientInfo_base(info),
327 qapi_free_VncClientInfo(info);
331 info->websocket = client->websocket;
334 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
335 info->has_x509_dname = info->x509_dname != NULL;
337 #ifdef CONFIG_VNC_SASL
338 if (client->sasl.conn && client->sasl.username) {
339 info->has_sasl_username = true;
340 info->sasl_username = g_strdup(client->sasl.username);
347 static VncDisplay *vnc_display_find(const char *id)
352 return QTAILQ_FIRST(&vnc_displays);
354 QTAILQ_FOREACH(vd, &vnc_displays, next) {
355 if (strcmp(id, vd->id) == 0) {
362 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
364 VncClientInfoList *cinfo, *prev = NULL;
367 QTAILQ_FOREACH(client, &vd->clients, next) {
368 cinfo = g_new0(VncClientInfoList, 1);
369 cinfo->value = qmp_query_vnc_client(client);
376 VncInfo *qmp_query_vnc(Error **errp)
378 VncInfo *info = g_malloc0(sizeof(*info));
379 VncDisplay *vd = vnc_display_find(NULL);
380 SocketAddress *addr = NULL;
382 if (vd == NULL || !vd->nlsock) {
383 info->enabled = false;
385 info->enabled = true;
387 /* for compatibility with the original command */
388 info->has_clients = true;
389 info->clients = qmp_query_client_list(vd);
391 if (vd->lsock == NULL) {
395 addr = qio_channel_socket_get_local_address(vd->lsock[0], errp);
400 switch (addr->type) {
401 case SOCKET_ADDRESS_TYPE_INET:
402 info->host = g_strdup(addr->u.inet.host);
403 info->service = g_strdup(addr->u.inet.port);
404 if (addr->u.inet.ipv6) {
405 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
407 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
411 case SOCKET_ADDRESS_TYPE_UNIX:
412 info->host = g_strdup("");
413 info->service = g_strdup(addr->u.q_unix.path);
414 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
417 case SOCKET_ADDRESS_TYPE_VSOCK:
418 case SOCKET_ADDRESS_TYPE_FD:
419 error_setg(errp, "Unsupported socket address type %s",
420 SocketAddressType_str(addr->type));
426 info->has_host = true;
427 info->has_service = true;
428 info->has_family = true;
430 info->has_auth = true;
431 info->auth = g_strdup(vnc_auth_name(vd));
434 qapi_free_SocketAddress(addr);
438 qapi_free_SocketAddress(addr);
439 qapi_free_VncInfo(info);
444 static void qmp_query_auth(int auth, int subauth,
445 VncPrimaryAuth *qmp_auth,
446 VncVencryptSubAuth *qmp_vencrypt,
447 bool *qmp_has_vencrypt);
449 static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
453 VncServerInfo2List *prev)
455 VncServerInfo2List *list;
456 VncServerInfo2 *info;
460 addr = qio_channel_socket_get_local_address(ioc, &err);
466 info = g_new0(VncServerInfo2, 1);
467 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
468 qapi_free_SocketAddress(addr);
470 qapi_free_VncServerInfo2(info);
474 info->websocket = websocket;
476 qmp_query_auth(auth, subauth, &info->auth,
477 &info->vencrypt, &info->has_vencrypt);
479 list = g_new0(VncServerInfo2List, 1);
485 static void qmp_query_auth(int auth, int subauth,
486 VncPrimaryAuth *qmp_auth,
487 VncVencryptSubAuth *qmp_vencrypt,
488 bool *qmp_has_vencrypt)
492 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
495 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
498 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
501 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
504 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
507 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
509 case VNC_AUTH_VENCRYPT:
510 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
511 *qmp_has_vencrypt = true;
513 case VNC_AUTH_VENCRYPT_PLAIN:
514 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
516 case VNC_AUTH_VENCRYPT_TLSNONE:
517 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
519 case VNC_AUTH_VENCRYPT_TLSVNC:
520 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
522 case VNC_AUTH_VENCRYPT_TLSPLAIN:
523 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
525 case VNC_AUTH_VENCRYPT_X509NONE:
526 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
528 case VNC_AUTH_VENCRYPT_X509VNC:
529 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
531 case VNC_AUTH_VENCRYPT_X509PLAIN:
532 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
534 case VNC_AUTH_VENCRYPT_TLSSASL:
535 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
537 case VNC_AUTH_VENCRYPT_X509SASL:
538 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
541 *qmp_has_vencrypt = false;
546 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
550 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
555 VncInfo2List *qmp_query_vnc_servers(Error **errp)
557 VncInfo2List *item, *prev = NULL;
563 QTAILQ_FOREACH(vd, &vnc_displays, next) {
564 info = g_new0(VncInfo2, 1);
565 info->id = g_strdup(vd->id);
566 info->clients = qmp_query_client_list(vd);
567 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
568 &info->vencrypt, &info->has_vencrypt);
570 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
572 info->has_display = true;
573 info->display = g_strdup(dev->id);
575 for (i = 0; i < vd->nlsock; i++) {
576 info->server = qmp_query_server_entry(
577 vd->lsock[i], false, vd->auth, vd->subauth, info->server);
579 for (i = 0; i < vd->nlwebsock; i++) {
580 info->server = qmp_query_server_entry(
581 vd->lwebsock[i], true, vd->ws_auth,
582 vd->ws_subauth, info->server);
585 item = g_new0(VncInfo2List, 1);
594 1) Get the queue working for IO.
595 2) there is some weirdness when using the -S option (the screen is grey
596 and not totally invalidated
597 3) resolutions > 1024
600 static int vnc_update_client(VncState *vs, int has_dirty);
601 static void vnc_disconnect_start(VncState *vs);
603 static void vnc_colordepth(VncState *vs);
604 static void framebuffer_update_request(VncState *vs, int incremental,
605 int x_position, int y_position,
607 static void vnc_refresh(DisplayChangeListener *dcl);
608 static int vnc_refresh_server_surface(VncDisplay *vd);
610 static int vnc_width(VncDisplay *vd)
612 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
613 VNC_DIRTY_PIXELS_PER_BIT));
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);
666 static void vnc_desktop_resize(VncState *vs)
668 if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
671 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
672 vs->client_height == pixman_image_get_height(vs->vd->server)) {
676 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
677 pixman_image_get_width(vs->vd->server) >= 0);
678 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
679 pixman_image_get_height(vs->vd->server) >= 0);
680 vs->client_width = pixman_image_get_width(vs->vd->server);
681 vs->client_height = pixman_image_get_height(vs->vd->server);
683 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
685 vnc_write_u16(vs, 1); /* number of rects */
686 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
687 VNC_ENCODING_DESKTOPRESIZE);
688 vnc_unlock_output(vs);
692 static void vnc_abort_display_jobs(VncDisplay *vd)
696 QTAILQ_FOREACH(vs, &vd->clients, next) {
699 vnc_unlock_output(vs);
701 QTAILQ_FOREACH(vs, &vd->clients, next) {
704 QTAILQ_FOREACH(vs, &vd->clients, next) {
707 vnc_unlock_output(vs);
711 int vnc_server_fb_stride(VncDisplay *vd)
713 return pixman_image_get_stride(vd->server);
716 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
720 ptr = (uint8_t *)pixman_image_get_data(vd->server);
721 ptr += y * vnc_server_fb_stride(vd);
722 ptr += x * VNC_SERVER_FB_BYTES;
726 static void vnc_update_server_surface(VncDisplay *vd)
730 qemu_pixman_image_unref(vd->server);
733 if (QTAILQ_EMPTY(&vd->clients)) {
737 width = vnc_width(vd);
738 height = vnc_height(vd);
739 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
743 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
744 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
748 static void vnc_dpy_switch(DisplayChangeListener *dcl,
749 DisplaySurface *surface)
751 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
754 vnc_abort_display_jobs(vd);
758 vnc_update_server_surface(vd);
761 qemu_pixman_image_unref(vd->guest.fb);
762 vd->guest.fb = pixman_image_ref(surface->image);
763 vd->guest.format = surface->format;
765 QTAILQ_FOREACH(vs, &vd->clients, next) {
767 vnc_desktop_resize(vs);
768 if (vs->vd->cursor) {
769 vnc_cursor_define(vs);
771 memset(vs->dirty, 0x00, sizeof(vs->dirty));
772 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
775 vnc_update_throttle_offset(vs);
780 static void vnc_write_pixels_copy(VncState *vs,
781 void *pixels, int size)
783 vnc_write(vs, pixels, size);
786 /* slowest but generic code. */
787 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
791 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
792 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
793 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
794 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
796 # error need some bits here if you change VNC_SERVER_FB_FORMAT
798 v = (r << vs->client_pf.rshift) |
799 (g << vs->client_pf.gshift) |
800 (b << vs->client_pf.bshift);
801 switch (vs->client_pf.bytes_per_pixel) {
831 static void vnc_write_pixels_generic(VncState *vs,
832 void *pixels1, int size)
836 if (VNC_SERVER_FB_BYTES == 4) {
837 uint32_t *pixels = pixels1;
840 for (i = 0; i < n; i++) {
841 vnc_convert_pixel(vs, buf, pixels[i]);
842 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
847 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
851 VncDisplay *vd = vs->vd;
853 row = vnc_server_fb_ptr(vd, x, y);
854 for (i = 0; i < h; i++) {
855 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
856 row += vnc_server_fb_stride(vd);
861 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
864 bool encode_raw = false;
865 size_t saved_offs = vs->output.offset;
867 switch(vs->vnc_encoding) {
868 case VNC_ENCODING_ZLIB:
869 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
871 case VNC_ENCODING_HEXTILE:
872 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
873 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
875 case VNC_ENCODING_TIGHT:
876 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
878 case VNC_ENCODING_TIGHT_PNG:
879 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
881 case VNC_ENCODING_ZRLE:
882 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
884 case VNC_ENCODING_ZYWRLE:
885 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
892 /* If the client has the same pixel format as our internal buffer and
893 * a RAW encoding would need less space fall back to RAW encoding to
894 * save bandwidth and processing power in the client. */
895 if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
896 12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
897 vs->output.offset = saved_offs;
902 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
903 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
909 static void vnc_mouse_set(DisplayChangeListener *dcl,
910 int x, int y, int visible)
912 /* can we ask the client(s) to move the pointer ??? */
915 static int vnc_cursor_define(VncState *vs)
917 QEMUCursor *c = vs->vd->cursor;
920 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
922 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
923 vnc_write_u8(vs, 0); /* padding */
924 vnc_write_u16(vs, 1); /* # of rects */
925 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
926 VNC_ENCODING_RICH_CURSOR);
927 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
928 vnc_write_pixels_generic(vs, c->data, isize);
929 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
930 vnc_unlock_output(vs);
936 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
939 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
942 cursor_put(vd->cursor);
943 g_free(vd->cursor_mask);
946 cursor_get(vd->cursor);
947 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
948 vd->cursor_mask = g_malloc0(vd->cursor_msize);
949 cursor_get_mono_mask(c, 0, vd->cursor_mask);
951 QTAILQ_FOREACH(vs, &vd->clients, next) {
952 vnc_cursor_define(vs);
956 static int find_and_clear_dirty_height(VncState *vs,
957 int y, int last_x, int x, int height)
961 for (h = 1; h < (height - y); h++) {
962 if (!test_bit(last_x, vs->dirty[y + h])) {
965 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
972 * Figure out how much pending data we should allow in the output
973 * buffer before we throttle incremental display updates, and/or
974 * drop audio samples.
976 * We allow for equiv of 1 full display's worth of FB updates,
977 * and 1 second of audio samples. If audio backlog was larger
978 * than that the client would already suffering awful audio
979 * glitches, so dropping samples is no worse really).
981 static void vnc_update_throttle_offset(VncState *vs)
984 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
987 int freq = vs->as.freq;
988 /* We don't limit freq when reading settings from client, so
989 * it could be upto MAX_INT in size. 48khz is a sensible
990 * upper bound for trustworthy clients */
995 switch (vs->as.fmt) {
1010 offset += freq * bps * vs->as.nchannels;
1013 /* Put a floor of 1MB on offset, so that if we have a large pending
1014 * buffer and the display is resized to a small size & back again
1015 * we don't suddenly apply a tiny send limit
1017 offset = MAX(offset, 1024 * 1024);
1019 if (vs->throttle_output_offset != offset) {
1020 trace_vnc_client_throttle_threshold(
1021 vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1022 vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1025 vs->throttle_output_offset = offset;
1028 static bool vnc_should_update(VncState *vs)
1030 switch (vs->update) {
1031 case VNC_STATE_UPDATE_NONE:
1033 case VNC_STATE_UPDATE_INCREMENTAL:
1034 /* Only allow incremental updates if the pending send queue
1035 * is less than the permitted threshold, and the job worker
1036 * is completely idle.
1038 if (vs->output.offset < vs->throttle_output_offset &&
1039 vs->job_update == VNC_STATE_UPDATE_NONE) {
1042 trace_vnc_client_throttle_incremental(
1043 vs, vs->ioc, vs->job_update, vs->output.offset);
1045 case VNC_STATE_UPDATE_FORCE:
1046 /* Only allow forced updates if the pending send queue
1047 * does not contain a previous forced update, and the
1048 * job worker is completely idle.
1050 * Note this means we'll queue a forced update, even if
1051 * the output buffer size is otherwise over the throttle
1054 if (vs->force_update_offset == 0 &&
1055 vs->job_update == VNC_STATE_UPDATE_NONE) {
1058 trace_vnc_client_throttle_forced(
1059 vs, vs->ioc, vs->job_update, vs->force_update_offset);
1065 static int vnc_update_client(VncState *vs, int has_dirty)
1067 VncDisplay *vd = vs->vd;
1073 if (vs->disconnecting) {
1074 vnc_disconnect_finish(vs);
1078 vs->has_dirty += has_dirty;
1079 if (!vnc_should_update(vs)) {
1083 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1088 * Send screen updates to the vnc client using the server
1089 * surface and server dirty map. guest surface updates
1090 * happening in parallel don't disturb us, the next pass will
1091 * send them to the client.
1093 job = vnc_job_new(vs);
1095 height = pixman_image_get_height(vd->server);
1096 width = pixman_image_get_width(vd->server);
1102 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1103 height * VNC_DIRTY_BPL(vs),
1104 y * VNC_DIRTY_BPL(vs));
1105 if (offset == height * VNC_DIRTY_BPL(vs)) {
1106 /* no more dirty bits */
1109 y = offset / VNC_DIRTY_BPL(vs);
1110 x = offset % VNC_DIRTY_BPL(vs);
1111 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1112 VNC_DIRTY_BPL(vs), x);
1113 bitmap_clear(vs->dirty[y], x, x2 - x);
1114 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1115 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1117 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1118 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1120 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1128 vs->job_update = vs->update;
1129 vs->update = VNC_STATE_UPDATE_NONE;
1136 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1138 VncState *vs = opaque;
1141 case AUD_CNOTIFY_DISABLE:
1142 vnc_lock_output(vs);
1143 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1144 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1145 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1146 vnc_unlock_output(vs);
1150 case AUD_CNOTIFY_ENABLE:
1151 vnc_lock_output(vs);
1152 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1153 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1154 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1155 vnc_unlock_output(vs);
1161 static void audio_capture_destroy(void *opaque)
1165 static void audio_capture(void *opaque, void *buf, int size)
1167 VncState *vs = opaque;
1169 vnc_lock_output(vs);
1170 if (vs->output.offset < vs->throttle_output_offset) {
1171 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1172 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1173 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1174 vnc_write_u32(vs, size);
1175 vnc_write(vs, buf, size);
1177 trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1179 vnc_unlock_output(vs);
1183 static void audio_add(VncState *vs)
1185 struct audio_capture_ops ops;
1187 if (vs->audio_cap) {
1188 error_report("audio already running");
1192 ops.notify = audio_capture_notify;
1193 ops.destroy = audio_capture_destroy;
1194 ops.capture = audio_capture;
1196 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1197 if (!vs->audio_cap) {
1198 error_report("Failed to add audio capture");
1202 static void audio_del(VncState *vs)
1204 if (vs->audio_cap) {
1205 AUD_del_capture(vs->audio_cap, vs);
1206 vs->audio_cap = NULL;
1210 static void vnc_disconnect_start(VncState *vs)
1212 if (vs->disconnecting) {
1215 trace_vnc_client_disconnect_start(vs, vs->ioc);
1216 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1218 g_source_remove(vs->ioc_tag);
1221 qio_channel_close(vs->ioc, NULL);
1222 vs->disconnecting = TRUE;
1225 void vnc_disconnect_finish(VncState *vs)
1229 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1231 vnc_jobs_join(vs); /* Wait encoding jobs */
1233 vnc_lock_output(vs);
1234 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1236 buffer_free(&vs->input);
1237 buffer_free(&vs->output);
1239 qapi_free_VncClientInfo(vs->info);
1242 vnc_tight_clear(vs);
1245 #ifdef CONFIG_VNC_SASL
1246 vnc_sasl_client_cleanup(vs);
1247 #endif /* CONFIG_VNC_SASL */
1249 vnc_release_modifiers(vs);
1251 if (vs->mouse_mode_notifier.notify != NULL) {
1252 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1254 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1255 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1256 /* last client gone */
1257 vnc_update_server_surface(vs->vd);
1260 vnc_unlock_output(vs);
1262 qemu_mutex_destroy(&vs->output_mutex);
1263 if (vs->bh != NULL) {
1264 qemu_bh_delete(vs->bh);
1266 buffer_free(&vs->jobs_buffer);
1268 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1269 g_free(vs->lossy_rect[i]);
1271 g_free(vs->lossy_rect);
1273 object_unref(OBJECT(vs->ioc));
1275 object_unref(OBJECT(vs->sioc));
1280 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
1284 trace_vnc_client_eof(vs, vs->ioc);
1285 vnc_disconnect_start(vs);
1286 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1287 trace_vnc_client_io_error(vs, vs->ioc,
1288 errp ? error_get_pretty(*errp) :
1290 vnc_disconnect_start(vs);
1303 void vnc_client_error(VncState *vs)
1305 VNC_DEBUG("Closing down client sock: protocol error\n");
1306 vnc_disconnect_start(vs);
1311 * Called to write a chunk of data to the client socket. The data may
1312 * be the raw data, or may have already been encoded by SASL.
1313 * The data will be written either straight onto the socket, or
1314 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1316 * NB, it is theoretically possible to have 2 layers of encryption,
1317 * both SASL, and this TLS layer. It is highly unlikely in practice
1318 * though, since SASL encryption will typically be a no-op if TLS
1321 * Returns the number of bytes written, which may be less than
1322 * the requested 'datalen' if the socket would block. Returns
1323 * 0 on I/O error, and disconnects the client socket.
1325 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1329 ret = qio_channel_write(
1330 vs->ioc, (const char *)data, datalen, &err);
1331 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1332 return vnc_client_io_error(vs, ret, &err);
1337 * Called to write buffered data to the client socket, when not
1338 * using any SASL SSF encryption layers. Will write as much data
1339 * as possible without blocking. If all buffered data is written,
1340 * will switch the FD poll() handler back to read monitoring.
1342 * Returns the number of bytes written, which may be less than
1343 * the buffered output data if the socket would block. Returns
1344 * 0 on I/O error, and disconnects the client socket.
1346 static size_t vnc_client_write_plain(VncState *vs)
1351 #ifdef CONFIG_VNC_SASL
1352 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1353 vs->output.buffer, vs->output.capacity, vs->output.offset,
1354 vs->sasl.waitWriteSSF);
1356 if (vs->sasl.conn &&
1358 vs->sasl.waitWriteSSF) {
1359 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1361 vs->sasl.waitWriteSSF -= ret;
1363 #endif /* CONFIG_VNC_SASL */
1364 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1368 if (ret >= vs->force_update_offset) {
1369 if (vs->force_update_offset != 0) {
1370 trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1372 vs->force_update_offset = 0;
1374 vs->force_update_offset -= ret;
1376 offset = vs->output.offset;
1377 buffer_advance(&vs->output, ret);
1378 if (offset >= vs->throttle_output_offset &&
1379 vs->output.offset < vs->throttle_output_offset) {
1380 trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1383 if (vs->output.offset == 0) {
1385 g_source_remove(vs->ioc_tag);
1387 vs->ioc_tag = qio_channel_add_watch(
1388 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1396 * First function called whenever there is data to be written to
1397 * the client socket. Will delegate actual work according to whether
1398 * SASL SSF layers are enabled (thus requiring encryption calls)
1400 static void vnc_client_write_locked(VncState *vs)
1402 #ifdef CONFIG_VNC_SASL
1403 if (vs->sasl.conn &&
1405 !vs->sasl.waitWriteSSF) {
1406 vnc_client_write_sasl(vs);
1408 #endif /* CONFIG_VNC_SASL */
1410 vnc_client_write_plain(vs);
1414 static void vnc_client_write(VncState *vs)
1417 vnc_lock_output(vs);
1418 if (vs->output.offset) {
1419 vnc_client_write_locked(vs);
1420 } else if (vs->ioc != NULL) {
1422 g_source_remove(vs->ioc_tag);
1424 vs->ioc_tag = qio_channel_add_watch(
1425 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1427 vnc_unlock_output(vs);
1430 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1432 vs->read_handler = func;
1433 vs->read_handler_expect = expecting;
1438 * Called to read a chunk of data from the client socket. The data may
1439 * be the raw data, or may need to be further decoded by SASL.
1440 * The data will be read either straight from to the socket, or
1441 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1443 * NB, it is theoretically possible to have 2 layers of encryption,
1444 * both SASL, and this TLS layer. It is highly unlikely in practice
1445 * though, since SASL encryption will typically be a no-op if TLS
1448 * Returns the number of bytes read, which may be less than
1449 * the requested 'datalen' if the socket would block. Returns
1450 * 0 on I/O error or EOF, and disconnects the client socket.
1452 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1456 ret = qio_channel_read(
1457 vs->ioc, (char *)data, datalen, &err);
1458 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1459 return vnc_client_io_error(vs, ret, &err);
1464 * Called to read data from the client socket to the input buffer,
1465 * when not using any SASL SSF encryption layers. Will read as much
1466 * data as possible without blocking.
1468 * Returns the number of bytes read, which may be less than
1469 * the requested 'datalen' if the socket would block. Returns
1470 * 0 on I/O error or EOF, and disconnects the client socket.
1472 static size_t vnc_client_read_plain(VncState *vs)
1475 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1476 vs->input.buffer, vs->input.capacity, vs->input.offset);
1477 buffer_reserve(&vs->input, 4096);
1478 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1481 vs->input.offset += ret;
1485 static void vnc_jobs_bh(void *opaque)
1487 VncState *vs = opaque;
1489 vnc_jobs_consume_buffer(vs);
1493 * First function called whenever there is more data to be read from
1494 * the client socket. Will delegate actual work according to whether
1495 * SASL SSF layers are enabled (thus requiring decryption calls)
1496 * Returns 0 on success, -1 if client disconnected
1498 static int vnc_client_read(VncState *vs)
1502 #ifdef CONFIG_VNC_SASL
1503 if (vs->sasl.conn && vs->sasl.runSSF)
1504 ret = vnc_client_read_sasl(vs);
1506 #endif /* CONFIG_VNC_SASL */
1507 ret = vnc_client_read_plain(vs);
1509 if (vs->disconnecting) {
1510 vnc_disconnect_finish(vs);
1516 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1517 size_t len = vs->read_handler_expect;
1520 ret = vs->read_handler(vs, vs->input.buffer, len);
1521 if (vs->disconnecting) {
1522 vnc_disconnect_finish(vs);
1527 buffer_advance(&vs->input, len);
1529 vs->read_handler_expect = ret;
1535 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1536 GIOCondition condition, void *opaque)
1538 VncState *vs = opaque;
1539 if (condition & G_IO_IN) {
1540 if (vnc_client_read(vs) < 0) {
1544 if (condition & G_IO_OUT) {
1545 vnc_client_write(vs);
1552 * Scale factor to apply to vs->throttle_output_offset when checking for
1553 * hard limit. Worst case normal usage could be x2, if we have a complete
1554 * incremental update and complete forced update in the output buffer.
1555 * So x3 should be good enough, but we pick x5 to be conservative and thus
1556 * (hopefully) never trigger incorrectly.
1558 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1560 void vnc_write(VncState *vs, const void *data, size_t len)
1562 if (vs->disconnecting) {
1565 /* Protection against malicious client/guest to prevent our output
1566 * buffer growing without bound if client stops reading data. This
1567 * should rarely trigger, because we have earlier throttling code
1568 * which stops issuing framebuffer updates and drops audio data
1569 * if the throttle_output_offset value is exceeded. So we only reach
1570 * this higher level if a huge number of pseudo-encodings get
1571 * triggered while data can't be sent on the socket.
1573 * NB throttle_output_offset can be zero during early protocol
1574 * handshake, or from the job thread's VncState clone
1576 if (vs->throttle_output_offset != 0 &&
1577 vs->output.offset > (vs->throttle_output_offset *
1578 VNC_THROTTLE_OUTPUT_LIMIT_SCALE)) {
1579 trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1580 vs->throttle_output_offset);
1581 vnc_disconnect_start(vs);
1584 buffer_reserve(&vs->output, len);
1586 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1588 g_source_remove(vs->ioc_tag);
1590 vs->ioc_tag = qio_channel_add_watch(
1591 vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1594 buffer_append(&vs->output, data, len);
1597 void vnc_write_s32(VncState *vs, int32_t value)
1599 vnc_write_u32(vs, *(uint32_t *)&value);
1602 void vnc_write_u32(VncState *vs, uint32_t value)
1606 buf[0] = (value >> 24) & 0xFF;
1607 buf[1] = (value >> 16) & 0xFF;
1608 buf[2] = (value >> 8) & 0xFF;
1609 buf[3] = value & 0xFF;
1611 vnc_write(vs, buf, 4);
1614 void vnc_write_u16(VncState *vs, uint16_t value)
1618 buf[0] = (value >> 8) & 0xFF;
1619 buf[1] = value & 0xFF;
1621 vnc_write(vs, buf, 2);
1624 void vnc_write_u8(VncState *vs, uint8_t value)
1626 vnc_write(vs, (char *)&value, 1);
1629 void vnc_flush(VncState *vs)
1631 vnc_lock_output(vs);
1632 if (vs->ioc != NULL && vs->output.offset) {
1633 vnc_client_write_locked(vs);
1635 vnc_unlock_output(vs);
1638 static uint8_t read_u8(uint8_t *data, size_t offset)
1640 return data[offset];
1643 static uint16_t read_u16(uint8_t *data, size_t offset)
1645 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1648 static int32_t read_s32(uint8_t *data, size_t offset)
1650 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1651 (data[offset + 2] << 8) | data[offset + 3]);
1654 uint32_t read_u32(uint8_t *data, size_t offset)
1656 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1657 (data[offset + 2] << 8) | data[offset + 3]);
1660 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1664 static void check_pointer_type_change(Notifier *notifier, void *data)
1666 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1667 int absolute = qemu_input_is_absolute();
1669 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1670 vnc_lock_output(vs);
1671 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1672 vnc_write_u8(vs, 0);
1673 vnc_write_u16(vs, 1);
1674 vnc_framebuffer_update(vs, absolute, 0,
1675 pixman_image_get_width(vs->vd->server),
1676 pixman_image_get_height(vs->vd->server),
1677 VNC_ENCODING_POINTER_TYPE_CHANGE);
1678 vnc_unlock_output(vs);
1681 vs->absolute = absolute;
1684 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1686 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1687 [INPUT_BUTTON_LEFT] = 0x01,
1688 [INPUT_BUTTON_MIDDLE] = 0x02,
1689 [INPUT_BUTTON_RIGHT] = 0x04,
1690 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1691 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1693 QemuConsole *con = vs->vd->dcl.con;
1694 int width = pixman_image_get_width(vs->vd->server);
1695 int height = pixman_image_get_height(vs->vd->server);
1697 if (vs->last_bmask != button_mask) {
1698 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1699 vs->last_bmask = button_mask;
1703 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1704 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1705 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1706 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1707 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1709 if (vs->last_x != -1) {
1710 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1711 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1716 qemu_input_event_sync();
1719 static void reset_keys(VncState *vs)
1722 for(i = 0; i < 256; i++) {
1723 if (vs->modifiers_state[i]) {
1724 qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1725 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1726 vs->modifiers_state[i] = 0;
1731 static void press_key(VncState *vs, int keysym)
1733 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1734 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1735 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1736 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1737 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1740 static void vnc_led_state_change(VncState *vs)
1742 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1746 vnc_lock_output(vs);
1747 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1748 vnc_write_u8(vs, 0);
1749 vnc_write_u16(vs, 1);
1750 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1751 vnc_write_u8(vs, vs->vd->ledstate);
1752 vnc_unlock_output(vs);
1756 static void kbd_leds(void *opaque, int ledstate)
1758 VncDisplay *vd = opaque;
1761 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1762 (ledstate & QEMU_NUM_LOCK_LED),
1763 (ledstate & QEMU_SCROLL_LOCK_LED));
1765 if (ledstate == vd->ledstate) {
1769 vd->ledstate = ledstate;
1771 QTAILQ_FOREACH(client, &vd->clients, next) {
1772 vnc_led_state_change(client);
1776 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1778 /* QEMU console switch */
1780 case 0x2a: /* Left Shift */
1781 case 0x36: /* Right Shift */
1782 case 0x1d: /* Left CTRL */
1783 case 0x9d: /* Right CTRL */
1784 case 0x38: /* Left ALT */
1785 case 0xb8: /* Right ALT */
1787 vs->modifiers_state[keycode] = 1;
1789 vs->modifiers_state[keycode] = 0;
1791 case 0x02 ... 0x0a: /* '1' to '9' keys */
1792 if (vs->vd->dcl.con == NULL &&
1793 down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1794 /* Reset the modifiers sent to the current console */
1796 console_select(keycode - 0x02);
1800 case 0x3a: /* CapsLock */
1801 case 0x45: /* NumLock */
1803 vs->modifiers_state[keycode] ^= 1;
1807 /* Turn off the lock state sync logic if the client support the led
1810 if (down && vs->vd->lock_key_sync &&
1811 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1812 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1813 /* If the numlock state needs to change then simulate an additional
1814 keypress before sending this one. This will happen if the user
1815 toggles numlock away from the VNC window.
1817 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1818 if (!vs->modifiers_state[0x45]) {
1819 trace_vnc_key_sync_numlock(true);
1820 vs->modifiers_state[0x45] = 1;
1821 press_key(vs, 0xff7f);
1824 if (vs->modifiers_state[0x45]) {
1825 trace_vnc_key_sync_numlock(false);
1826 vs->modifiers_state[0x45] = 0;
1827 press_key(vs, 0xff7f);
1832 if (down && vs->vd->lock_key_sync &&
1833 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1834 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1835 /* If the capslock state needs to change then simulate an additional
1836 keypress before sending this one. This will happen if the user
1837 toggles capslock away from the VNC window.
1839 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1840 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1841 int capslock = !!(vs->modifiers_state[0x3a]);
1843 if (uppercase == shift) {
1844 trace_vnc_key_sync_capslock(false);
1845 vs->modifiers_state[0x3a] = 0;
1846 press_key(vs, 0xffe5);
1849 if (uppercase != shift) {
1850 trace_vnc_key_sync_capslock(true);
1851 vs->modifiers_state[0x3a] = 1;
1852 press_key(vs, 0xffe5);
1857 if (qemu_console_is_graphic(NULL)) {
1858 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1859 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1861 bool numlock = vs->modifiers_state[0x45];
1862 bool control = (vs->modifiers_state[0x1d] ||
1863 vs->modifiers_state[0x9d]);
1864 /* QEMU console emulation */
1867 case 0x2a: /* Left Shift */
1868 case 0x36: /* Right Shift */
1869 case 0x1d: /* Left CTRL */
1870 case 0x9d: /* Right CTRL */
1871 case 0x38: /* Left ALT */
1872 case 0xb8: /* Right ALT */
1875 kbd_put_keysym(QEMU_KEY_UP);
1878 kbd_put_keysym(QEMU_KEY_DOWN);
1881 kbd_put_keysym(QEMU_KEY_LEFT);
1884 kbd_put_keysym(QEMU_KEY_RIGHT);
1887 kbd_put_keysym(QEMU_KEY_DELETE);
1890 kbd_put_keysym(QEMU_KEY_HOME);
1893 kbd_put_keysym(QEMU_KEY_END);
1896 kbd_put_keysym(QEMU_KEY_PAGEUP);
1899 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1903 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1906 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1909 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1912 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1915 kbd_put_keysym('5');
1918 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1921 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1924 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1927 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1930 kbd_put_keysym('0');
1933 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1937 kbd_put_keysym('/');
1940 kbd_put_keysym('*');
1943 kbd_put_keysym('-');
1946 kbd_put_keysym('+');
1949 kbd_put_keysym('\n');
1954 kbd_put_keysym(sym & 0x1f);
1956 kbd_put_keysym(sym);
1964 static void vnc_release_modifiers(VncState *vs)
1966 static const int keycodes[] = {
1967 /* shift, control, alt keys, both left & right */
1968 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1972 if (!qemu_console_is_graphic(NULL)) {
1975 for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1976 keycode = keycodes[i];
1977 if (!vs->modifiers_state[keycode]) {
1980 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1981 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1985 static const char *code2name(int keycode)
1987 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
1990 static void key_event(VncState *vs, int down, uint32_t sym)
1995 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1996 lsym = lsym - 'A' + 'a';
1999 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
2000 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
2001 do_key_event(vs, down, keycode, sym);
2004 static void ext_key_event(VncState *vs, int down,
2005 uint32_t sym, uint16_t keycode)
2007 /* if the user specifies a keyboard layout, always use it */
2008 if (keyboard_layout) {
2009 key_event(vs, down, sym);
2011 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2012 do_key_event(vs, down, keycode, sym);
2016 static void framebuffer_update_request(VncState *vs, int incremental,
2017 int x, int y, int w, int h)
2020 if (vs->update != VNC_STATE_UPDATE_FORCE) {
2021 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2024 vs->update = VNC_STATE_UPDATE_FORCE;
2025 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2029 static void send_ext_key_event_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_EXT_KEY_EVENT);
2039 vnc_unlock_output(vs);
2043 static void send_ext_audio_ack(VncState *vs)
2045 vnc_lock_output(vs);
2046 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2047 vnc_write_u8(vs, 0);
2048 vnc_write_u16(vs, 1);
2049 vnc_framebuffer_update(vs, 0, 0,
2050 pixman_image_get_width(vs->vd->server),
2051 pixman_image_get_height(vs->vd->server),
2052 VNC_ENCODING_AUDIO);
2053 vnc_unlock_output(vs);
2057 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2060 unsigned int enc = 0;
2063 vs->vnc_encoding = 0;
2064 vs->tight.compression = 9;
2065 vs->tight.quality = -1; /* Lossless by default */
2069 * Start from the end because the encodings are sent in order of preference.
2070 * This way the preferred encoding (first encoding defined in the array)
2071 * will be set at the end of the loop.
2073 for (i = n_encodings - 1; i >= 0; i--) {
2076 case VNC_ENCODING_RAW:
2077 vs->vnc_encoding = enc;
2079 case VNC_ENCODING_COPYRECT:
2080 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2082 case VNC_ENCODING_HEXTILE:
2083 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2084 vs->vnc_encoding = enc;
2086 case VNC_ENCODING_TIGHT:
2087 vs->features |= VNC_FEATURE_TIGHT_MASK;
2088 vs->vnc_encoding = enc;
2090 #ifdef CONFIG_VNC_PNG
2091 case VNC_ENCODING_TIGHT_PNG:
2092 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2093 vs->vnc_encoding = enc;
2096 case VNC_ENCODING_ZLIB:
2097 vs->features |= VNC_FEATURE_ZLIB_MASK;
2098 vs->vnc_encoding = enc;
2100 case VNC_ENCODING_ZRLE:
2101 vs->features |= VNC_FEATURE_ZRLE_MASK;
2102 vs->vnc_encoding = enc;
2104 case VNC_ENCODING_ZYWRLE:
2105 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2106 vs->vnc_encoding = enc;
2108 case VNC_ENCODING_DESKTOPRESIZE:
2109 vs->features |= VNC_FEATURE_RESIZE_MASK;
2111 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2112 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2114 case VNC_ENCODING_RICH_CURSOR:
2115 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2116 if (vs->vd->cursor) {
2117 vnc_cursor_define(vs);
2120 case VNC_ENCODING_EXT_KEY_EVENT:
2121 send_ext_key_event_ack(vs);
2123 case VNC_ENCODING_AUDIO:
2124 send_ext_audio_ack(vs);
2126 case VNC_ENCODING_WMVi:
2127 vs->features |= VNC_FEATURE_WMVI_MASK;
2129 case VNC_ENCODING_LED_STATE:
2130 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2132 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2133 vs->tight.compression = (enc & 0x0F);
2135 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2136 if (vs->vd->lossy) {
2137 vs->tight.quality = (enc & 0x0F);
2141 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2145 vnc_desktop_resize(vs);
2146 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2147 vnc_led_state_change(vs);
2150 static void set_pixel_conversion(VncState *vs)
2152 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2154 if (fmt == VNC_SERVER_FB_FORMAT) {
2155 vs->write_pixels = vnc_write_pixels_copy;
2156 vnc_hextile_set_pixel_conversion(vs, 0);
2158 vs->write_pixels = vnc_write_pixels_generic;
2159 vnc_hextile_set_pixel_conversion(vs, 1);
2163 static void send_color_map(VncState *vs)
2167 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2168 vnc_write_u8(vs, 0); /* padding */
2169 vnc_write_u16(vs, 0); /* first color */
2170 vnc_write_u16(vs, 256); /* # of colors */
2172 for (i = 0; i < 256; i++) {
2173 PixelFormat *pf = &vs->client_pf;
2175 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2176 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2177 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2181 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2182 int big_endian_flag, int true_color_flag,
2183 int red_max, int green_max, int blue_max,
2184 int red_shift, int green_shift, int blue_shift)
2186 if (!true_color_flag) {
2187 /* Expose a reasonable default 256 color map */
2197 switch (bits_per_pixel) {
2203 vnc_client_error(vs);
2207 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2208 vs->client_pf.rbits = ctpopl(red_max);
2209 vs->client_pf.rshift = red_shift;
2210 vs->client_pf.rmask = red_max << red_shift;
2211 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2212 vs->client_pf.gbits = ctpopl(green_max);
2213 vs->client_pf.gshift = green_shift;
2214 vs->client_pf.gmask = green_max << green_shift;
2215 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2216 vs->client_pf.bbits = ctpopl(blue_max);
2217 vs->client_pf.bshift = blue_shift;
2218 vs->client_pf.bmask = blue_max << blue_shift;
2219 vs->client_pf.bits_per_pixel = bits_per_pixel;
2220 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2221 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2222 vs->client_be = big_endian_flag;
2224 if (!true_color_flag) {
2228 set_pixel_conversion(vs);
2230 graphic_hw_invalidate(vs->vd->dcl.con);
2231 graphic_hw_update(vs->vd->dcl.con);
2234 static void pixel_format_message (VncState *vs) {
2235 char pad[3] = { 0, 0, 0 };
2237 vs->client_pf = qemu_default_pixelformat(32);
2239 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2240 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2242 #ifdef HOST_WORDS_BIGENDIAN
2243 vnc_write_u8(vs, 1); /* big-endian-flag */
2245 vnc_write_u8(vs, 0); /* big-endian-flag */
2247 vnc_write_u8(vs, 1); /* true-color-flag */
2248 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2249 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2250 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2251 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2252 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2253 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2254 vnc_write(vs, pad, 3); /* padding */
2256 vnc_hextile_set_pixel_conversion(vs, 0);
2257 vs->write_pixels = vnc_write_pixels_copy;
2260 static void vnc_colordepth(VncState *vs)
2262 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2263 /* Sending a WMVi message to notify the client*/
2264 vnc_lock_output(vs);
2265 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2266 vnc_write_u8(vs, 0);
2267 vnc_write_u16(vs, 1); /* number of rects */
2268 vnc_framebuffer_update(vs, 0, 0,
2269 pixman_image_get_width(vs->vd->server),
2270 pixman_image_get_height(vs->vd->server),
2272 pixel_format_message(vs);
2273 vnc_unlock_output(vs);
2276 set_pixel_conversion(vs);
2280 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2284 VncDisplay *vd = vs->vd;
2287 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2291 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2295 set_pixel_format(vs, read_u8(data, 4),
2296 read_u8(data, 6), read_u8(data, 7),
2297 read_u16(data, 8), read_u16(data, 10),
2298 read_u16(data, 12), read_u8(data, 14),
2299 read_u8(data, 15), read_u8(data, 16));
2301 case VNC_MSG_CLIENT_SET_ENCODINGS:
2306 limit = read_u16(data, 2);
2308 return 4 + (limit * 4);
2310 limit = read_u16(data, 2);
2312 for (i = 0; i < limit; i++) {
2313 int32_t val = read_s32(data, 4 + (i * 4));
2314 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2317 set_encodings(vs, (int32_t *)(data + 4), limit);
2319 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2323 framebuffer_update_request(vs,
2324 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2325 read_u16(data, 6), read_u16(data, 8));
2327 case VNC_MSG_CLIENT_KEY_EVENT:
2331 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2333 case VNC_MSG_CLIENT_POINTER_EVENT:
2337 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2339 case VNC_MSG_CLIENT_CUT_TEXT:
2344 uint32_t dlen = read_u32(data, 4);
2345 if (dlen > (1 << 20)) {
2346 error_report("vnc: client_cut_text msg payload has %u bytes"
2347 " which exceeds our limit of 1MB.", dlen);
2348 vnc_client_error(vs);
2356 client_cut_text(vs, read_u32(data, 4), data + 8);
2358 case VNC_MSG_CLIENT_QEMU:
2362 switch (read_u8(data, 1)) {
2363 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2367 ext_key_event(vs, read_u16(data, 2),
2368 read_u32(data, 4), read_u32(data, 8));
2370 case VNC_MSG_CLIENT_QEMU_AUDIO:
2374 switch (read_u16 (data, 2)) {
2375 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2378 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2381 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2384 switch (read_u8(data, 4)) {
2385 case 0: vs->as.fmt = AUD_FMT_U8; break;
2386 case 1: vs->as.fmt = AUD_FMT_S8; break;
2387 case 2: vs->as.fmt = AUD_FMT_U16; break;
2388 case 3: vs->as.fmt = AUD_FMT_S16; break;
2389 case 4: vs->as.fmt = AUD_FMT_U32; break;
2390 case 5: vs->as.fmt = AUD_FMT_S32; break;
2392 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2393 vnc_client_error(vs);
2396 vs->as.nchannels = read_u8(data, 5);
2397 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2398 VNC_DEBUG("Invalid audio channel count %d\n",
2400 vnc_client_error(vs);
2403 vs->as.freq = read_u32(data, 6);
2406 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2407 vnc_client_error(vs);
2413 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2414 vnc_client_error(vs);
2419 VNC_DEBUG("Msg: %d\n", data[0]);
2420 vnc_client_error(vs);
2424 vnc_update_throttle_offset(vs);
2425 vnc_read_when(vs, protocol_client_msg, 1);
2429 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2435 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2436 switch (vs->vd->share_policy) {
2437 case VNC_SHARE_POLICY_IGNORE:
2439 * Ignore the shared flag. Nothing to do here.
2441 * Doesn't conform to the rfb spec but is traditional qemu
2442 * behavior, thus left here as option for compatibility
2446 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2448 * Policy: Allow clients ask for exclusive access.
2450 * Implementation: When a client asks for exclusive access,
2451 * disconnect all others. Shared connects are allowed as long
2452 * as no exclusive connection exists.
2454 * This is how the rfb spec suggests to handle the shared flag.
2456 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2458 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2462 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2463 client->share_mode != VNC_SHARE_MODE_SHARED) {
2466 vnc_disconnect_start(client);
2469 if (mode == VNC_SHARE_MODE_SHARED) {
2470 if (vs->vd->num_exclusive > 0) {
2471 vnc_disconnect_start(vs);
2476 case VNC_SHARE_POLICY_FORCE_SHARED:
2478 * Policy: Shared connects only.
2479 * Implementation: Disallow clients asking for exclusive access.
2481 * Useful for shared desktop sessions where you don't want
2482 * someone forgetting to say -shared when running the vnc
2483 * client disconnect everybody else.
2485 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2486 vnc_disconnect_start(vs);
2491 vnc_set_share_mode(vs, mode);
2493 if (vs->vd->num_shared > vs->vd->connections_limit) {
2494 vnc_disconnect_start(vs);
2498 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2499 pixman_image_get_width(vs->vd->server) >= 0);
2500 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2501 pixman_image_get_height(vs->vd->server) >= 0);
2502 vs->client_width = pixman_image_get_width(vs->vd->server);
2503 vs->client_height = pixman_image_get_height(vs->vd->server);
2504 vnc_write_u16(vs, vs->client_width);
2505 vnc_write_u16(vs, vs->client_height);
2507 pixel_format_message(vs);
2510 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2511 if (size > sizeof(buf)) {
2515 size = snprintf(buf, sizeof(buf), "QEMU");
2518 vnc_write_u32(vs, size);
2519 vnc_write(vs, buf, size);
2522 vnc_client_cache_auth(vs);
2523 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2525 vnc_read_when(vs, protocol_client_msg, 1);
2530 void start_client_init(VncState *vs)
2532 vnc_read_when(vs, protocol_client_init, 1);
2535 static void make_challenge(VncState *vs)
2539 srand(time(NULL)+getpid()+getpid()*987654+rand());
2541 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2542 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2545 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2547 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2549 unsigned char key[8];
2550 time_t now = time(NULL);
2551 QCryptoCipher *cipher = NULL;
2554 if (!vs->vd->password) {
2555 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2558 if (vs->vd->expires < now) {
2559 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2563 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2565 /* Calculate the expected challenge response */
2566 pwlen = strlen(vs->vd->password);
2567 for (i=0; i<sizeof(key); i++)
2568 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2570 cipher = qcrypto_cipher_new(
2571 QCRYPTO_CIPHER_ALG_DES_RFB,
2572 QCRYPTO_CIPHER_MODE_ECB,
2573 key, G_N_ELEMENTS(key),
2576 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2577 error_get_pretty(err));
2582 if (qcrypto_cipher_encrypt(cipher,
2585 VNC_AUTH_CHALLENGE_SIZE,
2587 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2588 error_get_pretty(err));
2593 /* Compare expected vs actual challenge response */
2594 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2595 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2598 trace_vnc_auth_pass(vs, vs->auth);
2599 vnc_write_u32(vs, 0); /* Accept auth */
2602 start_client_init(vs);
2605 qcrypto_cipher_free(cipher);
2609 vnc_write_u32(vs, 1); /* Reject auth */
2610 if (vs->minor >= 8) {
2611 static const char err[] = "Authentication failed";
2612 vnc_write_u32(vs, sizeof(err));
2613 vnc_write(vs, err, sizeof(err));
2616 vnc_client_error(vs);
2617 qcrypto_cipher_free(cipher);
2621 void start_auth_vnc(VncState *vs)
2624 /* Send client a 'random' challenge */
2625 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2628 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2632 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2634 /* We only advertise 1 auth scheme at a time, so client
2635 * must pick the one we sent. Verify this */
2636 if (data[0] != vs->auth) { /* Reject auth */
2637 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2638 vnc_write_u32(vs, 1);
2639 if (vs->minor >= 8) {
2640 static const char err[] = "Authentication failed";
2641 vnc_write_u32(vs, sizeof(err));
2642 vnc_write(vs, err, sizeof(err));
2644 vnc_client_error(vs);
2645 } else { /* Accept requested auth */
2646 trace_vnc_auth_start(vs, vs->auth);
2649 if (vs->minor >= 8) {
2650 vnc_write_u32(vs, 0); /* Accept auth completion */
2653 trace_vnc_auth_pass(vs, vs->auth);
2654 start_client_init(vs);
2661 case VNC_AUTH_VENCRYPT:
2662 start_auth_vencrypt(vs);
2665 #ifdef CONFIG_VNC_SASL
2667 start_auth_sasl(vs);
2669 #endif /* CONFIG_VNC_SASL */
2671 default: /* Should not be possible, but just in case */
2672 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2673 vnc_write_u8(vs, 1);
2674 if (vs->minor >= 8) {
2675 static const char err[] = "Authentication failed";
2676 vnc_write_u32(vs, sizeof(err));
2677 vnc_write(vs, err, sizeof(err));
2679 vnc_client_error(vs);
2685 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2689 memcpy(local, version, 12);
2692 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2693 VNC_DEBUG("Malformed protocol version %s\n", local);
2694 vnc_client_error(vs);
2697 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2698 if (vs->major != 3 ||
2704 VNC_DEBUG("Unsupported client version\n");
2705 vnc_write_u32(vs, VNC_AUTH_INVALID);
2707 vnc_client_error(vs);
2710 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2711 * as equivalent to v3.3 by servers
2713 if (vs->minor == 4 || vs->minor == 5)
2716 if (vs->minor == 3) {
2717 trace_vnc_auth_start(vs, vs->auth);
2718 if (vs->auth == VNC_AUTH_NONE) {
2719 vnc_write_u32(vs, vs->auth);
2721 trace_vnc_auth_pass(vs, vs->auth);
2722 start_client_init(vs);
2723 } else if (vs->auth == VNC_AUTH_VNC) {
2724 VNC_DEBUG("Tell client VNC auth\n");
2725 vnc_write_u32(vs, vs->auth);
2729 trace_vnc_auth_fail(vs, vs->auth,
2730 "Unsupported auth method for v3.3", "");
2731 vnc_write_u32(vs, VNC_AUTH_INVALID);
2733 vnc_client_error(vs);
2736 vnc_write_u8(vs, 1); /* num auth */
2737 vnc_write_u8(vs, vs->auth);
2738 vnc_read_when(vs, protocol_client_auth, 1);
2745 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2747 struct VncSurface *vs = &vd->guest;
2749 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2752 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2756 w = (x + w) / VNC_STAT_RECT;
2757 h = (y + h) / VNC_STAT_RECT;
2761 for (j = y; j <= h; j++) {
2762 for (i = x; i <= w; i++) {
2763 vs->lossy_rect[j][i] = 1;
2768 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2771 int sty = y / VNC_STAT_RECT;
2772 int stx = x / VNC_STAT_RECT;
2775 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2776 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2778 QTAILQ_FOREACH(vs, &vd->clients, next) {
2781 /* kernel send buffers are full -> refresh later */
2782 if (vs->output.offset) {
2786 if (!vs->lossy_rect[sty][stx]) {
2790 vs->lossy_rect[sty][stx] = 0;
2791 for (j = 0; j < VNC_STAT_RECT; ++j) {
2792 bitmap_set(vs->dirty[y + j],
2793 x / VNC_DIRTY_PIXELS_PER_BIT,
2794 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2802 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2804 int width = MIN(pixman_image_get_width(vd->guest.fb),
2805 pixman_image_get_width(vd->server));
2806 int height = MIN(pixman_image_get_height(vd->guest.fb),
2807 pixman_image_get_height(vd->server));
2812 for (y = 0; y < height; y += VNC_STAT_RECT) {
2813 for (x = 0; x < width; x += VNC_STAT_RECT) {
2814 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2816 rect->updated = false;
2820 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2822 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2825 vd->guest.last_freq_check = *tv;
2827 for (y = 0; y < height; y += VNC_STAT_RECT) {
2828 for (x = 0; x < width; x += VNC_STAT_RECT) {
2829 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2830 int count = ARRAY_SIZE(rect->times);
2831 struct timeval min, max;
2833 if (!timerisset(&rect->times[count - 1])) {
2837 max = rect->times[(rect->idx + count - 1) % count];
2838 qemu_timersub(tv, &max, &res);
2840 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2842 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2843 memset(rect->times, 0, sizeof (rect->times));
2847 min = rect->times[rect->idx];
2848 max = rect->times[(rect->idx + count - 1) % count];
2849 qemu_timersub(&max, &min, &res);
2851 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2852 rect->freq /= count;
2853 rect->freq = 1. / rect->freq;
2859 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2865 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2866 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2868 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2869 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2870 total += vnc_stat_rect(vs->vd, i, j)->freq;
2882 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2886 rect = vnc_stat_rect(vd, x, y);
2887 if (rect->updated) {
2890 rect->times[rect->idx] = *tv;
2891 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2892 rect->updated = true;
2895 static int vnc_refresh_server_surface(VncDisplay *vd)
2897 int width = MIN(pixman_image_get_width(vd->guest.fb),
2898 pixman_image_get_width(vd->server));
2899 int height = MIN(pixman_image_get_height(vd->guest.fb),
2900 pixman_image_get_height(vd->server));
2901 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2902 uint8_t *guest_row0 = NULL, *server_row0;
2905 pixman_image_t *tmpbuf = NULL;
2907 struct timeval tv = { 0, 0 };
2909 if (!vd->non_adaptive) {
2910 gettimeofday(&tv, NULL);
2911 has_dirty = vnc_update_stats(vd, &tv);
2915 * Walk through the guest dirty map.
2916 * Check and copy modified bits from guest to server surface.
2917 * Update server dirty map.
2919 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2920 server_stride = guest_stride = guest_ll =
2921 pixman_image_get_stride(vd->server);
2922 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2924 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2925 int width = pixman_image_get_width(vd->server);
2926 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2929 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2930 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2931 guest_stride = pixman_image_get_stride(vd->guest.fb);
2932 guest_ll = pixman_image_get_width(vd->guest.fb) * (DIV_ROUND_UP(guest_bpp, 8));
2934 line_bytes = MIN(server_stride, guest_ll);
2938 uint8_t *guest_ptr, *server_ptr;
2939 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2940 height * VNC_DIRTY_BPL(&vd->guest),
2941 y * VNC_DIRTY_BPL(&vd->guest));
2942 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2943 /* no more dirty bits */
2946 y = offset / VNC_DIRTY_BPL(&vd->guest);
2947 x = offset % VNC_DIRTY_BPL(&vd->guest);
2949 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2951 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2952 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2953 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2955 guest_ptr = guest_row0 + y * guest_stride;
2957 guest_ptr += x * cmp_bytes;
2959 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2960 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2961 int _cmp_bytes = cmp_bytes;
2962 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2965 if ((x + 1) * cmp_bytes > line_bytes) {
2966 _cmp_bytes = line_bytes - x * cmp_bytes;
2968 assert(_cmp_bytes >= 0);
2969 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2972 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2973 if (!vd->non_adaptive) {
2974 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2977 QTAILQ_FOREACH(vs, &vd->clients, next) {
2978 set_bit(x, vs->dirty[y]);
2985 qemu_pixman_image_unref(tmpbuf);
2989 static void vnc_refresh(DisplayChangeListener *dcl)
2991 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2993 int has_dirty, rects = 0;
2995 if (QTAILQ_EMPTY(&vd->clients)) {
2996 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
3000 graphic_hw_update(vd->dcl.con);
3002 if (vnc_trylock_display(vd)) {
3003 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3007 has_dirty = vnc_refresh_server_surface(vd);
3008 vnc_unlock_display(vd);
3010 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3011 rects += vnc_update_client(vs, has_dirty);
3012 /* vs might be free()ed here */
3015 if (has_dirty && rects) {
3016 vd->dcl.update_interval /= 2;
3017 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3018 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3021 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3022 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3023 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3028 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3029 bool skipauth, bool websocket)
3031 VncState *vs = g_new0(VncState, 1);
3032 bool first_client = QTAILQ_EMPTY(&vd->clients);
3035 trace_vnc_client_connect(vs, sioc);
3037 object_ref(OBJECT(vs->sioc));
3038 vs->ioc = QIO_CHANNEL(sioc);
3039 object_ref(OBJECT(vs->ioc));
3042 buffer_init(&vs->input, "vnc-input/%p", sioc);
3043 buffer_init(&vs->output, "vnc-output/%p", sioc);
3044 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
3046 buffer_init(&vs->tight.tight, "vnc-tight/%p", sioc);
3047 buffer_init(&vs->tight.zlib, "vnc-tight-zlib/%p", sioc);
3048 buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
3049 #ifdef CONFIG_VNC_JPEG
3050 buffer_init(&vs->tight.jpeg, "vnc-tight-jpeg/%p", sioc);
3052 #ifdef CONFIG_VNC_PNG
3053 buffer_init(&vs->tight.png, "vnc-tight-png/%p", sioc);
3055 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
3056 buffer_init(&vs->zrle.zrle, "vnc-zrle/%p", sioc);
3057 buffer_init(&vs->zrle.fb, "vnc-zrle-fb/%p", sioc);
3058 buffer_init(&vs->zrle.zlib, "vnc-zrle-zlib/%p", sioc);
3061 vs->auth = VNC_AUTH_NONE;
3062 vs->subauth = VNC_AUTH_INVALID;
3065 vs->auth = vd->ws_auth;
3066 vs->subauth = VNC_AUTH_INVALID;
3068 vs->auth = vd->auth;
3069 vs->subauth = vd->subauth;
3072 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3073 sioc, websocket, vs->auth, vs->subauth);
3075 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3076 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3077 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3080 VNC_DEBUG("New client on socket %p\n", vs->sioc);
3081 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3082 qio_channel_set_blocking(vs->ioc, false, NULL);
3084 g_source_remove(vs->ioc_tag);
3089 vs->ioc_tag = qio_channel_add_watch(
3090 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
3092 vs->ioc_tag = qio_channel_add_watch(
3093 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
3096 vs->ioc_tag = qio_channel_add_watch(
3097 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
3100 vnc_client_cache_addr(vs);
3101 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3102 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3107 vs->as.freq = 44100;
3108 vs->as.nchannels = 2;
3109 vs->as.fmt = AUD_FMT_S16;
3110 vs->as.endianness = 0;
3112 qemu_mutex_init(&vs->output_mutex);
3113 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3115 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3117 vnc_update_server_surface(vd);
3120 graphic_hw_update(vd->dcl.con);
3122 if (!vs->websocket) {
3123 vnc_start_protocol(vs);
3126 if (vd->num_connecting > vd->connections_limit) {
3127 QTAILQ_FOREACH(vs, &vd->clients, next) {
3128 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3129 vnc_disconnect_start(vs);
3136 void vnc_start_protocol(VncState *vs)
3138 vnc_write(vs, "RFB 003.008\n", 12);
3140 vnc_read_when(vs, protocol_version, 12);
3142 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3143 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3146 static gboolean vnc_listen_io(QIOChannel *ioc,
3147 GIOCondition condition,
3150 VncDisplay *vd = opaque;
3151 QIOChannelSocket *sioc = NULL;
3153 bool isWebsock = false;
3156 for (i = 0; i < vd->nlwebsock; i++) {
3157 if (ioc == QIO_CHANNEL(vd->lwebsock[i])) {
3163 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), &err);
3165 qio_channel_set_name(QIO_CHANNEL(sioc),
3166 isWebsock ? "vnc-ws-server" : "vnc-server");
3167 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
3168 vnc_connect(vd, sioc, false, isWebsock);
3169 object_unref(OBJECT(sioc));
3171 /* client probably closed connection before we got there */
3178 static const DisplayChangeListenerOps dcl_ops = {
3180 .dpy_refresh = vnc_refresh,
3181 .dpy_gfx_update = vnc_dpy_update,
3182 .dpy_gfx_switch = vnc_dpy_switch,
3183 .dpy_gfx_check_format = qemu_pixman_check_format,
3184 .dpy_mouse_set = vnc_mouse_set,
3185 .dpy_cursor_define = vnc_dpy_cursor_define,
3188 void vnc_display_init(const char *id)
3192 if (vnc_display_find(id) != NULL) {
3195 vd = g_malloc0(sizeof(*vd));
3197 vd->id = strdup(id);
3198 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3200 QTAILQ_INIT(&vd->clients);
3201 vd->expires = TIME_MAX;
3203 if (keyboard_layout) {
3204 trace_vnc_key_map_init(keyboard_layout);
3205 vd->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
3207 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
3210 if (!vd->kbd_layout) {
3214 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3215 vd->connections_limit = 32;
3217 qemu_mutex_init(&vd->mutex);
3218 vnc_start_worker_thread();
3220 vd->dcl.ops = &dcl_ops;
3221 register_displaychangelistener(&vd->dcl);
3225 static void vnc_display_close(VncDisplay *vd)
3231 vd->is_unix = false;
3232 for (i = 0; i < vd->nlsock; i++) {
3233 if (vd->lsock_tag[i]) {
3234 g_source_remove(vd->lsock_tag[i]);
3236 object_unref(OBJECT(vd->lsock[i]));
3239 g_free(vd->lsock_tag);
3241 vd->lsock_tag = NULL;
3244 for (i = 0; i < vd->nlwebsock; i++) {
3245 if (vd->lwebsock_tag[i]) {
3246 g_source_remove(vd->lwebsock_tag[i]);
3248 object_unref(OBJECT(vd->lwebsock[i]));
3250 g_free(vd->lwebsock);
3251 g_free(vd->lwebsock_tag);
3252 vd->lwebsock = NULL;
3253 vd->lwebsock_tag = NULL;
3256 vd->auth = VNC_AUTH_INVALID;
3257 vd->subauth = VNC_AUTH_INVALID;
3259 object_unparent(OBJECT(vd->tlscreds));
3260 vd->tlscreds = NULL;
3262 g_free(vd->tlsaclname);
3263 vd->tlsaclname = NULL;
3264 if (vd->lock_key_sync) {
3265 qemu_remove_led_event_handler(vd->led);
3270 int vnc_display_password(const char *id, const char *password)
3272 VncDisplay *vd = vnc_display_find(id);
3277 if (vd->auth == VNC_AUTH_NONE) {
3278 error_printf_unless_qmp("If you want use passwords please enable "
3279 "password auth using '-vnc ${dpy},password'.\n");
3283 g_free(vd->password);
3284 vd->password = g_strdup(password);
3289 int vnc_display_pw_expire(const char *id, time_t expires)
3291 VncDisplay *vd = vnc_display_find(id);
3297 vd->expires = expires;
3301 static void vnc_display_print_local_addr(VncDisplay *vd)
3303 SocketAddress *addr;
3310 addr = qio_channel_socket_get_local_address(vd->lsock[0], &err);
3315 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3316 qapi_free_SocketAddress(addr);
3319 error_printf_unless_qmp("VNC server running on %s:%s\n",
3322 qapi_free_SocketAddress(addr);
3325 static QemuOptsList qemu_vnc_opts = {
3327 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3328 .implied_opt_name = "vnc",
3332 .type = QEMU_OPT_STRING,
3334 .name = "websocket",
3335 .type = QEMU_OPT_STRING,
3337 .name = "tls-creds",
3338 .type = QEMU_OPT_STRING,
3340 /* Deprecated in favour of tls-creds */
3342 .type = QEMU_OPT_STRING,
3345 .type = QEMU_OPT_STRING,
3348 .type = QEMU_OPT_STRING,
3351 .type = QEMU_OPT_NUMBER,
3353 .name = "connections",
3354 .type = QEMU_OPT_NUMBER,
3357 .type = QEMU_OPT_NUMBER,
3360 .type = QEMU_OPT_BOOL,
3363 .type = QEMU_OPT_BOOL,
3366 .type = QEMU_OPT_BOOL,
3369 .type = QEMU_OPT_BOOL,
3371 .name = "lock-key-sync",
3372 .type = QEMU_OPT_BOOL,
3374 .name = "key-delay-ms",
3375 .type = QEMU_OPT_NUMBER,
3378 .type = QEMU_OPT_BOOL,
3380 /* Deprecated in favour of tls-creds */
3382 .type = QEMU_OPT_BOOL,
3384 /* Deprecated in favour of tls-creds */
3385 .name = "x509verify",
3386 .type = QEMU_OPT_STRING,
3389 .type = QEMU_OPT_BOOL,
3392 .type = QEMU_OPT_BOOL,
3394 .name = "non-adaptive",
3395 .type = QEMU_OPT_BOOL,
3397 { /* end of list */ }
3403 vnc_display_setup_auth(int *auth,
3405 QCryptoTLSCreds *tlscreds,
3412 * We have a choice of 3 authentication options
3418 * The channel can be run in 2 modes
3423 * And TLS can use 2 types of credentials
3428 * We thus have 9 possible logical combinations
3433 * 4. tls + anon + none
3434 * 5. tls + anon + vnc
3435 * 6. tls + anon + sasl
3436 * 7. tls + x509 + none
3437 * 8. tls + x509 + vnc
3438 * 9. tls + x509 + sasl
3440 * These need to be mapped into the VNC auth schemes
3441 * in an appropriate manner. In regular VNC, all the
3442 * TLS options get mapped into VNC_AUTH_VENCRYPT
3445 * In websockets, the https:// protocol already provides
3446 * TLS support, so there is no need to make use of the
3447 * VeNCrypt extension. Furthermore, websockets browser
3448 * clients could not use VeNCrypt even if they wanted to,
3449 * as they cannot control when the TLS handshake takes
3450 * place. Thus there is no option but to rely on https://,
3451 * meaning combinations 4->6 and 7->9 will be mapped to
3452 * VNC auth schemes in the same way as combos 1->3.
3454 * Regardless of fact that we have a different mapping to
3455 * VNC auth mechs for plain VNC vs websockets VNC, the end
3456 * result has the same security characteristics.
3458 if (websocket || !tlscreds) {
3460 VNC_DEBUG("Initializing VNC server with password auth\n");
3461 *auth = VNC_AUTH_VNC;
3463 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3464 *auth = VNC_AUTH_SASL;
3466 VNC_DEBUG("Initializing VNC server with no auth\n");
3467 *auth = VNC_AUTH_NONE;
3469 *subauth = VNC_AUTH_INVALID;
3471 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3472 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3473 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3474 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3476 if (!is_x509 && !is_anon) {
3478 "Unsupported TLS cred type %s",
3479 object_get_typename(OBJECT(tlscreds)));
3482 *auth = VNC_AUTH_VENCRYPT;
3485 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3486 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3488 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3489 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3494 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3495 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3497 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3498 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3502 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3503 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3505 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3506 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3515 * Handle back compat with old CLI syntax by creating some
3516 * suitable QCryptoTLSCreds objects
3518 static QCryptoTLSCreds *
3519 vnc_display_create_creds(bool x509,
3525 gchar *credsid = g_strdup_printf("tlsvnc%s", id);
3526 Object *parent = object_get_objects_root();
3531 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
3535 "endpoint", "server",
3537 "verify-peer", x509verify ? "yes" : "no",
3540 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
3544 "endpoint", "server",
3551 error_propagate(errp, err);
3555 return QCRYPTO_TLS_CREDS(creds);
3559 static int vnc_display_get_address(const char *addrstr,
3568 SocketAddress **retaddr,
3572 SocketAddress *addr = NULL;
3574 addr = g_new0(SocketAddress, 1);
3576 if (strncmp(addrstr, "unix:", 5) == 0) {
3577 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3578 addr->u.q_unix.path = g_strdup(addrstr + 5);
3581 error_setg(errp, "UNIX sockets not supported with websock");
3586 error_setg(errp, "Port range not support with UNIX socket");
3593 unsigned long long baseport = 0;
3594 InetSocketAddress *inet;
3596 port = strrchr(addrstr, ':');
3602 error_setg(errp, "no vnc port specified");
3606 hostlen = port - addrstr;
3608 if (*port == '\0') {
3609 error_setg(errp, "vnc port cannot be empty");
3614 addr->type = SOCKET_ADDRESS_TYPE_INET;
3615 inet = &addr->u.inet;
3616 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3617 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3619 inet->host = g_strndup(addrstr, hostlen);
3621 /* plain VNC port is just an offset, for websocket
3622 * port is absolute */
3624 if (g_str_equal(addrstr, "") ||
3625 g_str_equal(addrstr, "on")) {
3626 if (displaynum == -1) {
3627 error_setg(errp, "explicit websocket port is required");
3630 inet->port = g_strdup_printf(
3631 "%d", displaynum + 5700);
3633 inet->has_to = true;
3634 inet->to = to + 5700;
3637 inet->port = g_strdup(port);
3640 int offset = reverse ? 0 : 5900;
3641 if (parse_uint_full(port, &baseport, 10) < 0) {
3642 error_setg(errp, "can't convert to a number: %s", port);
3645 if (baseport > 65535 ||
3646 baseport + offset > 65535) {
3647 error_setg(errp, "port %s out of range", port);
3650 inet->port = g_strdup_printf(
3651 "%d", (int)baseport + offset);
3654 inet->has_to = true;
3655 inet->to = to + offset;
3660 inet->has_ipv4 = has_ipv4;
3662 inet->has_ipv6 = has_ipv6;
3671 qapi_free_SocketAddress(addr);
3676 static void vnc_free_addresses(SocketAddress ***retsaddr,
3681 for (i = 0; i < *retnsaddr; i++) {
3682 qapi_free_SocketAddress((*retsaddr)[i]);
3690 static int vnc_display_get_addresses(QemuOpts *opts,
3692 SocketAddress ***retsaddr,
3694 SocketAddress ***retwsaddr,
3698 SocketAddress *saddr = NULL;
3699 SocketAddress *wsaddr = NULL;
3700 QemuOptsIter addriter;
3702 int to = qemu_opt_get_number(opts, "to", 0);
3703 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3704 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3705 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3706 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3707 int displaynum = -1;
3715 addr = qemu_opt_get(opts, "vnc");
3716 if (addr == NULL || g_str_equal(addr, "none")) {
3720 if (qemu_opt_get(opts, "websocket") &&
3721 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3723 "SHA1 hash support is required for websockets");
3727 qemu_opt_iter_init(&addriter, opts, "vnc");
3728 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3730 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3737 /* Historical compat - first listen address can be used
3738 * to set the default websocket port
3740 if (displaynum == -1) {
3743 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3744 (*retsaddr)[(*retnsaddr)++] = saddr;
3747 /* If we had multiple primary displays, we don't do defaults
3748 * for websocket, and require explicit config instead. */
3749 if (*retnsaddr > 1) {
3753 qemu_opt_iter_init(&addriter, opts, "websocket");
3754 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3755 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3758 &wsaddr, errp) < 0) {
3762 /* Historical compat - if only a single listen address was
3763 * provided, then this is used to set the default listen
3764 * address for websocket too
3766 if (*retnsaddr == 1 &&
3767 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3768 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3769 g_str_equal(wsaddr->u.inet.host, "") &&
3770 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3771 g_free(wsaddr->u.inet.host);
3772 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3775 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3776 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3782 vnc_free_addresses(retsaddr, retnsaddr);
3783 vnc_free_addresses(retwsaddr, retnwsaddr);
3788 static int vnc_display_connect(VncDisplay *vd,
3789 SocketAddress **saddr,
3791 SocketAddress **wsaddr,
3795 /* connect to viewer */
3796 QIOChannelSocket *sioc = NULL;
3798 error_setg(errp, "Cannot use websockets in reverse mode");
3802 error_setg(errp, "Expected a single address in reverse mode");
3805 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3806 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3807 sioc = qio_channel_socket_new();
3808 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3809 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3812 vnc_connect(vd, sioc, false, false);
3813 object_unref(OBJECT(sioc));
3818 static int vnc_display_listen_addr(VncDisplay *vd,
3819 SocketAddress *addr,
3821 QIOChannelSocket ***lsock,
3826 QIODNSResolver *resolver = qio_dns_resolver_get_instance();
3827 SocketAddress **rawaddrs = NULL;
3828 size_t nrawaddrs = 0;
3829 Error *listenerr = NULL;
3830 bool listening = false;
3833 if (qio_dns_resolver_lookup_sync(resolver, addr, &nrawaddrs,
3834 &rawaddrs, errp) < 0) {
3838 for (i = 0; i < nrawaddrs; i++) {
3839 QIOChannelSocket *sioc = qio_channel_socket_new();
3841 qio_channel_set_name(QIO_CHANNEL(sioc), name);
3842 if (qio_channel_socket_listen_sync(
3843 sioc, rawaddrs[i], listenerr == NULL ? &listenerr : NULL) < 0) {
3844 object_unref(OBJECT(sioc));
3849 *lsock = g_renew(QIOChannelSocket *, *lsock, *nlsock);
3850 *lsock_tag = g_renew(guint, *lsock_tag, *nlsock);
3852 (*lsock)[*nlsock - 1] = sioc;
3853 (*lsock_tag)[*nlsock - 1] = 0;
3856 for (i = 0; i < nrawaddrs; i++) {
3857 qapi_free_SocketAddress(rawaddrs[i]);
3863 error_propagate(errp, listenerr);
3866 error_free(listenerr);
3870 for (i = 0; i < *nlsock; i++) {
3871 (*lsock_tag)[i] = qio_channel_add_watch(
3872 QIO_CHANNEL((*lsock)[i]),
3873 G_IO_IN, vnc_listen_io, vd, NULL);
3880 static int vnc_display_listen(VncDisplay *vd,
3881 SocketAddress **saddr,
3883 SocketAddress **wsaddr,
3889 for (i = 0; i < nsaddr; i++) {
3890 if (vnc_display_listen_addr(vd, saddr[i],
3899 for (i = 0; i < nwsaddr; i++) {
3900 if (vnc_display_listen_addr(vd, wsaddr[i],
3914 void vnc_display_open(const char *id, Error **errp)
3916 VncDisplay *vd = vnc_display_find(id);
3917 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3918 SocketAddress **saddr = NULL, **wsaddr = NULL;
3919 size_t nsaddr, nwsaddr;
3920 const char *share, *device_id;
3922 bool password = false;
3923 bool reverse = false;
3926 #ifdef CONFIG_VNC_SASL
3930 int lock_key_sync = 1;
3934 error_setg(errp, "VNC display not active");
3937 vnc_display_close(vd);
3943 reverse = qemu_opt_get_bool(opts, "reverse", false);
3944 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3945 &wsaddr, &nwsaddr, errp) < 0) {
3949 password = qemu_opt_get_bool(opts, "password", false);
3951 if (fips_get_state()) {
3953 "VNC password auth disabled due to FIPS mode, "
3954 "consider using the VeNCrypt or SASL authentication "
3955 "methods as an alternative");
3958 if (!qcrypto_cipher_supports(
3959 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3961 "Cipher backend does not support DES RFB algorithm");
3966 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3967 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3968 sasl = qemu_opt_get_bool(opts, "sasl", false);
3969 #ifndef CONFIG_VNC_SASL
3971 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3974 #endif /* CONFIG_VNC_SASL */
3975 credid = qemu_opt_get(opts, "tls-creds");
3978 if (qemu_opt_get(opts, "tls") ||
3979 qemu_opt_get(opts, "x509") ||
3980 qemu_opt_get(opts, "x509verify")) {
3982 "'tls-creds' parameter is mutually exclusive with "
3983 "'tls', 'x509' and 'x509verify' parameters");
3987 creds = object_resolve_path_component(
3988 object_get_objects_root(), credid);
3990 error_setg(errp, "No TLS credentials with id '%s'",
3994 vd->tlscreds = (QCryptoTLSCreds *)
3995 object_dynamic_cast(creds,
3996 TYPE_QCRYPTO_TLS_CREDS);
3997 if (!vd->tlscreds) {
3998 error_setg(errp, "Object with id '%s' is not TLS credentials",
4002 object_ref(OBJECT(vd->tlscreds));
4004 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4006 "Expecting TLS credentials with a server endpoint");
4011 bool tls = false, x509 = false, x509verify = false;
4012 tls = qemu_opt_get_bool(opts, "tls", false);
4014 path = qemu_opt_get(opts, "x509");
4019 path = qemu_opt_get(opts, "x509verify");
4025 vd->tlscreds = vnc_display_create_creds(x509,
4030 if (!vd->tlscreds) {
4035 acl = qemu_opt_get_bool(opts, "acl", false);
4037 share = qemu_opt_get(opts, "share");
4039 if (strcmp(share, "ignore") == 0) {
4040 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
4041 } else if (strcmp(share, "allow-exclusive") == 0) {
4042 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4043 } else if (strcmp(share, "force-shared") == 0) {
4044 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
4046 error_setg(errp, "unknown vnc share= option");
4050 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4052 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
4054 #ifdef CONFIG_VNC_JPEG
4055 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
4057 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4058 /* adaptive updates are only used with tight encoding and
4059 * if lossy updates are enabled so we can disable all the
4060 * calculations otherwise */
4062 vd->non_adaptive = true;
4066 if (strcmp(vd->id, "default") == 0) {
4067 vd->tlsaclname = g_strdup("vnc.x509dname");
4069 vd->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vd->id);
4071 qemu_acl_init(vd->tlsaclname);
4073 #ifdef CONFIG_VNC_SASL
4077 if (strcmp(vd->id, "default") == 0) {
4078 aclname = g_strdup("vnc.username");
4080 aclname = g_strdup_printf("vnc.%s.username", vd->id);
4082 vd->sasl.acl = qemu_acl_init(aclname);
4087 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4088 vd->tlscreds, password,
4089 sasl, false, errp) < 0) {
4092 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4094 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4095 vd->tlscreds, password,
4096 sasl, true, errp) < 0) {
4099 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
4101 #ifdef CONFIG_VNC_SASL
4102 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
4103 error_setg(errp, "Failed to initialize SASL auth: %s",
4104 sasl_errstring(saslErr, NULL, NULL));
4108 vd->lock_key_sync = lock_key_sync;
4109 if (lock_key_sync) {
4110 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4113 vd->key_delay_ms = key_delay_ms;
4115 device_id = qemu_opt_get(opts, "display");
4117 int head = qemu_opt_get_number(opts, "head", 0);
4120 con = qemu_console_lookup_by_device_name(device_id, head, &err);
4122 error_propagate(errp, err);
4129 if (con != vd->dcl.con) {
4130 unregister_displaychangelistener(&vd->dcl);
4132 register_displaychangelistener(&vd->dcl);
4135 if (saddr == NULL) {
4140 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4144 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4149 if (qemu_opt_get(opts, "to")) {
4150 vnc_display_print_local_addr(vd);
4154 vnc_free_addresses(&saddr, &nsaddr);
4155 vnc_free_addresses(&wsaddr, &nwsaddr);
4159 vnc_display_close(vd);
4163 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4165 VncDisplay *vd = vnc_display_find(id);
4166 QIOChannelSocket *sioc;
4172 sioc = qio_channel_socket_new_fd(csock, NULL);
4174 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4175 vnc_connect(vd, sioc, skipauth, false);
4176 object_unref(OBJECT(sioc));
4180 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4185 id = g_strdup("default");
4186 while (qemu_opts_find(olist, id)) {
4188 id = g_strdup_printf("vnc%d", i++);
4190 qemu_opts_set_id(opts, id);
4193 QemuOpts *vnc_parse(const char *str, Error **errp)
4195 QemuOptsList *olist = qemu_find_opts("vnc");
4196 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
4203 id = qemu_opts_id(opts);
4205 /* auto-assign id if not present */
4206 vnc_auto_assign_id(olist, opts);
4211 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4213 Error *local_err = NULL;
4214 char *id = (char *)qemu_opts_id(opts);
4217 vnc_display_init(id);
4218 vnc_display_open(id, &local_err);
4219 if (local_err != NULL) {
4220 error_reportf_err(local_err, "Failed to start VNC server: ");
4226 static void vnc_register_config(void)
4228 qemu_add_opts(&qemu_vnc_opts);
4230 opts_init(vnc_register_config);