2 * QEMU VNC display driver
5 * Copyright (C) 2006 Fabrice Bellard
6 * Copyright (C) 2009 Red Hat, Inc
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 #include "qemu/osdep.h"
31 #include "hw/qdev-core.h"
32 #include "sysemu/sysemu.h"
33 #include "qemu/error-report.h"
34 #include "qemu/main-loop.h"
35 #include "qemu/module.h"
36 #include "qemu/option.h"
37 #include "qemu/sockets.h"
38 #include "qemu/timer.h"
39 #include "authz/list.h"
40 #include "qemu/config-file.h"
41 #include "qapi/qapi-emit-events.h"
42 #include "qapi/qapi-events-ui.h"
43 #include "qapi/error.h"
44 #include "qapi/qapi-commands-ui.h"
46 #include "crypto/hash.h"
47 #include "crypto/tlscredsanon.h"
48 #include "crypto/tlscredsx509.h"
49 #include "crypto/random.h"
50 #include "qom/object_interfaces.h"
51 #include "qemu/cutils.h"
52 #include "io/dns-resolver.h"
54 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
55 #define VNC_REFRESH_INTERVAL_INC 50
56 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
57 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
58 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
60 #include "vnc_keysym.h"
61 #include "crypto/cipher.h"
63 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
64 QTAILQ_HEAD_INITIALIZER(vnc_displays);
66 static int vnc_cursor_define(VncState *vs);
67 static void vnc_update_throttle_offset(VncState *vs);
69 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
72 static const char *mn[] = {
74 [VNC_SHARE_MODE_CONNECTING] = "connecting",
75 [VNC_SHARE_MODE_SHARED] = "shared",
76 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
77 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
79 fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
80 vs->ioc, mn[vs->share_mode], mn[mode]);
83 switch (vs->share_mode) {
84 case VNC_SHARE_MODE_CONNECTING:
85 vs->vd->num_connecting--;
87 case VNC_SHARE_MODE_SHARED:
90 case VNC_SHARE_MODE_EXCLUSIVE:
91 vs->vd->num_exclusive--;
97 vs->share_mode = mode;
99 switch (vs->share_mode) {
100 case VNC_SHARE_MODE_CONNECTING:
101 vs->vd->num_connecting++;
103 case VNC_SHARE_MODE_SHARED:
104 vs->vd->num_shared++;
106 case VNC_SHARE_MODE_EXCLUSIVE:
107 vs->vd->num_exclusive++;
115 static void vnc_init_basic_info(SocketAddress *addr,
119 switch (addr->type) {
120 case SOCKET_ADDRESS_TYPE_INET:
121 info->host = g_strdup(addr->u.inet.host);
122 info->service = g_strdup(addr->u.inet.port);
123 if (addr->u.inet.ipv6) {
124 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
126 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
130 case SOCKET_ADDRESS_TYPE_UNIX:
131 info->host = g_strdup("");
132 info->service = g_strdup(addr->u.q_unix.path);
133 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
136 case SOCKET_ADDRESS_TYPE_VSOCK:
137 case SOCKET_ADDRESS_TYPE_FD:
138 error_setg(errp, "Unsupported socket address type %s",
139 SocketAddressType_str(addr->type));
148 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
152 SocketAddress *addr = NULL;
155 error_setg(errp, "No listener socket available");
159 addr = qio_channel_socket_get_local_address(ioc, errp);
164 vnc_init_basic_info(addr, info, errp);
165 qapi_free_SocketAddress(addr);
168 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
172 SocketAddress *addr = NULL;
174 addr = qio_channel_socket_get_remote_address(ioc, errp);
179 vnc_init_basic_info(addr, info, errp);
180 qapi_free_SocketAddress(addr);
183 static const char *vnc_auth_name(VncDisplay *vd) {
185 case VNC_AUTH_INVALID:
201 case VNC_AUTH_VENCRYPT:
202 switch (vd->subauth) {
203 case VNC_AUTH_VENCRYPT_PLAIN:
204 return "vencrypt+plain";
205 case VNC_AUTH_VENCRYPT_TLSNONE:
206 return "vencrypt+tls+none";
207 case VNC_AUTH_VENCRYPT_TLSVNC:
208 return "vencrypt+tls+vnc";
209 case VNC_AUTH_VENCRYPT_TLSPLAIN:
210 return "vencrypt+tls+plain";
211 case VNC_AUTH_VENCRYPT_X509NONE:
212 return "vencrypt+x509+none";
213 case VNC_AUTH_VENCRYPT_X509VNC:
214 return "vencrypt+x509+vnc";
215 case VNC_AUTH_VENCRYPT_X509PLAIN:
216 return "vencrypt+x509+plain";
217 case VNC_AUTH_VENCRYPT_TLSSASL:
218 return "vencrypt+tls+sasl";
219 case VNC_AUTH_VENCRYPT_X509SASL:
220 return "vencrypt+x509+sasl";
230 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
235 if (!vd->listener || !vd->listener->nsioc) {
239 info = g_malloc0(sizeof(*info));
240 vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
241 qapi_VncServerInfo_base(info), &err);
242 info->has_auth = true;
243 info->auth = g_strdup(vnc_auth_name(vd));
245 qapi_free_VncServerInfo(info);
252 static void vnc_client_cache_auth(VncState *client)
259 client->info->x509_dname =
260 qcrypto_tls_session_get_peer_name(client->tls);
261 client->info->has_x509_dname =
262 client->info->x509_dname != NULL;
264 #ifdef CONFIG_VNC_SASL
265 if (client->sasl.conn &&
266 client->sasl.username) {
267 client->info->has_sasl_username = true;
268 client->info->sasl_username = g_strdup(client->sasl.username);
273 static void vnc_client_cache_addr(VncState *client)
277 client->info = g_malloc0(sizeof(*client->info));
278 vnc_init_basic_info_from_remote_addr(client->sioc,
279 qapi_VncClientInfo_base(client->info),
281 client->info->websocket = client->websocket;
283 qapi_free_VncClientInfo(client->info);
289 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
297 si = vnc_server_info_get(vs->vd);
303 case QAPI_EVENT_VNC_CONNECTED:
304 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
306 case QAPI_EVENT_VNC_INITIALIZED:
307 qapi_event_send_vnc_initialized(si, vs->info);
309 case QAPI_EVENT_VNC_DISCONNECTED:
310 qapi_event_send_vnc_disconnected(si, vs->info);
316 qapi_free_VncServerInfo(si);
319 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
324 info = g_malloc0(sizeof(*info));
326 vnc_init_basic_info_from_remote_addr(client->sioc,
327 qapi_VncClientInfo_base(info),
331 qapi_free_VncClientInfo(info);
335 info->websocket = client->websocket;
338 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
339 info->has_x509_dname = info->x509_dname != NULL;
341 #ifdef CONFIG_VNC_SASL
342 if (client->sasl.conn && client->sasl.username) {
343 info->has_sasl_username = true;
344 info->sasl_username = g_strdup(client->sasl.username);
351 static VncDisplay *vnc_display_find(const char *id)
356 return QTAILQ_FIRST(&vnc_displays);
358 QTAILQ_FOREACH(vd, &vnc_displays, next) {
359 if (strcmp(id, vd->id) == 0) {
366 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
368 VncClientInfoList *cinfo, *prev = NULL;
371 QTAILQ_FOREACH(client, &vd->clients, next) {
372 cinfo = g_new0(VncClientInfoList, 1);
373 cinfo->value = qmp_query_vnc_client(client);
380 VncInfo *qmp_query_vnc(Error **errp)
382 VncInfo *info = g_malloc0(sizeof(*info));
383 VncDisplay *vd = vnc_display_find(NULL);
384 SocketAddress *addr = NULL;
386 if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
387 info->enabled = false;
389 info->enabled = true;
391 /* for compatibility with the original command */
392 info->has_clients = true;
393 info->clients = qmp_query_client_list(vd);
395 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
401 switch (addr->type) {
402 case SOCKET_ADDRESS_TYPE_INET:
403 info->host = g_strdup(addr->u.inet.host);
404 info->service = g_strdup(addr->u.inet.port);
405 if (addr->u.inet.ipv6) {
406 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
408 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
412 case SOCKET_ADDRESS_TYPE_UNIX:
413 info->host = g_strdup("");
414 info->service = g_strdup(addr->u.q_unix.path);
415 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
418 case SOCKET_ADDRESS_TYPE_VSOCK:
419 case SOCKET_ADDRESS_TYPE_FD:
420 error_setg(errp, "Unsupported socket address type %s",
421 SocketAddressType_str(addr->type));
427 info->has_host = true;
428 info->has_service = true;
429 info->has_family = true;
431 info->has_auth = true;
432 info->auth = g_strdup(vnc_auth_name(vd));
435 qapi_free_SocketAddress(addr);
439 qapi_free_SocketAddress(addr);
440 qapi_free_VncInfo(info);
445 static void qmp_query_auth(int auth, int subauth,
446 VncPrimaryAuth *qmp_auth,
447 VncVencryptSubAuth *qmp_vencrypt,
448 bool *qmp_has_vencrypt);
450 static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
454 VncServerInfo2List *prev)
456 VncServerInfo2List *list;
457 VncServerInfo2 *info;
461 addr = qio_channel_socket_get_local_address(ioc, &err);
467 info = g_new0(VncServerInfo2, 1);
468 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
469 qapi_free_SocketAddress(addr);
471 qapi_free_VncServerInfo2(info);
475 info->websocket = websocket;
477 qmp_query_auth(auth, subauth, &info->auth,
478 &info->vencrypt, &info->has_vencrypt);
480 list = g_new0(VncServerInfo2List, 1);
486 static void qmp_query_auth(int auth, int subauth,
487 VncPrimaryAuth *qmp_auth,
488 VncVencryptSubAuth *qmp_vencrypt,
489 bool *qmp_has_vencrypt)
493 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
496 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
499 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
502 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
505 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
508 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
510 case VNC_AUTH_VENCRYPT:
511 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
512 *qmp_has_vencrypt = true;
514 case VNC_AUTH_VENCRYPT_PLAIN:
515 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
517 case VNC_AUTH_VENCRYPT_TLSNONE:
518 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
520 case VNC_AUTH_VENCRYPT_TLSVNC:
521 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
523 case VNC_AUTH_VENCRYPT_TLSPLAIN:
524 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
526 case VNC_AUTH_VENCRYPT_X509NONE:
527 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
529 case VNC_AUTH_VENCRYPT_X509VNC:
530 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
532 case VNC_AUTH_VENCRYPT_X509PLAIN:
533 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
535 case VNC_AUTH_VENCRYPT_TLSSASL:
536 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
538 case VNC_AUTH_VENCRYPT_X509SASL:
539 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
542 *qmp_has_vencrypt = false;
547 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
551 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
556 VncInfo2List *qmp_query_vnc_servers(Error **errp)
558 VncInfo2List *item, *prev = NULL;
564 QTAILQ_FOREACH(vd, &vnc_displays, next) {
565 info = g_new0(VncInfo2, 1);
566 info->id = g_strdup(vd->id);
567 info->clients = qmp_query_client_list(vd);
568 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
569 &info->vencrypt, &info->has_vencrypt);
571 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
573 info->has_display = true;
574 info->display = g_strdup(dev->id);
576 for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
577 info->server = qmp_query_server_entry(
578 vd->listener->sioc[i], false, vd->auth, vd->subauth,
581 for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
582 info->server = qmp_query_server_entry(
583 vd->wslistener->sioc[i], true, vd->ws_auth,
584 vd->ws_subauth, info->server);
587 item = g_new0(VncInfo2List, 1);
596 1) Get the queue working for IO.
597 2) there is some weirdness when using the -S option (the screen is grey
598 and not totally invalidated
599 3) resolutions > 1024
602 static int vnc_update_client(VncState *vs, int has_dirty);
603 static void vnc_disconnect_start(VncState *vs);
605 static void vnc_colordepth(VncState *vs);
606 static void framebuffer_update_request(VncState *vs, int incremental,
607 int x_position, int y_position,
609 static void vnc_refresh(DisplayChangeListener *dcl);
610 static int vnc_refresh_server_surface(VncDisplay *vd);
612 static int vnc_width(VncDisplay *vd)
614 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
615 VNC_DIRTY_PIXELS_PER_BIT));
618 static int vnc_height(VncDisplay *vd)
620 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
623 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
624 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
626 int x, int y, int w, int h)
628 int width = vnc_width(vd);
629 int height = vnc_height(vd);
631 /* this is needed this to ensure we updated all affected
632 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
633 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
634 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
638 w = MIN(x + w, width) - x;
639 h = MIN(y + h, height);
642 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
643 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
647 static void vnc_dpy_update(DisplayChangeListener *dcl,
648 int x, int y, int w, int h)
650 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
651 struct VncSurface *s = &vd->guest;
653 vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
656 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
659 vnc_write_u16(vs, x);
660 vnc_write_u16(vs, y);
661 vnc_write_u16(vs, w);
662 vnc_write_u16(vs, h);
664 vnc_write_s32(vs, encoding);
668 static void vnc_desktop_resize(VncState *vs)
670 if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
673 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
674 vs->client_height == pixman_image_get_height(vs->vd->server)) {
678 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
679 pixman_image_get_width(vs->vd->server) >= 0);
680 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
681 pixman_image_get_height(vs->vd->server) >= 0);
682 vs->client_width = pixman_image_get_width(vs->vd->server);
683 vs->client_height = pixman_image_get_height(vs->vd->server);
685 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
687 vnc_write_u16(vs, 1); /* number of rects */
688 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
689 VNC_ENCODING_DESKTOPRESIZE);
690 vnc_unlock_output(vs);
694 static void vnc_abort_display_jobs(VncDisplay *vd)
698 QTAILQ_FOREACH(vs, &vd->clients, next) {
701 vnc_unlock_output(vs);
703 QTAILQ_FOREACH(vs, &vd->clients, next) {
706 QTAILQ_FOREACH(vs, &vd->clients, next) {
708 if (vs->update == VNC_STATE_UPDATE_NONE &&
709 vs->job_update != VNC_STATE_UPDATE_NONE) {
710 /* job aborted before completion */
711 vs->update = vs->job_update;
712 vs->job_update = VNC_STATE_UPDATE_NONE;
715 vnc_unlock_output(vs);
719 int vnc_server_fb_stride(VncDisplay *vd)
721 return pixman_image_get_stride(vd->server);
724 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
728 ptr = (uint8_t *)pixman_image_get_data(vd->server);
729 ptr += y * vnc_server_fb_stride(vd);
730 ptr += x * VNC_SERVER_FB_BYTES;
734 static void vnc_update_server_surface(VncDisplay *vd)
738 qemu_pixman_image_unref(vd->server);
741 if (QTAILQ_EMPTY(&vd->clients)) {
745 width = vnc_width(vd);
746 height = vnc_height(vd);
747 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
751 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
752 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
756 static bool vnc_check_pageflip(DisplaySurface *s1,
759 return (s1 != NULL &&
761 surface_width(s1) == surface_width(s2) &&
762 surface_height(s1) == surface_height(s2) &&
763 surface_format(s1) == surface_format(s2));
767 static void vnc_dpy_switch(DisplayChangeListener *dcl,
768 DisplaySurface *surface)
770 static const char placeholder_msg[] =
771 "Display output is not active.";
772 static DisplaySurface *placeholder;
773 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
774 bool pageflip = vnc_check_pageflip(vd->ds, surface);
777 if (surface == NULL) {
778 if (placeholder == NULL) {
779 placeholder = qemu_create_message_surface(640, 480, placeholder_msg);
781 surface = placeholder;
784 vnc_abort_display_jobs(vd);
788 qemu_pixman_image_unref(vd->guest.fb);
789 vd->guest.fb = pixman_image_ref(surface->image);
790 vd->guest.format = surface->format;
793 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
794 surface_width(surface),
795 surface_height(surface));
800 vnc_update_server_surface(vd);
802 QTAILQ_FOREACH(vs, &vd->clients, next) {
804 vnc_desktop_resize(vs);
805 if (vs->vd->cursor) {
806 vnc_cursor_define(vs);
808 memset(vs->dirty, 0x00, sizeof(vs->dirty));
809 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
812 vnc_update_throttle_offset(vs);
817 static void vnc_write_pixels_copy(VncState *vs,
818 void *pixels, int size)
820 vnc_write(vs, pixels, size);
823 /* slowest but generic code. */
824 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
828 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
829 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
830 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
831 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
833 # error need some bits here if you change VNC_SERVER_FB_FORMAT
835 v = (r << vs->client_pf.rshift) |
836 (g << vs->client_pf.gshift) |
837 (b << vs->client_pf.bshift);
838 switch (vs->client_pf.bytes_per_pixel) {
868 static void vnc_write_pixels_generic(VncState *vs,
869 void *pixels1, int size)
873 if (VNC_SERVER_FB_BYTES == 4) {
874 uint32_t *pixels = pixels1;
877 for (i = 0; i < n; i++) {
878 vnc_convert_pixel(vs, buf, pixels[i]);
879 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
884 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
888 VncDisplay *vd = vs->vd;
890 row = vnc_server_fb_ptr(vd, x, y);
891 for (i = 0; i < h; i++) {
892 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
893 row += vnc_server_fb_stride(vd);
898 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
901 bool encode_raw = false;
902 size_t saved_offs = vs->output.offset;
904 switch(vs->vnc_encoding) {
905 case VNC_ENCODING_ZLIB:
906 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
908 case VNC_ENCODING_HEXTILE:
909 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
910 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
912 case VNC_ENCODING_TIGHT:
913 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
915 case VNC_ENCODING_TIGHT_PNG:
916 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
918 case VNC_ENCODING_ZRLE:
919 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
921 case VNC_ENCODING_ZYWRLE:
922 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
929 /* If the client has the same pixel format as our internal buffer and
930 * a RAW encoding would need less space fall back to RAW encoding to
931 * save bandwidth and processing power in the client. */
932 if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
933 12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
934 vs->output.offset = saved_offs;
939 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
940 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
946 static void vnc_mouse_set(DisplayChangeListener *dcl,
947 int x, int y, int visible)
949 /* can we ask the client(s) to move the pointer ??? */
952 static int vnc_cursor_define(VncState *vs)
954 QEMUCursor *c = vs->vd->cursor;
957 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
959 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
960 vnc_write_u8(vs, 0); /* padding */
961 vnc_write_u16(vs, 1); /* # of rects */
962 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
963 VNC_ENCODING_RICH_CURSOR);
964 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
965 vnc_write_pixels_generic(vs, c->data, isize);
966 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
967 vnc_unlock_output(vs);
973 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
976 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
979 cursor_put(vd->cursor);
980 g_free(vd->cursor_mask);
983 cursor_get(vd->cursor);
984 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
985 vd->cursor_mask = g_malloc0(vd->cursor_msize);
986 cursor_get_mono_mask(c, 0, vd->cursor_mask);
988 QTAILQ_FOREACH(vs, &vd->clients, next) {
989 vnc_cursor_define(vs);
993 static int find_and_clear_dirty_height(VncState *vs,
994 int y, int last_x, int x, int height)
998 for (h = 1; h < (height - y); h++) {
999 if (!test_bit(last_x, vs->dirty[y + h])) {
1002 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1009 * Figure out how much pending data we should allow in the output
1010 * buffer before we throttle incremental display updates, and/or
1011 * drop audio samples.
1013 * We allow for equiv of 1 full display's worth of FB updates,
1014 * and 1 second of audio samples. If audio backlog was larger
1015 * than that the client would already suffering awful audio
1016 * glitches, so dropping samples is no worse really).
1018 static void vnc_update_throttle_offset(VncState *vs)
1021 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1023 if (vs->audio_cap) {
1025 switch (vs->as.fmt) {
1027 case AUDIO_FORMAT_U8:
1028 case AUDIO_FORMAT_S8:
1031 case AUDIO_FORMAT_U16:
1032 case AUDIO_FORMAT_S16:
1035 case AUDIO_FORMAT_U32:
1036 case AUDIO_FORMAT_S32:
1040 offset += vs->as.freq * bps * vs->as.nchannels;
1043 /* Put a floor of 1MB on offset, so that if we have a large pending
1044 * buffer and the display is resized to a small size & back again
1045 * we don't suddenly apply a tiny send limit
1047 offset = MAX(offset, 1024 * 1024);
1049 if (vs->throttle_output_offset != offset) {
1050 trace_vnc_client_throttle_threshold(
1051 vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1052 vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1055 vs->throttle_output_offset = offset;
1058 static bool vnc_should_update(VncState *vs)
1060 switch (vs->update) {
1061 case VNC_STATE_UPDATE_NONE:
1063 case VNC_STATE_UPDATE_INCREMENTAL:
1064 /* Only allow incremental updates if the pending send queue
1065 * is less than the permitted threshold, and the job worker
1066 * is completely idle.
1068 if (vs->output.offset < vs->throttle_output_offset &&
1069 vs->job_update == VNC_STATE_UPDATE_NONE) {
1072 trace_vnc_client_throttle_incremental(
1073 vs, vs->ioc, vs->job_update, vs->output.offset);
1075 case VNC_STATE_UPDATE_FORCE:
1076 /* Only allow forced updates if the pending send queue
1077 * does not contain a previous forced update, and the
1078 * job worker is completely idle.
1080 * Note this means we'll queue a forced update, even if
1081 * the output buffer size is otherwise over the throttle
1084 if (vs->force_update_offset == 0 &&
1085 vs->job_update == VNC_STATE_UPDATE_NONE) {
1088 trace_vnc_client_throttle_forced(
1089 vs, vs->ioc, vs->job_update, vs->force_update_offset);
1095 static int vnc_update_client(VncState *vs, int has_dirty)
1097 VncDisplay *vd = vs->vd;
1103 if (vs->disconnecting) {
1104 vnc_disconnect_finish(vs);
1108 vs->has_dirty += has_dirty;
1109 if (!vnc_should_update(vs)) {
1113 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1118 * Send screen updates to the vnc client using the server
1119 * surface and server dirty map. guest surface updates
1120 * happening in parallel don't disturb us, the next pass will
1121 * send them to the client.
1123 job = vnc_job_new(vs);
1125 height = pixman_image_get_height(vd->server);
1126 width = pixman_image_get_width(vd->server);
1132 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1133 height * VNC_DIRTY_BPL(vs),
1134 y * VNC_DIRTY_BPL(vs));
1135 if (offset == height * VNC_DIRTY_BPL(vs)) {
1136 /* no more dirty bits */
1139 y = offset / VNC_DIRTY_BPL(vs);
1140 x = offset % VNC_DIRTY_BPL(vs);
1141 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1142 VNC_DIRTY_BPL(vs), x);
1143 bitmap_clear(vs->dirty[y], x, x2 - x);
1144 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1145 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1147 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1148 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1150 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1158 vs->job_update = vs->update;
1159 vs->update = VNC_STATE_UPDATE_NONE;
1166 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1168 VncState *vs = opaque;
1170 assert(vs->magic == VNC_MAGIC);
1172 case AUD_CNOTIFY_DISABLE:
1173 vnc_lock_output(vs);
1174 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1175 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1176 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1177 vnc_unlock_output(vs);
1181 case AUD_CNOTIFY_ENABLE:
1182 vnc_lock_output(vs);
1183 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1184 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1185 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1186 vnc_unlock_output(vs);
1192 static void audio_capture_destroy(void *opaque)
1196 static void audio_capture(void *opaque, void *buf, int size)
1198 VncState *vs = opaque;
1200 assert(vs->magic == VNC_MAGIC);
1201 vnc_lock_output(vs);
1202 if (vs->output.offset < vs->throttle_output_offset) {
1203 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1204 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1205 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1206 vnc_write_u32(vs, size);
1207 vnc_write(vs, buf, size);
1209 trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1211 vnc_unlock_output(vs);
1215 static void audio_add(VncState *vs)
1217 struct audio_capture_ops ops;
1219 if (vs->audio_cap) {
1220 error_report("audio already running");
1224 ops.notify = audio_capture_notify;
1225 ops.destroy = audio_capture_destroy;
1226 ops.capture = audio_capture;
1228 vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
1229 if (!vs->audio_cap) {
1230 error_report("Failed to add audio capture");
1234 static void audio_del(VncState *vs)
1236 if (vs->audio_cap) {
1237 AUD_del_capture(vs->audio_cap, vs);
1238 vs->audio_cap = NULL;
1242 static void vnc_disconnect_start(VncState *vs)
1244 if (vs->disconnecting) {
1247 trace_vnc_client_disconnect_start(vs, vs->ioc);
1248 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1250 g_source_remove(vs->ioc_tag);
1253 qio_channel_close(vs->ioc, NULL);
1254 vs->disconnecting = TRUE;
1257 void vnc_disconnect_finish(VncState *vs)
1261 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1263 vnc_jobs_join(vs); /* Wait encoding jobs */
1265 vnc_lock_output(vs);
1266 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1268 buffer_free(&vs->input);
1269 buffer_free(&vs->output);
1271 qapi_free_VncClientInfo(vs->info);
1274 vnc_tight_clear(vs);
1277 #ifdef CONFIG_VNC_SASL
1278 vnc_sasl_client_cleanup(vs);
1279 #endif /* CONFIG_VNC_SASL */
1281 qkbd_state_lift_all_keys(vs->vd->kbd);
1283 if (vs->mouse_mode_notifier.notify != NULL) {
1284 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1286 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1287 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1288 /* last client gone */
1289 vnc_update_server_surface(vs->vd);
1292 vnc_unlock_output(vs);
1294 qemu_mutex_destroy(&vs->output_mutex);
1295 if (vs->bh != NULL) {
1296 qemu_bh_delete(vs->bh);
1298 buffer_free(&vs->jobs_buffer);
1300 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1301 g_free(vs->lossy_rect[i]);
1303 g_free(vs->lossy_rect);
1305 object_unref(OBJECT(vs->ioc));
1307 object_unref(OBJECT(vs->sioc));
1315 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
1319 trace_vnc_client_eof(vs, vs->ioc);
1320 vnc_disconnect_start(vs);
1321 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1322 trace_vnc_client_io_error(vs, vs->ioc,
1323 err ? error_get_pretty(err) : "Unknown");
1324 vnc_disconnect_start(vs);
1334 void vnc_client_error(VncState *vs)
1336 VNC_DEBUG("Closing down client sock: protocol error\n");
1337 vnc_disconnect_start(vs);
1342 * Called to write a chunk of data to the client socket. The data may
1343 * be the raw data, or may have already been encoded by SASL.
1344 * The data will be written either straight onto the socket, or
1345 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1347 * NB, it is theoretically possible to have 2 layers of encryption,
1348 * both SASL, and this TLS layer. It is highly unlikely in practice
1349 * though, since SASL encryption will typically be a no-op if TLS
1352 * Returns the number of bytes written, which may be less than
1353 * the requested 'datalen' if the socket would block. Returns
1354 * 0 on I/O error, and disconnects the client socket.
1356 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1360 ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
1361 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1362 return vnc_client_io_error(vs, ret, err);
1367 * Called to write buffered data to the client socket, when not
1368 * using any SASL SSF encryption layers. Will write as much data
1369 * as possible without blocking. If all buffered data is written,
1370 * will switch the FD poll() handler back to read monitoring.
1372 * Returns the number of bytes written, which may be less than
1373 * the buffered output data if the socket would block. Returns
1374 * 0 on I/O error, and disconnects the client socket.
1376 static size_t vnc_client_write_plain(VncState *vs)
1381 #ifdef CONFIG_VNC_SASL
1382 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1383 vs->output.buffer, vs->output.capacity, vs->output.offset,
1384 vs->sasl.waitWriteSSF);
1386 if (vs->sasl.conn &&
1388 vs->sasl.waitWriteSSF) {
1389 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1391 vs->sasl.waitWriteSSF -= ret;
1393 #endif /* CONFIG_VNC_SASL */
1394 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1398 if (ret >= vs->force_update_offset) {
1399 if (vs->force_update_offset != 0) {
1400 trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1402 vs->force_update_offset = 0;
1404 vs->force_update_offset -= ret;
1406 offset = vs->output.offset;
1407 buffer_advance(&vs->output, ret);
1408 if (offset >= vs->throttle_output_offset &&
1409 vs->output.offset < vs->throttle_output_offset) {
1410 trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1413 if (vs->output.offset == 0) {
1415 g_source_remove(vs->ioc_tag);
1417 vs->ioc_tag = qio_channel_add_watch(
1418 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1426 * First function called whenever there is data to be written to
1427 * the client socket. Will delegate actual work according to whether
1428 * SASL SSF layers are enabled (thus requiring encryption calls)
1430 static void vnc_client_write_locked(VncState *vs)
1432 #ifdef CONFIG_VNC_SASL
1433 if (vs->sasl.conn &&
1435 !vs->sasl.waitWriteSSF) {
1436 vnc_client_write_sasl(vs);
1438 #endif /* CONFIG_VNC_SASL */
1440 vnc_client_write_plain(vs);
1444 static void vnc_client_write(VncState *vs)
1446 assert(vs->magic == VNC_MAGIC);
1447 vnc_lock_output(vs);
1448 if (vs->output.offset) {
1449 vnc_client_write_locked(vs);
1450 } else if (vs->ioc != NULL) {
1452 g_source_remove(vs->ioc_tag);
1454 vs->ioc_tag = qio_channel_add_watch(
1455 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1457 vnc_unlock_output(vs);
1460 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1462 vs->read_handler = func;
1463 vs->read_handler_expect = expecting;
1468 * Called to read a chunk of data from the client socket. The data may
1469 * be the raw data, or may need to be further decoded by SASL.
1470 * The data will be read either straight from to the socket, or
1471 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1473 * NB, it is theoretically possible to have 2 layers of encryption,
1474 * both SASL, and this TLS layer. It is highly unlikely in practice
1475 * though, since SASL encryption will typically be a no-op if TLS
1478 * Returns the number of bytes read, which may be less than
1479 * the requested 'datalen' if the socket would block. Returns
1480 * 0 on I/O error or EOF, and disconnects the client socket.
1482 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1486 ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
1487 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1488 return vnc_client_io_error(vs, ret, err);
1493 * Called to read data from the client socket to the input buffer,
1494 * when not using any SASL SSF encryption layers. Will read as much
1495 * data as possible without blocking.
1497 * Returns the number of bytes read, which may be less than
1498 * the requested 'datalen' if the socket would block. Returns
1499 * 0 on I/O error or EOF, and disconnects the client socket.
1501 static size_t vnc_client_read_plain(VncState *vs)
1504 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1505 vs->input.buffer, vs->input.capacity, vs->input.offset);
1506 buffer_reserve(&vs->input, 4096);
1507 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1510 vs->input.offset += ret;
1514 static void vnc_jobs_bh(void *opaque)
1516 VncState *vs = opaque;
1518 assert(vs->magic == VNC_MAGIC);
1519 vnc_jobs_consume_buffer(vs);
1523 * First function called whenever there is more data to be read from
1524 * the client socket. Will delegate actual work according to whether
1525 * SASL SSF layers are enabled (thus requiring decryption calls)
1526 * Returns 0 on success, -1 if client disconnected
1528 static int vnc_client_read(VncState *vs)
1532 #ifdef CONFIG_VNC_SASL
1533 if (vs->sasl.conn && vs->sasl.runSSF)
1534 ret = vnc_client_read_sasl(vs);
1536 #endif /* CONFIG_VNC_SASL */
1537 ret = vnc_client_read_plain(vs);
1539 if (vs->disconnecting) {
1540 vnc_disconnect_finish(vs);
1546 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1547 size_t len = vs->read_handler_expect;
1550 ret = vs->read_handler(vs, vs->input.buffer, len);
1551 if (vs->disconnecting) {
1552 vnc_disconnect_finish(vs);
1557 buffer_advance(&vs->input, len);
1559 vs->read_handler_expect = ret;
1565 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1566 GIOCondition condition, void *opaque)
1568 VncState *vs = opaque;
1570 assert(vs->magic == VNC_MAGIC);
1571 if (condition & G_IO_IN) {
1572 if (vnc_client_read(vs) < 0) {
1573 /* vs is free()ed here */
1577 if (condition & G_IO_OUT) {
1578 vnc_client_write(vs);
1581 if (vs->disconnecting) {
1582 if (vs->ioc_tag != 0) {
1583 g_source_remove(vs->ioc_tag);
1592 * Scale factor to apply to vs->throttle_output_offset when checking for
1593 * hard limit. Worst case normal usage could be x2, if we have a complete
1594 * incremental update and complete forced update in the output buffer.
1595 * So x3 should be good enough, but we pick x5 to be conservative and thus
1596 * (hopefully) never trigger incorrectly.
1598 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1600 void vnc_write(VncState *vs, const void *data, size_t len)
1602 assert(vs->magic == VNC_MAGIC);
1603 if (vs->disconnecting) {
1606 /* Protection against malicious client/guest to prevent our output
1607 * buffer growing without bound if client stops reading data. This
1608 * should rarely trigger, because we have earlier throttling code
1609 * which stops issuing framebuffer updates and drops audio data
1610 * if the throttle_output_offset value is exceeded. So we only reach
1611 * this higher level if a huge number of pseudo-encodings get
1612 * triggered while data can't be sent on the socket.
1614 * NB throttle_output_offset can be zero during early protocol
1615 * handshake, or from the job thread's VncState clone
1617 if (vs->throttle_output_offset != 0 &&
1618 (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1619 vs->throttle_output_offset) {
1620 trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1621 vs->throttle_output_offset);
1622 vnc_disconnect_start(vs);
1625 buffer_reserve(&vs->output, len);
1627 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1629 g_source_remove(vs->ioc_tag);
1631 vs->ioc_tag = qio_channel_add_watch(
1632 vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1635 buffer_append(&vs->output, data, len);
1638 void vnc_write_s32(VncState *vs, int32_t value)
1640 vnc_write_u32(vs, *(uint32_t *)&value);
1643 void vnc_write_u32(VncState *vs, uint32_t value)
1647 buf[0] = (value >> 24) & 0xFF;
1648 buf[1] = (value >> 16) & 0xFF;
1649 buf[2] = (value >> 8) & 0xFF;
1650 buf[3] = value & 0xFF;
1652 vnc_write(vs, buf, 4);
1655 void vnc_write_u16(VncState *vs, uint16_t value)
1659 buf[0] = (value >> 8) & 0xFF;
1660 buf[1] = value & 0xFF;
1662 vnc_write(vs, buf, 2);
1665 void vnc_write_u8(VncState *vs, uint8_t value)
1667 vnc_write(vs, (char *)&value, 1);
1670 void vnc_flush(VncState *vs)
1672 vnc_lock_output(vs);
1673 if (vs->ioc != NULL && vs->output.offset) {
1674 vnc_client_write_locked(vs);
1676 if (vs->disconnecting) {
1677 if (vs->ioc_tag != 0) {
1678 g_source_remove(vs->ioc_tag);
1682 vnc_unlock_output(vs);
1685 static uint8_t read_u8(uint8_t *data, size_t offset)
1687 return data[offset];
1690 static uint16_t read_u16(uint8_t *data, size_t offset)
1692 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1695 static int32_t read_s32(uint8_t *data, size_t offset)
1697 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1698 (data[offset + 2] << 8) | data[offset + 3]);
1701 uint32_t read_u32(uint8_t *data, size_t offset)
1703 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1704 (data[offset + 2] << 8) | data[offset + 3]);
1707 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1711 static void check_pointer_type_change(Notifier *notifier, void *data)
1713 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1714 int absolute = qemu_input_is_absolute();
1716 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1717 vnc_lock_output(vs);
1718 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1719 vnc_write_u8(vs, 0);
1720 vnc_write_u16(vs, 1);
1721 vnc_framebuffer_update(vs, absolute, 0,
1722 pixman_image_get_width(vs->vd->server),
1723 pixman_image_get_height(vs->vd->server),
1724 VNC_ENCODING_POINTER_TYPE_CHANGE);
1725 vnc_unlock_output(vs);
1728 vs->absolute = absolute;
1731 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1733 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1734 [INPUT_BUTTON_LEFT] = 0x01,
1735 [INPUT_BUTTON_MIDDLE] = 0x02,
1736 [INPUT_BUTTON_RIGHT] = 0x04,
1737 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1738 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1740 QemuConsole *con = vs->vd->dcl.con;
1741 int width = pixman_image_get_width(vs->vd->server);
1742 int height = pixman_image_get_height(vs->vd->server);
1744 if (vs->last_bmask != button_mask) {
1745 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1746 vs->last_bmask = button_mask;
1750 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1751 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1752 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1753 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1754 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1756 if (vs->last_x != -1) {
1757 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1758 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1763 qemu_input_event_sync();
1766 static void press_key(VncState *vs, QKeyCode qcode)
1768 qkbd_state_key_event(vs->vd->kbd, qcode, true);
1769 qkbd_state_key_event(vs->vd->kbd, qcode, false);
1772 static void vnc_led_state_change(VncState *vs)
1774 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1778 vnc_lock_output(vs);
1779 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1780 vnc_write_u8(vs, 0);
1781 vnc_write_u16(vs, 1);
1782 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1783 vnc_write_u8(vs, vs->vd->ledstate);
1784 vnc_unlock_output(vs);
1788 static void kbd_leds(void *opaque, int ledstate)
1790 VncDisplay *vd = opaque;
1793 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1794 (ledstate & QEMU_NUM_LOCK_LED),
1795 (ledstate & QEMU_SCROLL_LOCK_LED));
1797 if (ledstate == vd->ledstate) {
1801 vd->ledstate = ledstate;
1803 QTAILQ_FOREACH(client, &vd->clients, next) {
1804 vnc_led_state_change(client);
1808 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1810 QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1812 /* QEMU console switch */
1814 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1815 if (vs->vd->dcl.con == NULL && down &&
1816 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1817 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1818 /* Reset the modifiers sent to the current console */
1819 qkbd_state_lift_all_keys(vs->vd->kbd);
1820 console_select(qcode - Q_KEY_CODE_1);
1827 /* Turn off the lock state sync logic if the client support the led
1830 if (down && vs->vd->lock_key_sync &&
1831 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1832 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1833 /* If the numlock state needs to change then simulate an additional
1834 keypress before sending this one. This will happen if the user
1835 toggles numlock away from the VNC window.
1837 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1838 if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1839 trace_vnc_key_sync_numlock(true);
1840 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1843 if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1844 trace_vnc_key_sync_numlock(false);
1845 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1850 if (down && vs->vd->lock_key_sync &&
1851 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1852 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1853 /* If the capslock state needs to change then simulate an additional
1854 keypress before sending this one. This will happen if the user
1855 toggles capslock away from the VNC window.
1857 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1858 bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1859 bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1861 if (uppercase == shift) {
1862 trace_vnc_key_sync_capslock(false);
1863 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1866 if (uppercase != shift) {
1867 trace_vnc_key_sync_capslock(true);
1868 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1873 qkbd_state_key_event(vs->vd->kbd, qcode, down);
1874 if (!qemu_console_is_graphic(NULL)) {
1875 bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1876 bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1877 /* QEMU console emulation */
1880 case 0x2a: /* Left Shift */
1881 case 0x36: /* Right Shift */
1882 case 0x1d: /* Left CTRL */
1883 case 0x9d: /* Right CTRL */
1884 case 0x38: /* Left ALT */
1885 case 0xb8: /* Right ALT */
1888 kbd_put_keysym(QEMU_KEY_UP);
1891 kbd_put_keysym(QEMU_KEY_DOWN);
1894 kbd_put_keysym(QEMU_KEY_LEFT);
1897 kbd_put_keysym(QEMU_KEY_RIGHT);
1900 kbd_put_keysym(QEMU_KEY_DELETE);
1903 kbd_put_keysym(QEMU_KEY_HOME);
1906 kbd_put_keysym(QEMU_KEY_END);
1909 kbd_put_keysym(QEMU_KEY_PAGEUP);
1912 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1916 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1919 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1922 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1925 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1928 kbd_put_keysym('5');
1931 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1934 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1937 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1940 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1943 kbd_put_keysym('0');
1946 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1950 kbd_put_keysym('/');
1953 kbd_put_keysym('*');
1956 kbd_put_keysym('-');
1959 kbd_put_keysym('+');
1962 kbd_put_keysym('\n');
1967 kbd_put_keysym(sym & 0x1f);
1969 kbd_put_keysym(sym);
1977 static const char *code2name(int keycode)
1979 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
1982 static void key_event(VncState *vs, int down, uint32_t sym)
1987 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1988 lsym = lsym - 'A' + 'a';
1991 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
1992 vs->vd->kbd, down) & SCANCODE_KEYMASK;
1993 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1994 do_key_event(vs, down, keycode, sym);
1997 static void ext_key_event(VncState *vs, int down,
1998 uint32_t sym, uint16_t keycode)
2000 /* if the user specifies a keyboard layout, always use it */
2001 if (keyboard_layout) {
2002 key_event(vs, down, sym);
2004 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2005 do_key_event(vs, down, keycode, sym);
2009 static void framebuffer_update_request(VncState *vs, int incremental,
2010 int x, int y, int w, int h)
2013 if (vs->update != VNC_STATE_UPDATE_FORCE) {
2014 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2017 vs->update = VNC_STATE_UPDATE_FORCE;
2018 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2022 static void send_ext_key_event_ack(VncState *vs)
2024 vnc_lock_output(vs);
2025 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2026 vnc_write_u8(vs, 0);
2027 vnc_write_u16(vs, 1);
2028 vnc_framebuffer_update(vs, 0, 0,
2029 pixman_image_get_width(vs->vd->server),
2030 pixman_image_get_height(vs->vd->server),
2031 VNC_ENCODING_EXT_KEY_EVENT);
2032 vnc_unlock_output(vs);
2036 static void send_ext_audio_ack(VncState *vs)
2038 vnc_lock_output(vs);
2039 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2040 vnc_write_u8(vs, 0);
2041 vnc_write_u16(vs, 1);
2042 vnc_framebuffer_update(vs, 0, 0,
2043 pixman_image_get_width(vs->vd->server),
2044 pixman_image_get_height(vs->vd->server),
2045 VNC_ENCODING_AUDIO);
2046 vnc_unlock_output(vs);
2050 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2053 unsigned int enc = 0;
2056 vs->vnc_encoding = 0;
2057 vs->tight->compression = 9;
2058 vs->tight->quality = -1; /* Lossless by default */
2062 * Start from the end because the encodings are sent in order of preference.
2063 * This way the preferred encoding (first encoding defined in the array)
2064 * will be set at the end of the loop.
2066 for (i = n_encodings - 1; i >= 0; i--) {
2069 case VNC_ENCODING_RAW:
2070 vs->vnc_encoding = enc;
2072 case VNC_ENCODING_COPYRECT:
2073 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2075 case VNC_ENCODING_HEXTILE:
2076 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2077 vs->vnc_encoding = enc;
2079 case VNC_ENCODING_TIGHT:
2080 vs->features |= VNC_FEATURE_TIGHT_MASK;
2081 vs->vnc_encoding = enc;
2083 #ifdef CONFIG_VNC_PNG
2084 case VNC_ENCODING_TIGHT_PNG:
2085 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2086 vs->vnc_encoding = enc;
2089 case VNC_ENCODING_ZLIB:
2090 vs->features |= VNC_FEATURE_ZLIB_MASK;
2091 vs->vnc_encoding = enc;
2093 case VNC_ENCODING_ZRLE:
2094 vs->features |= VNC_FEATURE_ZRLE_MASK;
2095 vs->vnc_encoding = enc;
2097 case VNC_ENCODING_ZYWRLE:
2098 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2099 vs->vnc_encoding = enc;
2101 case VNC_ENCODING_DESKTOPRESIZE:
2102 vs->features |= VNC_FEATURE_RESIZE_MASK;
2104 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2105 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2107 case VNC_ENCODING_RICH_CURSOR:
2108 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2109 if (vs->vd->cursor) {
2110 vnc_cursor_define(vs);
2113 case VNC_ENCODING_EXT_KEY_EVENT:
2114 send_ext_key_event_ack(vs);
2116 case VNC_ENCODING_AUDIO:
2117 send_ext_audio_ack(vs);
2119 case VNC_ENCODING_WMVi:
2120 vs->features |= VNC_FEATURE_WMVI_MASK;
2122 case VNC_ENCODING_LED_STATE:
2123 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2125 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2126 vs->tight->compression = (enc & 0x0F);
2128 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2129 if (vs->vd->lossy) {
2130 vs->tight->quality = (enc & 0x0F);
2134 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2138 vnc_desktop_resize(vs);
2139 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2140 vnc_led_state_change(vs);
2143 static void set_pixel_conversion(VncState *vs)
2145 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2147 if (fmt == VNC_SERVER_FB_FORMAT) {
2148 vs->write_pixels = vnc_write_pixels_copy;
2149 vnc_hextile_set_pixel_conversion(vs, 0);
2151 vs->write_pixels = vnc_write_pixels_generic;
2152 vnc_hextile_set_pixel_conversion(vs, 1);
2156 static void send_color_map(VncState *vs)
2160 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2161 vnc_write_u8(vs, 0); /* padding */
2162 vnc_write_u16(vs, 0); /* first color */
2163 vnc_write_u16(vs, 256); /* # of colors */
2165 for (i = 0; i < 256; i++) {
2166 PixelFormat *pf = &vs->client_pf;
2168 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2169 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2170 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2174 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2175 int big_endian_flag, int true_color_flag,
2176 int red_max, int green_max, int blue_max,
2177 int red_shift, int green_shift, int blue_shift)
2179 if (!true_color_flag) {
2180 /* Expose a reasonable default 256 color map */
2190 switch (bits_per_pixel) {
2196 vnc_client_error(vs);
2200 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2201 vs->client_pf.rbits = ctpopl(red_max);
2202 vs->client_pf.rshift = red_shift;
2203 vs->client_pf.rmask = red_max << red_shift;
2204 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2205 vs->client_pf.gbits = ctpopl(green_max);
2206 vs->client_pf.gshift = green_shift;
2207 vs->client_pf.gmask = green_max << green_shift;
2208 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2209 vs->client_pf.bbits = ctpopl(blue_max);
2210 vs->client_pf.bshift = blue_shift;
2211 vs->client_pf.bmask = blue_max << blue_shift;
2212 vs->client_pf.bits_per_pixel = bits_per_pixel;
2213 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2214 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2215 vs->client_be = big_endian_flag;
2217 if (!true_color_flag) {
2221 set_pixel_conversion(vs);
2223 graphic_hw_invalidate(vs->vd->dcl.con);
2224 graphic_hw_update(vs->vd->dcl.con);
2227 static void pixel_format_message (VncState *vs) {
2228 char pad[3] = { 0, 0, 0 };
2230 vs->client_pf = qemu_default_pixelformat(32);
2232 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2233 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2235 #ifdef HOST_WORDS_BIGENDIAN
2236 vnc_write_u8(vs, 1); /* big-endian-flag */
2238 vnc_write_u8(vs, 0); /* big-endian-flag */
2240 vnc_write_u8(vs, 1); /* true-color-flag */
2241 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2242 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2243 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2244 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2245 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2246 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2247 vnc_write(vs, pad, 3); /* padding */
2249 vnc_hextile_set_pixel_conversion(vs, 0);
2250 vs->write_pixels = vnc_write_pixels_copy;
2253 static void vnc_colordepth(VncState *vs)
2255 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2256 /* Sending a WMVi message to notify the client*/
2257 vnc_lock_output(vs);
2258 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2259 vnc_write_u8(vs, 0);
2260 vnc_write_u16(vs, 1); /* number of rects */
2261 vnc_framebuffer_update(vs, 0, 0,
2262 pixman_image_get_width(vs->vd->server),
2263 pixman_image_get_height(vs->vd->server),
2265 pixel_format_message(vs);
2266 vnc_unlock_output(vs);
2269 set_pixel_conversion(vs);
2273 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2278 VncDisplay *vd = vs->vd;
2281 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2285 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2289 set_pixel_format(vs, read_u8(data, 4),
2290 read_u8(data, 6), read_u8(data, 7),
2291 read_u16(data, 8), read_u16(data, 10),
2292 read_u16(data, 12), read_u8(data, 14),
2293 read_u8(data, 15), read_u8(data, 16));
2295 case VNC_MSG_CLIENT_SET_ENCODINGS:
2300 limit = read_u16(data, 2);
2302 return 4 + (limit * 4);
2304 limit = read_u16(data, 2);
2306 for (i = 0; i < limit; i++) {
2307 int32_t val = read_s32(data, 4 + (i * 4));
2308 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2311 set_encodings(vs, (int32_t *)(data + 4), limit);
2313 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2317 framebuffer_update_request(vs,
2318 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2319 read_u16(data, 6), read_u16(data, 8));
2321 case VNC_MSG_CLIENT_KEY_EVENT:
2325 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2327 case VNC_MSG_CLIENT_POINTER_EVENT:
2331 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2333 case VNC_MSG_CLIENT_CUT_TEXT:
2338 uint32_t dlen = read_u32(data, 4);
2339 if (dlen > (1 << 20)) {
2340 error_report("vnc: client_cut_text msg payload has %u bytes"
2341 " which exceeds our limit of 1MB.", dlen);
2342 vnc_client_error(vs);
2350 client_cut_text(vs, read_u32(data, 4), data + 8);
2352 case VNC_MSG_CLIENT_QEMU:
2356 switch (read_u8(data, 1)) {
2357 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2361 ext_key_event(vs, read_u16(data, 2),
2362 read_u32(data, 4), read_u32(data, 8));
2364 case VNC_MSG_CLIENT_QEMU_AUDIO:
2368 switch (read_u16 (data, 2)) {
2369 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2372 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2375 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2378 switch (read_u8(data, 4)) {
2379 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
2380 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
2381 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
2382 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
2383 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
2384 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
2386 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2387 vnc_client_error(vs);
2390 vs->as.nchannels = read_u8(data, 5);
2391 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2392 VNC_DEBUG("Invalid audio channel count %d\n",
2394 vnc_client_error(vs);
2397 freq = read_u32(data, 6);
2398 /* No official limit for protocol, but 48khz is a sensible
2399 * upper bound for trustworthy clients, and this limit
2400 * protects calculations involving 'vs->as.freq' later.
2403 VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2404 vnc_client_error(vs);
2410 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2411 vnc_client_error(vs);
2417 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2418 vnc_client_error(vs);
2423 VNC_DEBUG("Msg: %d\n", data[0]);
2424 vnc_client_error(vs);
2428 vnc_update_throttle_offset(vs);
2429 vnc_read_when(vs, protocol_client_msg, 1);
2433 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2439 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2440 switch (vs->vd->share_policy) {
2441 case VNC_SHARE_POLICY_IGNORE:
2443 * Ignore the shared flag. Nothing to do here.
2445 * Doesn't conform to the rfb spec but is traditional qemu
2446 * behavior, thus left here as option for compatibility
2450 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2452 * Policy: Allow clients ask for exclusive access.
2454 * Implementation: When a client asks for exclusive access,
2455 * disconnect all others. Shared connects are allowed as long
2456 * as no exclusive connection exists.
2458 * This is how the rfb spec suggests to handle the shared flag.
2460 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2462 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2466 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2467 client->share_mode != VNC_SHARE_MODE_SHARED) {
2470 vnc_disconnect_start(client);
2473 if (mode == VNC_SHARE_MODE_SHARED) {
2474 if (vs->vd->num_exclusive > 0) {
2475 vnc_disconnect_start(vs);
2480 case VNC_SHARE_POLICY_FORCE_SHARED:
2482 * Policy: Shared connects only.
2483 * Implementation: Disallow clients asking for exclusive access.
2485 * Useful for shared desktop sessions where you don't want
2486 * someone forgetting to say -shared when running the vnc
2487 * client disconnect everybody else.
2489 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2490 vnc_disconnect_start(vs);
2495 vnc_set_share_mode(vs, mode);
2497 if (vs->vd->num_shared > vs->vd->connections_limit) {
2498 vnc_disconnect_start(vs);
2502 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2503 pixman_image_get_width(vs->vd->server) >= 0);
2504 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2505 pixman_image_get_height(vs->vd->server) >= 0);
2506 vs->client_width = pixman_image_get_width(vs->vd->server);
2507 vs->client_height = pixman_image_get_height(vs->vd->server);
2508 vnc_write_u16(vs, vs->client_width);
2509 vnc_write_u16(vs, vs->client_height);
2511 pixel_format_message(vs);
2514 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2515 if (size > sizeof(buf)) {
2519 size = snprintf(buf, sizeof(buf), "QEMU");
2522 vnc_write_u32(vs, size);
2523 vnc_write(vs, buf, size);
2526 vnc_client_cache_auth(vs);
2527 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2529 vnc_read_when(vs, protocol_client_msg, 1);
2534 void start_client_init(VncState *vs)
2536 vnc_read_when(vs, protocol_client_init, 1);
2539 static void authentication_failed(VncState *vs)
2541 vnc_write_u32(vs, 1); /* Reject auth */
2542 if (vs->minor >= 8) {
2543 static const char err[] = "Authentication failed";
2544 vnc_write_u32(vs, sizeof(err));
2545 vnc_write(vs, err, sizeof(err));
2548 vnc_client_error(vs);
2551 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2553 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2555 unsigned char key[8];
2556 time_t now = time(NULL);
2557 QCryptoCipher *cipher = NULL;
2560 if (!vs->vd->password) {
2561 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2564 if (vs->vd->expires < now) {
2565 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2569 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2571 /* Calculate the expected challenge response */
2572 pwlen = strlen(vs->vd->password);
2573 for (i=0; i<sizeof(key); i++)
2574 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2576 cipher = qcrypto_cipher_new(
2577 QCRYPTO_CIPHER_ALG_DES_RFB,
2578 QCRYPTO_CIPHER_MODE_ECB,
2579 key, G_N_ELEMENTS(key),
2582 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2583 error_get_pretty(err));
2588 if (qcrypto_cipher_encrypt(cipher,
2591 VNC_AUTH_CHALLENGE_SIZE,
2593 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2594 error_get_pretty(err));
2599 /* Compare expected vs actual challenge response */
2600 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2601 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2604 trace_vnc_auth_pass(vs, vs->auth);
2605 vnc_write_u32(vs, 0); /* Accept auth */
2608 start_client_init(vs);
2611 qcrypto_cipher_free(cipher);
2615 authentication_failed(vs);
2616 qcrypto_cipher_free(cipher);
2620 void start_auth_vnc(VncState *vs)
2624 if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2625 trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2626 error_get_pretty(err));
2628 authentication_failed(vs);
2632 /* Send client a 'random' challenge */
2633 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2636 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2640 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2642 /* We only advertise 1 auth scheme at a time, so client
2643 * must pick the one we sent. Verify this */
2644 if (data[0] != vs->auth) { /* Reject auth */
2645 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2646 authentication_failed(vs);
2647 } else { /* Accept requested auth */
2648 trace_vnc_auth_start(vs, vs->auth);
2651 if (vs->minor >= 8) {
2652 vnc_write_u32(vs, 0); /* Accept auth completion */
2655 trace_vnc_auth_pass(vs, vs->auth);
2656 start_client_init(vs);
2663 case VNC_AUTH_VENCRYPT:
2664 start_auth_vencrypt(vs);
2667 #ifdef CONFIG_VNC_SASL
2669 start_auth_sasl(vs);
2671 #endif /* CONFIG_VNC_SASL */
2673 default: /* Should not be possible, but just in case */
2674 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2675 authentication_failed(vs);
2681 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2685 memcpy(local, version, 12);
2688 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2689 VNC_DEBUG("Malformed protocol version %s\n", local);
2690 vnc_client_error(vs);
2693 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2694 if (vs->major != 3 ||
2700 VNC_DEBUG("Unsupported client version\n");
2701 vnc_write_u32(vs, VNC_AUTH_INVALID);
2703 vnc_client_error(vs);
2706 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2707 * as equivalent to v3.3 by servers
2709 if (vs->minor == 4 || vs->minor == 5)
2712 if (vs->minor == 3) {
2713 trace_vnc_auth_start(vs, vs->auth);
2714 if (vs->auth == VNC_AUTH_NONE) {
2715 vnc_write_u32(vs, vs->auth);
2717 trace_vnc_auth_pass(vs, vs->auth);
2718 start_client_init(vs);
2719 } else if (vs->auth == VNC_AUTH_VNC) {
2720 VNC_DEBUG("Tell client VNC auth\n");
2721 vnc_write_u32(vs, vs->auth);
2725 trace_vnc_auth_fail(vs, vs->auth,
2726 "Unsupported auth method for v3.3", "");
2727 vnc_write_u32(vs, VNC_AUTH_INVALID);
2729 vnc_client_error(vs);
2732 vnc_write_u8(vs, 1); /* num auth */
2733 vnc_write_u8(vs, vs->auth);
2734 vnc_read_when(vs, protocol_client_auth, 1);
2741 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2743 struct VncSurface *vs = &vd->guest;
2745 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2748 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2752 w = (x + w) / VNC_STAT_RECT;
2753 h = (y + h) / VNC_STAT_RECT;
2757 for (j = y; j <= h; j++) {
2758 for (i = x; i <= w; i++) {
2759 vs->lossy_rect[j][i] = 1;
2764 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2767 int sty = y / VNC_STAT_RECT;
2768 int stx = x / VNC_STAT_RECT;
2771 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2772 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2774 QTAILQ_FOREACH(vs, &vd->clients, next) {
2777 /* kernel send buffers are full -> refresh later */
2778 if (vs->output.offset) {
2782 if (!vs->lossy_rect[sty][stx]) {
2786 vs->lossy_rect[sty][stx] = 0;
2787 for (j = 0; j < VNC_STAT_RECT; ++j) {
2788 bitmap_set(vs->dirty[y + j],
2789 x / VNC_DIRTY_PIXELS_PER_BIT,
2790 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2798 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2800 int width = MIN(pixman_image_get_width(vd->guest.fb),
2801 pixman_image_get_width(vd->server));
2802 int height = MIN(pixman_image_get_height(vd->guest.fb),
2803 pixman_image_get_height(vd->server));
2808 for (y = 0; y < height; y += VNC_STAT_RECT) {
2809 for (x = 0; x < width; x += VNC_STAT_RECT) {
2810 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2812 rect->updated = false;
2816 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2818 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2821 vd->guest.last_freq_check = *tv;
2823 for (y = 0; y < height; y += VNC_STAT_RECT) {
2824 for (x = 0; x < width; x += VNC_STAT_RECT) {
2825 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2826 int count = ARRAY_SIZE(rect->times);
2827 struct timeval min, max;
2829 if (!timerisset(&rect->times[count - 1])) {
2833 max = rect->times[(rect->idx + count - 1) % count];
2834 qemu_timersub(tv, &max, &res);
2836 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2838 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2839 memset(rect->times, 0, sizeof (rect->times));
2843 min = rect->times[rect->idx];
2844 max = rect->times[(rect->idx + count - 1) % count];
2845 qemu_timersub(&max, &min, &res);
2847 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2848 rect->freq /= count;
2849 rect->freq = 1. / rect->freq;
2855 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2861 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2862 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2864 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2865 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2866 total += vnc_stat_rect(vs->vd, i, j)->freq;
2878 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2882 rect = vnc_stat_rect(vd, x, y);
2883 if (rect->updated) {
2886 rect->times[rect->idx] = *tv;
2887 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2888 rect->updated = true;
2891 static int vnc_refresh_server_surface(VncDisplay *vd)
2893 int width = MIN(pixman_image_get_width(vd->guest.fb),
2894 pixman_image_get_width(vd->server));
2895 int height = MIN(pixman_image_get_height(vd->guest.fb),
2896 pixman_image_get_height(vd->server));
2897 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2898 uint8_t *guest_row0 = NULL, *server_row0;
2901 pixman_image_t *tmpbuf = NULL;
2903 struct timeval tv = { 0, 0 };
2905 if (!vd->non_adaptive) {
2906 gettimeofday(&tv, NULL);
2907 has_dirty = vnc_update_stats(vd, &tv);
2911 * Walk through the guest dirty map.
2912 * Check and copy modified bits from guest to server surface.
2913 * Update server dirty map.
2915 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2916 server_stride = guest_stride = guest_ll =
2917 pixman_image_get_stride(vd->server);
2918 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2920 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2921 int width = pixman_image_get_width(vd->server);
2922 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2925 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2926 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2927 guest_stride = pixman_image_get_stride(vd->guest.fb);
2928 guest_ll = pixman_image_get_width(vd->guest.fb)
2929 * DIV_ROUND_UP(guest_bpp, 8);
2931 line_bytes = MIN(server_stride, guest_ll);
2935 uint8_t *guest_ptr, *server_ptr;
2936 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2937 height * VNC_DIRTY_BPL(&vd->guest),
2938 y * VNC_DIRTY_BPL(&vd->guest));
2939 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2940 /* no more dirty bits */
2943 y = offset / VNC_DIRTY_BPL(&vd->guest);
2944 x = offset % VNC_DIRTY_BPL(&vd->guest);
2946 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2948 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2949 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2950 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2952 guest_ptr = guest_row0 + y * guest_stride;
2954 guest_ptr += x * cmp_bytes;
2956 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2957 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2958 int _cmp_bytes = cmp_bytes;
2959 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2962 if ((x + 1) * cmp_bytes > line_bytes) {
2963 _cmp_bytes = line_bytes - x * cmp_bytes;
2965 assert(_cmp_bytes >= 0);
2966 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2969 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2970 if (!vd->non_adaptive) {
2971 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2974 QTAILQ_FOREACH(vs, &vd->clients, next) {
2975 set_bit(x, vs->dirty[y]);
2982 qemu_pixman_image_unref(tmpbuf);
2986 static void vnc_refresh(DisplayChangeListener *dcl)
2988 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2990 int has_dirty, rects = 0;
2992 if (QTAILQ_EMPTY(&vd->clients)) {
2993 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2997 graphic_hw_update(vd->dcl.con);
2999 if (vnc_trylock_display(vd)) {
3000 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3004 has_dirty = vnc_refresh_server_surface(vd);
3005 vnc_unlock_display(vd);
3007 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3008 rects += vnc_update_client(vs, has_dirty);
3009 /* vs might be free()ed here */
3012 if (has_dirty && rects) {
3013 vd->dcl.update_interval /= 2;
3014 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3015 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3018 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3019 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3020 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3025 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3026 bool skipauth, bool websocket)
3028 VncState *vs = g_new0(VncState, 1);
3029 bool first_client = QTAILQ_EMPTY(&vd->clients);
3032 trace_vnc_client_connect(vs, sioc);
3033 vs->zrle = g_new0(VncZrle, 1);
3034 vs->tight = g_new0(VncTight, 1);
3035 vs->magic = VNC_MAGIC;
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 = AUDIO_FORMAT_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 void vnc_listen_io(QIONetListener *listener,
3147 QIOChannelSocket *cioc,
3150 VncDisplay *vd = opaque;
3151 bool isWebsock = listener == vd->wslistener;
3153 qio_channel_set_name(QIO_CHANNEL(cioc),
3154 isWebsock ? "vnc-ws-server" : "vnc-server");
3155 qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3156 vnc_connect(vd, cioc, false, isWebsock);
3159 static const DisplayChangeListenerOps dcl_ops = {
3161 .dpy_refresh = vnc_refresh,
3162 .dpy_gfx_update = vnc_dpy_update,
3163 .dpy_gfx_switch = vnc_dpy_switch,
3164 .dpy_gfx_check_format = qemu_pixman_check_format,
3165 .dpy_mouse_set = vnc_mouse_set,
3166 .dpy_cursor_define = vnc_dpy_cursor_define,
3169 void vnc_display_init(const char *id, Error **errp)
3173 if (vnc_display_find(id) != NULL) {
3176 vd = g_malloc0(sizeof(*vd));
3178 vd->id = strdup(id);
3179 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3181 QTAILQ_INIT(&vd->clients);
3182 vd->expires = TIME_MAX;
3184 if (keyboard_layout) {
3185 trace_vnc_key_map_init(keyboard_layout);
3186 vd->kbd_layout = init_keyboard_layout(name2keysym,
3187 keyboard_layout, errp);
3189 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3192 if (!vd->kbd_layout) {
3196 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3197 vd->connections_limit = 32;
3199 qemu_mutex_init(&vd->mutex);
3200 vnc_start_worker_thread();
3202 vd->dcl.ops = &dcl_ops;
3203 register_displaychangelistener(&vd->dcl);
3204 vd->kbd = qkbd_state_init(vd->dcl.con);
3208 static void vnc_display_close(VncDisplay *vd)
3213 vd->is_unix = false;
3216 qio_net_listener_disconnect(vd->listener);
3217 object_unref(OBJECT(vd->listener));
3219 vd->listener = NULL;
3221 if (vd->wslistener) {
3222 qio_net_listener_disconnect(vd->wslistener);
3223 object_unref(OBJECT(vd->wslistener));
3225 vd->wslistener = NULL;
3227 vd->auth = VNC_AUTH_INVALID;
3228 vd->subauth = VNC_AUTH_INVALID;
3230 object_unparent(OBJECT(vd->tlscreds));
3231 vd->tlscreds = NULL;
3234 object_unparent(OBJECT(vd->tlsauthz));
3235 vd->tlsauthz = NULL;
3237 g_free(vd->tlsauthzid);
3238 vd->tlsauthzid = NULL;
3239 if (vd->lock_key_sync) {
3240 qemu_remove_led_event_handler(vd->led);
3243 #ifdef CONFIG_VNC_SASL
3244 if (vd->sasl.authz) {
3245 object_unparent(OBJECT(vd->sasl.authz));
3246 vd->sasl.authz = NULL;
3248 g_free(vd->sasl.authzid);
3249 vd->sasl.authzid = NULL;
3253 int vnc_display_password(const char *id, const char *password)
3255 VncDisplay *vd = vnc_display_find(id);
3260 if (vd->auth == VNC_AUTH_NONE) {
3261 error_printf_unless_qmp("If you want use passwords please enable "
3262 "password auth using '-vnc ${dpy},password'.\n");
3266 g_free(vd->password);
3267 vd->password = g_strdup(password);
3272 int vnc_display_pw_expire(const char *id, time_t expires)
3274 VncDisplay *vd = vnc_display_find(id);
3280 vd->expires = expires;
3284 static void vnc_display_print_local_addr(VncDisplay *vd)
3286 SocketAddress *addr;
3289 if (!vd->listener || !vd->listener->nsioc) {
3293 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], &err);
3298 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3299 qapi_free_SocketAddress(addr);
3302 error_printf_unless_qmp("VNC server running on %s:%s\n",
3305 qapi_free_SocketAddress(addr);
3308 static QemuOptsList qemu_vnc_opts = {
3310 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3311 .implied_opt_name = "vnc",
3315 .type = QEMU_OPT_STRING,
3317 .name = "websocket",
3318 .type = QEMU_OPT_STRING,
3320 .name = "tls-creds",
3321 .type = QEMU_OPT_STRING,
3324 .type = QEMU_OPT_STRING,
3327 .type = QEMU_OPT_STRING,
3330 .type = QEMU_OPT_NUMBER,
3332 .name = "connections",
3333 .type = QEMU_OPT_NUMBER,
3336 .type = QEMU_OPT_NUMBER,
3339 .type = QEMU_OPT_BOOL,
3342 .type = QEMU_OPT_BOOL,
3345 .type = QEMU_OPT_BOOL,
3348 .type = QEMU_OPT_BOOL,
3350 .name = "lock-key-sync",
3351 .type = QEMU_OPT_BOOL,
3353 .name = "key-delay-ms",
3354 .type = QEMU_OPT_NUMBER,
3357 .type = QEMU_OPT_BOOL,
3360 .type = QEMU_OPT_BOOL,
3362 .name = "tls-authz",
3363 .type = QEMU_OPT_STRING,
3365 .name = "sasl-authz",
3366 .type = QEMU_OPT_STRING,
3369 .type = QEMU_OPT_BOOL,
3371 .name = "non-adaptive",
3372 .type = QEMU_OPT_BOOL,
3375 .type = QEMU_OPT_STRING,
3377 { /* end of list */ }
3383 vnc_display_setup_auth(int *auth,
3385 QCryptoTLSCreds *tlscreds,
3392 * We have a choice of 3 authentication options
3398 * The channel can be run in 2 modes
3403 * And TLS can use 2 types of credentials
3408 * We thus have 9 possible logical combinations
3413 * 4. tls + anon + none
3414 * 5. tls + anon + vnc
3415 * 6. tls + anon + sasl
3416 * 7. tls + x509 + none
3417 * 8. tls + x509 + vnc
3418 * 9. tls + x509 + sasl
3420 * These need to be mapped into the VNC auth schemes
3421 * in an appropriate manner. In regular VNC, all the
3422 * TLS options get mapped into VNC_AUTH_VENCRYPT
3425 * In websockets, the https:// protocol already provides
3426 * TLS support, so there is no need to make use of the
3427 * VeNCrypt extension. Furthermore, websockets browser
3428 * clients could not use VeNCrypt even if they wanted to,
3429 * as they cannot control when the TLS handshake takes
3430 * place. Thus there is no option but to rely on https://,
3431 * meaning combinations 4->6 and 7->9 will be mapped to
3432 * VNC auth schemes in the same way as combos 1->3.
3434 * Regardless of fact that we have a different mapping to
3435 * VNC auth mechs for plain VNC vs websockets VNC, the end
3436 * result has the same security characteristics.
3438 if (websocket || !tlscreds) {
3440 VNC_DEBUG("Initializing VNC server with password auth\n");
3441 *auth = VNC_AUTH_VNC;
3443 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3444 *auth = VNC_AUTH_SASL;
3446 VNC_DEBUG("Initializing VNC server with no auth\n");
3447 *auth = VNC_AUTH_NONE;
3449 *subauth = VNC_AUTH_INVALID;
3451 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3452 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3453 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3454 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3456 if (!is_x509 && !is_anon) {
3458 "Unsupported TLS cred type %s",
3459 object_get_typename(OBJECT(tlscreds)));
3462 *auth = VNC_AUTH_VENCRYPT;
3465 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3466 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3468 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3469 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3474 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3475 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3477 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3478 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3482 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3483 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3485 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3486 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3494 static int vnc_display_get_address(const char *addrstr,
3503 SocketAddress **retaddr,
3507 SocketAddress *addr = NULL;
3509 addr = g_new0(SocketAddress, 1);
3511 if (strncmp(addrstr, "unix:", 5) == 0) {
3512 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3513 addr->u.q_unix.path = g_strdup(addrstr + 5);
3516 error_setg(errp, "UNIX sockets not supported with websock");
3521 error_setg(errp, "Port range not support with UNIX socket");
3528 unsigned long long baseport = 0;
3529 InetSocketAddress *inet;
3531 port = strrchr(addrstr, ':');
3537 error_setg(errp, "no vnc port specified");
3541 hostlen = port - addrstr;
3543 if (*port == '\0') {
3544 error_setg(errp, "vnc port cannot be empty");
3549 addr->type = SOCKET_ADDRESS_TYPE_INET;
3550 inet = &addr->u.inet;
3551 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3552 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3554 inet->host = g_strndup(addrstr, hostlen);
3556 /* plain VNC port is just an offset, for websocket
3557 * port is absolute */
3559 if (g_str_equal(addrstr, "") ||
3560 g_str_equal(addrstr, "on")) {
3561 if (displaynum == -1) {
3562 error_setg(errp, "explicit websocket port is required");
3565 inet->port = g_strdup_printf(
3566 "%d", displaynum + 5700);
3568 inet->has_to = true;
3569 inet->to = to + 5700;
3572 inet->port = g_strdup(port);
3575 int offset = reverse ? 0 : 5900;
3576 if (parse_uint_full(port, &baseport, 10) < 0) {
3577 error_setg(errp, "can't convert to a number: %s", port);
3580 if (baseport > 65535 ||
3581 baseport + offset > 65535) {
3582 error_setg(errp, "port %s out of range", port);
3585 inet->port = g_strdup_printf(
3586 "%d", (int)baseport + offset);
3589 inet->has_to = true;
3590 inet->to = to + offset;
3595 inet->has_ipv4 = has_ipv4;
3597 inet->has_ipv6 = has_ipv6;
3606 qapi_free_SocketAddress(addr);
3611 static void vnc_free_addresses(SocketAddress ***retsaddr,
3616 for (i = 0; i < *retnsaddr; i++) {
3617 qapi_free_SocketAddress((*retsaddr)[i]);
3625 static int vnc_display_get_addresses(QemuOpts *opts,
3627 SocketAddress ***retsaddr,
3629 SocketAddress ***retwsaddr,
3633 SocketAddress *saddr = NULL;
3634 SocketAddress *wsaddr = NULL;
3635 QemuOptsIter addriter;
3637 int to = qemu_opt_get_number(opts, "to", 0);
3638 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3639 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3640 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3641 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3642 int displaynum = -1;
3650 addr = qemu_opt_get(opts, "vnc");
3651 if (addr == NULL || g_str_equal(addr, "none")) {
3655 if (qemu_opt_get(opts, "websocket") &&
3656 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3658 "SHA1 hash support is required for websockets");
3662 qemu_opt_iter_init(&addriter, opts, "vnc");
3663 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3665 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3672 /* Historical compat - first listen address can be used
3673 * to set the default websocket port
3675 if (displaynum == -1) {
3678 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3679 (*retsaddr)[(*retnsaddr)++] = saddr;
3682 /* If we had multiple primary displays, we don't do defaults
3683 * for websocket, and require explicit config instead. */
3684 if (*retnsaddr > 1) {
3688 qemu_opt_iter_init(&addriter, opts, "websocket");
3689 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3690 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3693 &wsaddr, errp) < 0) {
3697 /* Historical compat - if only a single listen address was
3698 * provided, then this is used to set the default listen
3699 * address for websocket too
3701 if (*retnsaddr == 1 &&
3702 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3703 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3704 g_str_equal(wsaddr->u.inet.host, "") &&
3705 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3706 g_free(wsaddr->u.inet.host);
3707 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3710 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3711 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3717 vnc_free_addresses(retsaddr, retnsaddr);
3718 vnc_free_addresses(retwsaddr, retnwsaddr);
3723 static int vnc_display_connect(VncDisplay *vd,
3724 SocketAddress **saddr,
3726 SocketAddress **wsaddr,
3730 /* connect to viewer */
3731 QIOChannelSocket *sioc = NULL;
3733 error_setg(errp, "Cannot use websockets in reverse mode");
3737 error_setg(errp, "Expected a single address in reverse mode");
3740 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3741 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3742 sioc = qio_channel_socket_new();
3743 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3744 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3747 vnc_connect(vd, sioc, false, false);
3748 object_unref(OBJECT(sioc));
3753 static int vnc_display_listen(VncDisplay *vd,
3754 SocketAddress **saddr,
3756 SocketAddress **wsaddr,
3763 vd->listener = qio_net_listener_new();
3764 qio_net_listener_set_name(vd->listener, "vnc-listen");
3765 for (i = 0; i < nsaddr; i++) {
3766 if (qio_net_listener_open_sync(vd->listener,
3773 qio_net_listener_set_client_func(vd->listener,
3774 vnc_listen_io, vd, NULL);
3778 vd->wslistener = qio_net_listener_new();
3779 qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3780 for (i = 0; i < nwsaddr; i++) {
3781 if (qio_net_listener_open_sync(vd->wslistener,
3788 qio_net_listener_set_client_func(vd->wslistener,
3789 vnc_listen_io, vd, NULL);
3796 void vnc_display_open(const char *id, Error **errp)
3798 VncDisplay *vd = vnc_display_find(id);
3799 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3800 SocketAddress **saddr = NULL, **wsaddr = NULL;
3801 size_t nsaddr, nwsaddr;
3802 const char *share, *device_id;
3804 bool password = false;
3805 bool reverse = false;
3809 const char *tlsauthz;
3810 const char *saslauthz;
3811 int lock_key_sync = 1;
3813 const char *audiodev;
3816 error_setg(errp, "VNC display not active");
3819 vnc_display_close(vd);
3825 reverse = qemu_opt_get_bool(opts, "reverse", false);
3826 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3827 &wsaddr, &nwsaddr, errp) < 0) {
3831 password = qemu_opt_get_bool(opts, "password", false);
3833 if (fips_get_state()) {
3835 "VNC password auth disabled due to FIPS mode, "
3836 "consider using the VeNCrypt or SASL authentication "
3837 "methods as an alternative");
3840 if (!qcrypto_cipher_supports(
3841 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3843 "Cipher backend does not support DES RFB algorithm");
3848 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3849 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3850 sasl = qemu_opt_get_bool(opts, "sasl", false);
3851 #ifndef CONFIG_VNC_SASL
3853 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3856 #endif /* CONFIG_VNC_SASL */
3857 credid = qemu_opt_get(opts, "tls-creds");
3860 creds = object_resolve_path_component(
3861 object_get_objects_root(), credid);
3863 error_setg(errp, "No TLS credentials with id '%s'",
3867 vd->tlscreds = (QCryptoTLSCreds *)
3868 object_dynamic_cast(creds,
3869 TYPE_QCRYPTO_TLS_CREDS);
3870 if (!vd->tlscreds) {
3871 error_setg(errp, "Object with id '%s' is not TLS credentials",
3875 object_ref(OBJECT(vd->tlscreds));
3877 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3879 "Expecting TLS credentials with a server endpoint");
3883 if (qemu_opt_get(opts, "acl")) {
3884 error_report("The 'acl' option to -vnc is deprecated. "
3885 "Please use the 'tls-authz' and 'sasl-authz' "
3888 acl = qemu_opt_get_bool(opts, "acl", false);
3889 tlsauthz = qemu_opt_get(opts, "tls-authz");
3890 if (acl && tlsauthz) {
3891 error_setg(errp, "'acl' option is mutually exclusive with the "
3892 "'tls-authz' option");
3895 if (tlsauthz && !vd->tlscreds) {
3896 error_setg(errp, "'tls-authz' provided but TLS is not enabled");
3900 saslauthz = qemu_opt_get(opts, "sasl-authz");
3901 if (acl && saslauthz) {
3902 error_setg(errp, "'acl' option is mutually exclusive with the "
3903 "'sasl-authz' option");
3906 if (saslauthz && !sasl) {
3907 error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
3911 share = qemu_opt_get(opts, "share");
3913 if (strcmp(share, "ignore") == 0) {
3914 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
3915 } else if (strcmp(share, "allow-exclusive") == 0) {
3916 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3917 } else if (strcmp(share, "force-shared") == 0) {
3918 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3920 error_setg(errp, "unknown vnc share= option");
3924 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3926 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3928 #ifdef CONFIG_VNC_JPEG
3929 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
3931 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3932 /* adaptive updates are only used with tight encoding and
3933 * if lossy updates are enabled so we can disable all the
3934 * calculations otherwise */
3936 vd->non_adaptive = true;
3940 vd->tlsauthzid = g_strdup(tlsauthz);
3942 if (strcmp(vd->id, "default") == 0) {
3943 vd->tlsauthzid = g_strdup("vnc.x509dname");
3945 vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
3947 vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
3948 QAUTHZ_LIST_POLICY_DENY,
3951 #ifdef CONFIG_VNC_SASL
3954 vd->sasl.authzid = g_strdup(saslauthz);
3956 if (strcmp(vd->id, "default") == 0) {
3957 vd->sasl.authzid = g_strdup("vnc.username");
3959 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
3961 vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
3962 QAUTHZ_LIST_POLICY_DENY,
3968 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
3969 vd->tlscreds, password,
3970 sasl, false, errp) < 0) {
3973 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
3975 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
3976 vd->tlscreds, password,
3977 sasl, true, errp) < 0) {
3980 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
3982 #ifdef CONFIG_VNC_SASL
3984 int saslErr = sasl_server_init(NULL, "qemu");
3986 if (saslErr != SASL_OK) {
3987 error_setg(errp, "Failed to initialize SASL auth: %s",
3988 sasl_errstring(saslErr, NULL, NULL));
3993 vd->lock_key_sync = lock_key_sync;
3994 if (lock_key_sync) {
3995 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
3999 audiodev = qemu_opt_get(opts, "audiodev");
4001 vd->audio_state = audio_state_by_name(audiodev);
4002 if (!vd->audio_state) {
4003 error_setg(errp, "Audiodev '%s' not found", audiodev);
4008 device_id = qemu_opt_get(opts, "display");
4010 int head = qemu_opt_get_number(opts, "head", 0);
4013 con = qemu_console_lookup_by_device_name(device_id, head, &err);
4015 error_propagate(errp, err);
4022 if (con != vd->dcl.con) {
4023 qkbd_state_free(vd->kbd);
4024 unregister_displaychangelistener(&vd->dcl);
4026 register_displaychangelistener(&vd->dcl);
4027 vd->kbd = qkbd_state_init(vd->dcl.con);
4029 qkbd_state_set_delay(vd->kbd, key_delay_ms);
4031 if (saddr == NULL) {
4036 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4040 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4045 if (qemu_opt_get(opts, "to")) {
4046 vnc_display_print_local_addr(vd);
4050 vnc_free_addresses(&saddr, &nsaddr);
4051 vnc_free_addresses(&wsaddr, &nwsaddr);
4055 vnc_display_close(vd);
4059 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4061 VncDisplay *vd = vnc_display_find(id);
4062 QIOChannelSocket *sioc;
4068 sioc = qio_channel_socket_new_fd(csock, NULL);
4070 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4071 vnc_connect(vd, sioc, skipauth, false);
4072 object_unref(OBJECT(sioc));
4076 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4081 id = g_strdup("default");
4082 while (qemu_opts_find(olist, id)) {
4084 id = g_strdup_printf("vnc%d", i++);
4086 qemu_opts_set_id(opts, id);
4089 QemuOpts *vnc_parse(const char *str, Error **errp)
4091 QemuOptsList *olist = qemu_find_opts("vnc");
4092 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
4099 id = qemu_opts_id(opts);
4101 /* auto-assign id if not present */
4102 vnc_auto_assign_id(olist, opts);
4107 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4109 Error *local_err = NULL;
4110 char *id = (char *)qemu_opts_id(opts);
4113 vnc_display_init(id, &local_err);
4115 error_propagate(errp, local_err);
4118 vnc_display_open(id, &local_err);
4119 if (local_err != NULL) {
4120 error_propagate(errp, local_err);
4126 static void vnc_register_config(void)
4128 qemu_add_opts(&qemu_vnc_opts);
4130 opts_init(vnc_register_config);