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
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"
40 #include "qemu/osdep.h"
42 #include "qapi-event.h"
43 #include "crypto/hash.h"
44 #include "crypto/tlscredsanon.h"
45 #include "crypto/tlscredsx509.h"
46 #include "qom/object_interfaces.h"
48 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
49 #define VNC_REFRESH_INTERVAL_INC 50
50 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
51 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
52 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
54 #include "vnc_keysym.h"
55 #include "crypto/cipher.h"
57 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
58 QTAILQ_HEAD_INITIALIZER(vnc_displays);
60 static int vnc_cursor_define(VncState *vs);
61 static void vnc_release_modifiers(VncState *vs);
63 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
66 static const char *mn[] = {
68 [VNC_SHARE_MODE_CONNECTING] = "connecting",
69 [VNC_SHARE_MODE_SHARED] = "shared",
70 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
71 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
73 fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
74 vs->csock, mn[vs->share_mode], mn[mode]);
77 switch (vs->share_mode) {
78 case VNC_SHARE_MODE_CONNECTING:
79 vs->vd->num_connecting--;
81 case VNC_SHARE_MODE_SHARED:
84 case VNC_SHARE_MODE_EXCLUSIVE:
85 vs->vd->num_exclusive--;
91 vs->share_mode = mode;
93 switch (vs->share_mode) {
94 case VNC_SHARE_MODE_CONNECTING:
95 vs->vd->num_connecting++;
97 case VNC_SHARE_MODE_SHARED:
100 case VNC_SHARE_MODE_EXCLUSIVE:
101 vs->vd->num_exclusive++;
108 static char *addr_to_string(const char *format,
109 struct sockaddr_storage *sa,
112 char host[NI_MAXHOST];
113 char serv[NI_MAXSERV];
117 if ((err = getnameinfo((struct sockaddr *)sa, salen,
120 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
121 VNC_DEBUG("Cannot resolve address %d: %s\n",
122 err, gai_strerror(err));
126 /* Enough for the existing format + the 2 vars we're
127 * substituting in. */
128 addrlen = strlen(format) + strlen(host) + strlen(serv);
129 addr = g_malloc(addrlen + 1);
130 snprintf(addr, addrlen, format, host, serv);
131 addr[addrlen] = '\0';
137 char *vnc_socket_local_addr(const char *format, int fd) {
138 struct sockaddr_storage sa;
142 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
145 return addr_to_string(format, &sa, salen);
148 char *vnc_socket_remote_addr(const char *format, int fd) {
149 struct sockaddr_storage sa;
153 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
156 return addr_to_string(format, &sa, salen);
159 static void vnc_init_basic_info(struct sockaddr_storage *sa,
164 char host[NI_MAXHOST];
165 char serv[NI_MAXSERV];
168 if ((err = getnameinfo((struct sockaddr *)sa, salen,
171 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
172 error_setg(errp, "Cannot resolve address: %s",
177 info->host = g_strdup(host);
178 info->service = g_strdup(serv);
179 info->family = inet_netfamily(sa->ss_family);
182 static void vnc_init_basic_info_from_server_addr(int fd, VncBasicInfo *info,
185 struct sockaddr_storage sa;
189 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
190 error_setg_errno(errp, errno, "getsockname failed");
194 vnc_init_basic_info(&sa, salen, info, errp);
197 static void vnc_init_basic_info_from_remote_addr(int fd, VncBasicInfo *info,
200 struct sockaddr_storage sa;
204 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
205 error_setg_errno(errp, errno, "getpeername failed");
209 vnc_init_basic_info(&sa, salen, info, errp);
212 static const char *vnc_auth_name(VncDisplay *vd) {
214 case VNC_AUTH_INVALID:
230 case VNC_AUTH_VENCRYPT:
231 switch (vd->subauth) {
232 case VNC_AUTH_VENCRYPT_PLAIN:
233 return "vencrypt+plain";
234 case VNC_AUTH_VENCRYPT_TLSNONE:
235 return "vencrypt+tls+none";
236 case VNC_AUTH_VENCRYPT_TLSVNC:
237 return "vencrypt+tls+vnc";
238 case VNC_AUTH_VENCRYPT_TLSPLAIN:
239 return "vencrypt+tls+plain";
240 case VNC_AUTH_VENCRYPT_X509NONE:
241 return "vencrypt+x509+none";
242 case VNC_AUTH_VENCRYPT_X509VNC:
243 return "vencrypt+x509+vnc";
244 case VNC_AUTH_VENCRYPT_X509PLAIN:
245 return "vencrypt+x509+plain";
246 case VNC_AUTH_VENCRYPT_TLSSASL:
247 return "vencrypt+tls+sasl";
248 case VNC_AUTH_VENCRYPT_X509SASL:
249 return "vencrypt+x509+sasl";
259 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
264 info = g_malloc(sizeof(*info));
265 vnc_init_basic_info_from_server_addr(vd->lsock,
266 qapi_VncServerInfo_base(info), &err);
267 info->has_auth = true;
268 info->auth = g_strdup(vnc_auth_name(vd));
270 qapi_free_VncServerInfo(info);
277 static void vnc_client_cache_auth(VncState *client)
284 client->info->x509_dname =
285 qcrypto_tls_session_get_peer_name(client->tls);
286 client->info->has_x509_dname =
287 client->info->x509_dname != NULL;
289 #ifdef CONFIG_VNC_SASL
290 if (client->sasl.conn &&
291 client->sasl.username) {
292 client->info->has_sasl_username = true;
293 client->info->sasl_username = g_strdup(client->sasl.username);
298 static void vnc_client_cache_addr(VncState *client)
302 client->info = g_malloc0(sizeof(*client->info));
303 vnc_init_basic_info_from_remote_addr(client->csock,
304 qapi_VncClientInfo_base(client->info),
307 qapi_free_VncClientInfo(client->info);
313 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
321 si = vnc_server_info_get(vs->vd);
327 case QAPI_EVENT_VNC_CONNECTED:
328 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info),
331 case QAPI_EVENT_VNC_INITIALIZED:
332 qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
334 case QAPI_EVENT_VNC_DISCONNECTED:
335 qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
341 qapi_free_VncServerInfo(si);
344 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
346 struct sockaddr_storage sa;
347 socklen_t salen = sizeof(sa);
348 char host[NI_MAXHOST];
349 char serv[NI_MAXSERV];
352 if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
356 if (getnameinfo((struct sockaddr *)&sa, salen,
359 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
363 info = g_malloc0(sizeof(*info));
364 info->host = g_strdup(host);
365 info->service = g_strdup(serv);
366 info->family = inet_netfamily(sa.ss_family);
367 info->websocket = client->websocket;
370 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
371 info->has_x509_dname = info->x509_dname != NULL;
373 #ifdef CONFIG_VNC_SASL
374 if (client->sasl.conn && client->sasl.username) {
375 info->has_sasl_username = true;
376 info->sasl_username = g_strdup(client->sasl.username);
383 static VncDisplay *vnc_display_find(const char *id)
388 return QTAILQ_FIRST(&vnc_displays);
390 QTAILQ_FOREACH(vd, &vnc_displays, next) {
391 if (strcmp(id, vd->id) == 0) {
398 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
400 VncClientInfoList *cinfo, *prev = NULL;
403 QTAILQ_FOREACH(client, &vd->clients, next) {
404 cinfo = g_new0(VncClientInfoList, 1);
405 cinfo->value = qmp_query_vnc_client(client);
412 VncInfo *qmp_query_vnc(Error **errp)
414 VncInfo *info = g_malloc0(sizeof(*info));
415 VncDisplay *vd = vnc_display_find(NULL);
417 if (vd == NULL || !vd->enabled) {
418 info->enabled = false;
420 struct sockaddr_storage sa;
421 socklen_t salen = sizeof(sa);
422 char host[NI_MAXHOST];
423 char serv[NI_MAXSERV];
425 info->enabled = true;
427 /* for compatibility with the original command */
428 info->has_clients = true;
429 info->clients = qmp_query_client_list(vd);
431 if (vd->lsock == -1) {
435 if (getsockname(vd->lsock, (struct sockaddr *)&sa,
437 error_setg(errp, QERR_UNDEFINED_ERROR);
441 if (getnameinfo((struct sockaddr *)&sa, salen,
444 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
445 error_setg(errp, QERR_UNDEFINED_ERROR);
449 info->has_host = true;
450 info->host = g_strdup(host);
452 info->has_service = true;
453 info->service = g_strdup(serv);
455 info->has_family = true;
456 info->family = inet_netfamily(sa.ss_family);
458 info->has_auth = true;
459 info->auth = g_strdup(vnc_auth_name(vd));
465 qapi_free_VncInfo(info);
469 static VncBasicInfoList *qmp_query_server_entry(int socket,
471 VncBasicInfoList *prev)
473 VncBasicInfoList *list;
475 struct sockaddr_storage sa;
476 socklen_t salen = sizeof(sa);
477 char host[NI_MAXHOST];
478 char serv[NI_MAXSERV];
480 if (getsockname(socket, (struct sockaddr *)&sa, &salen) < 0 ||
481 getnameinfo((struct sockaddr *)&sa, salen,
482 host, sizeof(host), serv, sizeof(serv),
483 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
487 info = g_new0(VncBasicInfo, 1);
488 info->host = g_strdup(host);
489 info->service = g_strdup(serv);
490 info->family = inet_netfamily(sa.ss_family);
491 info->websocket = websocket;
493 list = g_new0(VncBasicInfoList, 1);
499 static void qmp_query_auth(VncDisplay *vd, VncInfo2 *info)
503 info->auth = VNC_PRIMARY_AUTH_VNC;
506 info->auth = VNC_PRIMARY_AUTH_RA2;
509 info->auth = VNC_PRIMARY_AUTH_RA2NE;
512 info->auth = VNC_PRIMARY_AUTH_TIGHT;
515 info->auth = VNC_PRIMARY_AUTH_ULTRA;
518 info->auth = VNC_PRIMARY_AUTH_TLS;
520 case VNC_AUTH_VENCRYPT:
521 info->auth = VNC_PRIMARY_AUTH_VENCRYPT;
522 info->has_vencrypt = true;
523 switch (vd->subauth) {
524 case VNC_AUTH_VENCRYPT_PLAIN:
525 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
527 case VNC_AUTH_VENCRYPT_TLSNONE:
528 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
530 case VNC_AUTH_VENCRYPT_TLSVNC:
531 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
533 case VNC_AUTH_VENCRYPT_TLSPLAIN:
534 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
536 case VNC_AUTH_VENCRYPT_X509NONE:
537 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
539 case VNC_AUTH_VENCRYPT_X509VNC:
540 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
542 case VNC_AUTH_VENCRYPT_X509PLAIN:
543 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
545 case VNC_AUTH_VENCRYPT_TLSSASL:
546 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
548 case VNC_AUTH_VENCRYPT_X509SASL:
549 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
552 info->has_vencrypt = false;
557 info->auth = VNC_PRIMARY_AUTH_SASL;
561 info->auth = VNC_PRIMARY_AUTH_NONE;
566 VncInfo2List *qmp_query_vnc_servers(Error **errp)
568 VncInfo2List *item, *prev = NULL;
573 QTAILQ_FOREACH(vd, &vnc_displays, next) {
574 info = g_new0(VncInfo2, 1);
575 info->id = g_strdup(vd->id);
576 info->clients = qmp_query_client_list(vd);
577 qmp_query_auth(vd, info);
579 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
581 info->has_display = true;
582 info->display = g_strdup(dev->id);
584 if (vd->lsock != -1) {
585 info->server = qmp_query_server_entry(vd->lsock, false,
588 if (vd->lwebsock != -1) {
589 info->server = qmp_query_server_entry(vd->lwebsock, true,
593 item = g_new0(VncInfo2List, 1);
602 1) Get the queue working for IO.
603 2) there is some weirdness when using the -S option (the screen is grey
604 and not totally invalidated
605 3) resolutions > 1024
608 static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
609 static void vnc_disconnect_start(VncState *vs);
611 static void vnc_colordepth(VncState *vs);
612 static void framebuffer_update_request(VncState *vs, int incremental,
613 int x_position, int y_position,
615 static void vnc_refresh(DisplayChangeListener *dcl);
616 static int vnc_refresh_server_surface(VncDisplay *vd);
618 static int vnc_width(VncDisplay *vd)
620 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
621 VNC_DIRTY_PIXELS_PER_BIT));
624 static int vnc_height(VncDisplay *vd)
626 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
629 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
630 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
631 int width, int height,
632 int x, int y, int w, int h) {
633 /* this is needed this to ensure we updated all affected
634 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
635 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
636 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
640 w = MIN(x + w, width) - x;
641 h = MIN(y + h, height);
644 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
645 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
649 static void vnc_dpy_update(DisplayChangeListener *dcl,
650 int x, int y, int w, int h)
652 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
653 struct VncSurface *s = &vd->guest;
654 int width = pixman_image_get_width(vd->server);
655 int height = pixman_image_get_height(vd->server);
657 vnc_set_area_dirty(s->dirty, width, height, x, y, w, h);
660 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
663 vnc_write_u16(vs, x);
664 vnc_write_u16(vs, y);
665 vnc_write_u16(vs, w);
666 vnc_write_u16(vs, h);
668 vnc_write_s32(vs, encoding);
672 static void vnc_desktop_resize(VncState *vs)
674 if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
677 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
678 vs->client_height == pixman_image_get_height(vs->vd->server)) {
681 vs->client_width = pixman_image_get_width(vs->vd->server);
682 vs->client_height = pixman_image_get_height(vs->vd->server);
684 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
686 vnc_write_u16(vs, 1); /* number of rects */
687 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
688 VNC_ENCODING_DESKTOPRESIZE);
689 vnc_unlock_output(vs);
693 static void vnc_abort_display_jobs(VncDisplay *vd)
697 QTAILQ_FOREACH(vs, &vd->clients, next) {
700 vnc_unlock_output(vs);
702 QTAILQ_FOREACH(vs, &vd->clients, next) {
705 QTAILQ_FOREACH(vs, &vd->clients, next) {
708 vnc_unlock_output(vs);
712 int vnc_server_fb_stride(VncDisplay *vd)
714 return pixman_image_get_stride(vd->server);
717 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
721 ptr = (uint8_t *)pixman_image_get_data(vd->server);
722 ptr += y * vnc_server_fb_stride(vd);
723 ptr += x * VNC_SERVER_FB_BYTES;
727 static void vnc_dpy_switch(DisplayChangeListener *dcl,
728 DisplaySurface *surface)
730 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
734 vnc_abort_display_jobs(vd);
737 qemu_pixman_image_unref(vd->server);
739 width = vnc_width(vd);
740 height = vnc_height(vd);
741 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
742 width, height, NULL, 0);
745 qemu_pixman_image_unref(vd->guest.fb);
746 vd->guest.fb = pixman_image_ref(surface->image);
747 vd->guest.format = surface->format;
748 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
749 vnc_set_area_dirty(vd->guest.dirty, width, height, 0, 0,
752 QTAILQ_FOREACH(vs, &vd->clients, next) {
754 vnc_desktop_resize(vs);
755 if (vs->vd->cursor) {
756 vnc_cursor_define(vs);
758 memset(vs->dirty, 0x00, sizeof(vs->dirty));
759 vnc_set_area_dirty(vs->dirty, width, height, 0, 0,
765 static void vnc_write_pixels_copy(VncState *vs,
766 void *pixels, int size)
768 vnc_write(vs, pixels, size);
771 /* slowest but generic code. */
772 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
776 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
777 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
778 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
779 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
781 # error need some bits here if you change VNC_SERVER_FB_FORMAT
783 v = (r << vs->client_pf.rshift) |
784 (g << vs->client_pf.gshift) |
785 (b << vs->client_pf.bshift);
786 switch (vs->client_pf.bytes_per_pixel) {
816 static void vnc_write_pixels_generic(VncState *vs,
817 void *pixels1, int size)
821 if (VNC_SERVER_FB_BYTES == 4) {
822 uint32_t *pixels = pixels1;
825 for (i = 0; i < n; i++) {
826 vnc_convert_pixel(vs, buf, pixels[i]);
827 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
832 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
836 VncDisplay *vd = vs->vd;
838 row = vnc_server_fb_ptr(vd, x, y);
839 for (i = 0; i < h; i++) {
840 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
841 row += vnc_server_fb_stride(vd);
846 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
849 bool encode_raw = false;
850 size_t saved_offs = vs->output.offset;
852 switch(vs->vnc_encoding) {
853 case VNC_ENCODING_ZLIB:
854 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
856 case VNC_ENCODING_HEXTILE:
857 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
858 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
860 case VNC_ENCODING_TIGHT:
861 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
863 case VNC_ENCODING_TIGHT_PNG:
864 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
866 case VNC_ENCODING_ZRLE:
867 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
869 case VNC_ENCODING_ZYWRLE:
870 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
877 /* If the client has the same pixel format as our internal buffer and
878 * a RAW encoding would need less space fall back to RAW encoding to
879 * save bandwidth and processing power in the client. */
880 if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
881 12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
882 vs->output.offset = saved_offs;
887 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
888 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
894 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
896 /* send bitblit op to the vnc client */
898 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
900 vnc_write_u16(vs, 1); /* number of rects */
901 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
902 vnc_write_u16(vs, src_x);
903 vnc_write_u16(vs, src_y);
904 vnc_unlock_output(vs);
908 static void vnc_dpy_copy(DisplayChangeListener *dcl,
909 int src_x, int src_y,
910 int dst_x, int dst_y, int w, int h)
912 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
916 int i, x, y, pitch, inc, w_lim, s;
919 vnc_refresh_server_surface(vd);
920 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
921 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
922 vs->force_update = 1;
923 vnc_update_client(vs, 1, true);
924 /* vs might be free()ed here */
928 /* do bitblit op on the local surface too */
929 pitch = vnc_server_fb_stride(vd);
930 src_row = vnc_server_fb_ptr(vd, src_x, src_y);
931 dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
936 src_row += pitch * (h-1);
937 dst_row += pitch * (h-1);
942 w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
946 w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
948 for (i = 0; i < h; i++) {
949 for (x = 0; x <= w_lim;
950 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
952 if ((s = w - w_lim) == 0)
955 s = (VNC_DIRTY_PIXELS_PER_BIT -
956 (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
959 s = VNC_DIRTY_PIXELS_PER_BIT;
961 cmp_bytes = s * VNC_SERVER_FB_BYTES;
962 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
964 memmove(dst_row, src_row, cmp_bytes);
965 QTAILQ_FOREACH(vs, &vd->clients, next) {
966 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
967 set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
972 src_row += pitch - w * VNC_SERVER_FB_BYTES;
973 dst_row += pitch - w * VNC_SERVER_FB_BYTES;
977 QTAILQ_FOREACH(vs, &vd->clients, next) {
978 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
979 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
984 static void vnc_mouse_set(DisplayChangeListener *dcl,
985 int x, int y, int visible)
987 /* can we ask the client(s) to move the pointer ??? */
990 static int vnc_cursor_define(VncState *vs)
992 QEMUCursor *c = vs->vd->cursor;
995 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
997 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
998 vnc_write_u8(vs, 0); /* padding */
999 vnc_write_u16(vs, 1); /* # of rects */
1000 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
1001 VNC_ENCODING_RICH_CURSOR);
1002 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
1003 vnc_write_pixels_generic(vs, c->data, isize);
1004 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
1005 vnc_unlock_output(vs);
1011 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
1014 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
1017 cursor_put(vd->cursor);
1018 g_free(vd->cursor_mask);
1021 cursor_get(vd->cursor);
1022 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
1023 vd->cursor_mask = g_malloc0(vd->cursor_msize);
1024 cursor_get_mono_mask(c, 0, vd->cursor_mask);
1026 QTAILQ_FOREACH(vs, &vd->clients, next) {
1027 vnc_cursor_define(vs);
1031 static int find_and_clear_dirty_height(VncState *vs,
1032 int y, int last_x, int x, int height)
1036 for (h = 1; h < (height - y); h++) {
1037 if (!test_bit(last_x, vs->dirty[y + h])) {
1040 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1046 static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
1048 vs->has_dirty += has_dirty;
1049 if (vs->need_update && vs->csock != -1) {
1050 VncDisplay *vd = vs->vd;
1056 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
1057 /* kernel send buffers are full -> drop frames to throttle */
1060 if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)
1064 * Send screen updates to the vnc client using the server
1065 * surface and server dirty map. guest surface updates
1066 * happening in parallel don't disturb us, the next pass will
1067 * send them to the client.
1069 job = vnc_job_new(vs);
1071 height = pixman_image_get_height(vd->server);
1072 width = pixman_image_get_width(vd->server);
1078 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1079 height * VNC_DIRTY_BPL(vs),
1080 y * VNC_DIRTY_BPL(vs));
1081 if (offset == height * VNC_DIRTY_BPL(vs)) {
1082 /* no more dirty bits */
1085 y = offset / VNC_DIRTY_BPL(vs);
1086 x = offset % VNC_DIRTY_BPL(vs);
1087 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1088 VNC_DIRTY_BPL(vs), x);
1089 bitmap_clear(vs->dirty[y], x, x2 - x);
1090 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1091 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1093 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1094 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1096 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1108 vs->force_update = 0;
1113 if (vs->csock == -1) {
1114 vnc_disconnect_finish(vs);
1123 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1125 VncState *vs = opaque;
1128 case AUD_CNOTIFY_DISABLE:
1129 vnc_lock_output(vs);
1130 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1131 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1132 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1133 vnc_unlock_output(vs);
1137 case AUD_CNOTIFY_ENABLE:
1138 vnc_lock_output(vs);
1139 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1140 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1141 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1142 vnc_unlock_output(vs);
1148 static void audio_capture_destroy(void *opaque)
1152 static void audio_capture(void *opaque, void *buf, int size)
1154 VncState *vs = opaque;
1156 vnc_lock_output(vs);
1157 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1158 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1159 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1160 vnc_write_u32(vs, size);
1161 vnc_write(vs, buf, size);
1162 vnc_unlock_output(vs);
1166 static void audio_add(VncState *vs)
1168 struct audio_capture_ops ops;
1170 if (vs->audio_cap) {
1171 error_report("audio already running");
1175 ops.notify = audio_capture_notify;
1176 ops.destroy = audio_capture_destroy;
1177 ops.capture = audio_capture;
1179 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1180 if (!vs->audio_cap) {
1181 error_report("Failed to add audio capture");
1185 static void audio_del(VncState *vs)
1187 if (vs->audio_cap) {
1188 AUD_del_capture(vs->audio_cap, vs);
1189 vs->audio_cap = NULL;
1193 static void vnc_disconnect_start(VncState *vs)
1195 if (vs->csock == -1)
1197 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1198 qemu_set_fd_handler(vs->csock, NULL, NULL, NULL);
1199 closesocket(vs->csock);
1203 void vnc_disconnect_finish(VncState *vs)
1207 vnc_jobs_join(vs); /* Wait encoding jobs */
1209 vnc_lock_output(vs);
1210 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1212 buffer_free(&vs->input);
1213 buffer_free(&vs->output);
1214 buffer_free(&vs->ws_input);
1215 buffer_free(&vs->ws_output);
1217 qapi_free_VncClientInfo(vs->info);
1220 vnc_tight_clear(vs);
1223 qcrypto_tls_session_free(vs->tls);
1224 #ifdef CONFIG_VNC_SASL
1225 vnc_sasl_client_cleanup(vs);
1226 #endif /* CONFIG_VNC_SASL */
1228 vnc_release_modifiers(vs);
1230 if (vs->initialized) {
1231 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1232 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1235 if (vs->vd->lock_key_sync)
1236 qemu_remove_led_event_handler(vs->led);
1237 vnc_unlock_output(vs);
1239 qemu_mutex_destroy(&vs->output_mutex);
1240 if (vs->bh != NULL) {
1241 qemu_bh_delete(vs->bh);
1243 buffer_free(&vs->jobs_buffer);
1245 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1246 g_free(vs->lossy_rect[i]);
1248 g_free(vs->lossy_rect);
1252 ssize_t vnc_client_io_error(VncState *vs, ssize_t ret, int last_errno)
1254 if (ret == 0 || ret == -1) {
1256 switch (last_errno) {
1260 case WSAEWOULDBLOCK:
1268 VNC_DEBUG("Closing down client sock: ret %zd, errno %d\n",
1269 ret, ret < 0 ? last_errno : 0);
1270 vnc_disconnect_start(vs);
1278 void vnc_client_error(VncState *vs)
1280 VNC_DEBUG("Closing down client sock: protocol error\n");
1281 vnc_disconnect_start(vs);
1285 ssize_t vnc_tls_pull(char *buf, size_t len, void *opaque)
1287 VncState *vs = opaque;
1291 ret = qemu_recv(vs->csock, buf, len, 0);
1293 if (errno == EINTR) {
1302 ssize_t vnc_tls_push(const char *buf, size_t len, void *opaque)
1304 VncState *vs = opaque;
1308 ret = send(vs->csock, buf, len, 0);
1310 if (errno == EINTR) {
1320 * Called to write a chunk of data to the client socket. The data may
1321 * be the raw data, or may have already been encoded by SASL.
1322 * The data will be written either straight onto the socket, or
1323 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1325 * NB, it is theoretically possible to have 2 layers of encryption,
1326 * both SASL, and this TLS layer. It is highly unlikely in practice
1327 * though, since SASL encryption will typically be a no-op if TLS
1330 * Returns the number of bytes written, which may be less than
1331 * the requested 'datalen' if the socket would block. Returns
1332 * -1 on error, and disconnects the client socket.
1334 ssize_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1339 ret = qcrypto_tls_session_write(vs->tls, (const char *)data, datalen);
1344 ret = send(vs->csock, (const void *)data, datalen, 0);
1346 err = socket_error();
1349 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1350 return vnc_client_io_error(vs, ret, err);
1355 * Called to write buffered data to the client socket, when not
1356 * using any SASL SSF encryption layers. Will write as much data
1357 * as possible without blocking. If all buffered data is written,
1358 * will switch the FD poll() handler back to read monitoring.
1360 * Returns the number of bytes written, which may be less than
1361 * the buffered output data if the socket would block. Returns
1362 * -1 on error, and disconnects the client socket.
1364 static ssize_t vnc_client_write_plain(VncState *vs)
1368 #ifdef CONFIG_VNC_SASL
1369 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1370 vs->output.buffer, vs->output.capacity, vs->output.offset,
1371 vs->sasl.waitWriteSSF);
1373 if (vs->sasl.conn &&
1375 vs->sasl.waitWriteSSF) {
1376 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1378 vs->sasl.waitWriteSSF -= ret;
1380 #endif /* CONFIG_VNC_SASL */
1381 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1385 buffer_advance(&vs->output, ret);
1387 if (vs->output.offset == 0) {
1388 qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
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(void *opaque)
1402 VncState *vs = opaque;
1404 #ifdef CONFIG_VNC_SASL
1405 if (vs->sasl.conn &&
1407 !vs->sasl.waitWriteSSF) {
1408 vnc_client_write_sasl(vs);
1410 #endif /* CONFIG_VNC_SASL */
1412 if (vs->encode_ws) {
1413 vnc_client_write_ws(vs);
1415 vnc_client_write_plain(vs);
1420 void vnc_client_write(void *opaque)
1422 VncState *vs = opaque;
1424 vnc_lock_output(vs);
1425 if (vs->output.offset || vs->ws_output.offset) {
1426 vnc_client_write_locked(opaque);
1427 } else if (vs->csock != -1) {
1428 qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
1430 vnc_unlock_output(vs);
1433 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1435 vs->read_handler = func;
1436 vs->read_handler_expect = expecting;
1441 * Called to read a chunk of data from the client socket. The data may
1442 * be the raw data, or may need to be further decoded by SASL.
1443 * The data will be read either straight from to the socket, or
1444 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1446 * NB, it is theoretically possible to have 2 layers of encryption,
1447 * both SASL, and this TLS layer. It is highly unlikely in practice
1448 * though, since SASL encryption will typically be a no-op if TLS
1451 * Returns the number of bytes read, which may be less than
1452 * the requested 'datalen' if the socket would block. Returns
1453 * -1 on error, and disconnects the client socket.
1455 ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1460 ret = qcrypto_tls_session_read(vs->tls, (char *)data, datalen);
1465 ret = qemu_recv(vs->csock, data, datalen, 0);
1467 err = socket_error();
1470 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1471 return vnc_client_io_error(vs, ret, err);
1476 * Called to read data from the client socket to the input buffer,
1477 * when not using any SASL SSF encryption layers. Will read as much
1478 * data as possible without blocking.
1480 * Returns the number of bytes read. Returns -1 on error, and
1481 * disconnects the client socket.
1483 static ssize_t vnc_client_read_plain(VncState *vs)
1486 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1487 vs->input.buffer, vs->input.capacity, vs->input.offset);
1488 buffer_reserve(&vs->input, 4096);
1489 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1492 vs->input.offset += ret;
1496 static void vnc_jobs_bh(void *opaque)
1498 VncState *vs = opaque;
1500 vnc_jobs_consume_buffer(vs);
1504 * First function called whenever there is more data to be read from
1505 * the client socket. Will delegate actual work according to whether
1506 * SASL SSF layers are enabled (thus requiring decryption calls)
1508 void vnc_client_read(void *opaque)
1510 VncState *vs = opaque;
1513 #ifdef CONFIG_VNC_SASL
1514 if (vs->sasl.conn && vs->sasl.runSSF)
1515 ret = vnc_client_read_sasl(vs);
1517 #endif /* CONFIG_VNC_SASL */
1518 if (vs->encode_ws) {
1519 ret = vnc_client_read_ws(vs);
1521 vnc_disconnect_start(vs);
1523 } else if (ret == -2) {
1524 vnc_client_error(vs);
1528 ret = vnc_client_read_plain(vs);
1531 if (vs->csock == -1)
1532 vnc_disconnect_finish(vs);
1536 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1537 size_t len = vs->read_handler_expect;
1540 ret = vs->read_handler(vs, vs->input.buffer, len);
1541 if (vs->csock == -1) {
1542 vnc_disconnect_finish(vs);
1547 buffer_advance(&vs->input, len);
1549 vs->read_handler_expect = ret;
1554 void vnc_write(VncState *vs, const void *data, size_t len)
1556 buffer_reserve(&vs->output, len);
1558 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1559 qemu_set_fd_handler(vs->csock, vnc_client_read, vnc_client_write, vs);
1562 buffer_append(&vs->output, data, len);
1565 void vnc_write_s32(VncState *vs, int32_t value)
1567 vnc_write_u32(vs, *(uint32_t *)&value);
1570 void vnc_write_u32(VncState *vs, uint32_t value)
1574 buf[0] = (value >> 24) & 0xFF;
1575 buf[1] = (value >> 16) & 0xFF;
1576 buf[2] = (value >> 8) & 0xFF;
1577 buf[3] = value & 0xFF;
1579 vnc_write(vs, buf, 4);
1582 void vnc_write_u16(VncState *vs, uint16_t value)
1586 buf[0] = (value >> 8) & 0xFF;
1587 buf[1] = value & 0xFF;
1589 vnc_write(vs, buf, 2);
1592 void vnc_write_u8(VncState *vs, uint8_t value)
1594 vnc_write(vs, (char *)&value, 1);
1597 void vnc_flush(VncState *vs)
1599 vnc_lock_output(vs);
1600 if (vs->csock != -1 && (vs->output.offset ||
1601 vs->ws_output.offset)) {
1602 vnc_client_write_locked(vs);
1604 vnc_unlock_output(vs);
1607 static uint8_t read_u8(uint8_t *data, size_t offset)
1609 return data[offset];
1612 static uint16_t read_u16(uint8_t *data, size_t offset)
1614 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1617 static int32_t read_s32(uint8_t *data, size_t offset)
1619 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1620 (data[offset + 2] << 8) | data[offset + 3]);
1623 uint32_t read_u32(uint8_t *data, size_t offset)
1625 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1626 (data[offset + 2] << 8) | data[offset + 3]);
1629 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1633 static void check_pointer_type_change(Notifier *notifier, void *data)
1635 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1636 int absolute = qemu_input_is_absolute();
1638 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1639 vnc_lock_output(vs);
1640 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1641 vnc_write_u8(vs, 0);
1642 vnc_write_u16(vs, 1);
1643 vnc_framebuffer_update(vs, absolute, 0,
1644 pixman_image_get_width(vs->vd->server),
1645 pixman_image_get_height(vs->vd->server),
1646 VNC_ENCODING_POINTER_TYPE_CHANGE);
1647 vnc_unlock_output(vs);
1650 vs->absolute = absolute;
1653 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1655 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1656 [INPUT_BUTTON_LEFT] = 0x01,
1657 [INPUT_BUTTON_MIDDLE] = 0x02,
1658 [INPUT_BUTTON_RIGHT] = 0x04,
1659 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1660 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1662 QemuConsole *con = vs->vd->dcl.con;
1663 int width = pixman_image_get_width(vs->vd->server);
1664 int height = pixman_image_get_height(vs->vd->server);
1666 if (vs->last_bmask != button_mask) {
1667 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1668 vs->last_bmask = button_mask;
1672 qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
1673 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
1674 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1675 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1676 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1678 if (vs->last_x != -1) {
1679 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1680 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1685 qemu_input_event_sync();
1688 static void reset_keys(VncState *vs)
1691 for(i = 0; i < 256; i++) {
1692 if (vs->modifiers_state[i]) {
1693 qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1694 vs->modifiers_state[i] = 0;
1699 static void press_key(VncState *vs, int keysym)
1701 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1702 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1703 qemu_input_event_send_key_delay(0);
1704 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1705 qemu_input_event_send_key_delay(0);
1708 static int current_led_state(VncState *vs)
1712 if (vs->modifiers_state[0x46]) {
1713 ledstate |= QEMU_SCROLL_LOCK_LED;
1715 if (vs->modifiers_state[0x45]) {
1716 ledstate |= QEMU_NUM_LOCK_LED;
1718 if (vs->modifiers_state[0x3a]) {
1719 ledstate |= QEMU_CAPS_LOCK_LED;
1725 static void vnc_led_state_change(VncState *vs)
1729 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1733 ledstate = current_led_state(vs);
1734 vnc_lock_output(vs);
1735 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1736 vnc_write_u8(vs, 0);
1737 vnc_write_u16(vs, 1);
1738 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1739 vnc_write_u8(vs, ledstate);
1740 vnc_unlock_output(vs);
1744 static void kbd_leds(void *opaque, int ledstate)
1746 VncState *vs = opaque;
1748 bool has_changed = (ledstate != current_led_state(vs));
1750 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1751 (ledstate & QEMU_NUM_LOCK_LED),
1752 (ledstate & QEMU_SCROLL_LOCK_LED));
1754 caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1755 num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
1756 scr = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
1758 if (vs->modifiers_state[0x3a] != caps) {
1759 vs->modifiers_state[0x3a] = caps;
1761 if (vs->modifiers_state[0x45] != num) {
1762 vs->modifiers_state[0x45] = num;
1764 if (vs->modifiers_state[0x46] != scr) {
1765 vs->modifiers_state[0x46] = scr;
1768 /* Sending the current led state message to the client */
1770 vnc_led_state_change(vs);
1774 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1776 /* QEMU console switch */
1778 case 0x2a: /* Left Shift */
1779 case 0x36: /* Right Shift */
1780 case 0x1d: /* Left CTRL */
1781 case 0x9d: /* Right CTRL */
1782 case 0x38: /* Left ALT */
1783 case 0xb8: /* Right ALT */
1785 vs->modifiers_state[keycode] = 1;
1787 vs->modifiers_state[keycode] = 0;
1789 case 0x02 ... 0x0a: /* '1' to '9' keys */
1790 if (vs->vd->dcl.con == NULL &&
1791 down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1792 /* Reset the modifiers sent to the current console */
1794 console_select(keycode - 0x02);
1798 case 0x3a: /* CapsLock */
1799 case 0x45: /* NumLock */
1801 vs->modifiers_state[keycode] ^= 1;
1805 /* Turn off the lock state sync logic if the client support the led
1808 if (down && vs->vd->lock_key_sync &&
1809 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1810 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1811 /* If the numlock state needs to change then simulate an additional
1812 keypress before sending this one. This will happen if the user
1813 toggles numlock away from the VNC window.
1815 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1816 if (!vs->modifiers_state[0x45]) {
1817 trace_vnc_key_sync_numlock(true);
1818 vs->modifiers_state[0x45] = 1;
1819 press_key(vs, 0xff7f);
1822 if (vs->modifiers_state[0x45]) {
1823 trace_vnc_key_sync_numlock(false);
1824 vs->modifiers_state[0x45] = 0;
1825 press_key(vs, 0xff7f);
1830 if (down && vs->vd->lock_key_sync &&
1831 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1832 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1833 /* If the capslock state needs to change then simulate an additional
1834 keypress before sending this one. This will happen if the user
1835 toggles capslock away from the VNC window.
1837 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1838 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1839 int capslock = !!(vs->modifiers_state[0x3a]);
1841 if (uppercase == shift) {
1842 trace_vnc_key_sync_capslock(false);
1843 vs->modifiers_state[0x3a] = 0;
1844 press_key(vs, 0xffe5);
1847 if (uppercase != shift) {
1848 trace_vnc_key_sync_capslock(true);
1849 vs->modifiers_state[0x3a] = 1;
1850 press_key(vs, 0xffe5);
1855 if (qemu_console_is_graphic(NULL)) {
1856 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1858 bool numlock = vs->modifiers_state[0x45];
1859 bool control = (vs->modifiers_state[0x1d] ||
1860 vs->modifiers_state[0x9d]);
1861 /* QEMU console emulation */
1864 case 0x2a: /* Left Shift */
1865 case 0x36: /* Right Shift */
1866 case 0x1d: /* Left CTRL */
1867 case 0x9d: /* Right CTRL */
1868 case 0x38: /* Left ALT */
1869 case 0xb8: /* Right ALT */
1872 kbd_put_keysym(QEMU_KEY_UP);
1875 kbd_put_keysym(QEMU_KEY_DOWN);
1878 kbd_put_keysym(QEMU_KEY_LEFT);
1881 kbd_put_keysym(QEMU_KEY_RIGHT);
1884 kbd_put_keysym(QEMU_KEY_DELETE);
1887 kbd_put_keysym(QEMU_KEY_HOME);
1890 kbd_put_keysym(QEMU_KEY_END);
1893 kbd_put_keysym(QEMU_KEY_PAGEUP);
1896 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1900 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1903 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1906 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1909 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1912 kbd_put_keysym('5');
1915 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1918 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1921 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1924 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1927 kbd_put_keysym('0');
1930 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1934 kbd_put_keysym('/');
1937 kbd_put_keysym('*');
1940 kbd_put_keysym('-');
1943 kbd_put_keysym('+');
1946 kbd_put_keysym('\n');
1951 kbd_put_keysym(sym & 0x1f);
1953 kbd_put_keysym(sym);
1961 static void vnc_release_modifiers(VncState *vs)
1963 static const int keycodes[] = {
1964 /* shift, control, alt keys, both left & right */
1965 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1969 if (!qemu_console_is_graphic(NULL)) {
1972 for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1973 keycode = keycodes[i];
1974 if (!vs->modifiers_state[keycode]) {
1977 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1981 static const char *code2name(int keycode)
1983 return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
1986 static void key_event(VncState *vs, int down, uint32_t sym)
1991 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1992 lsym = lsym - 'A' + 'a';
1995 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1996 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1997 do_key_event(vs, down, keycode, sym);
2000 static void ext_key_event(VncState *vs, int down,
2001 uint32_t sym, uint16_t keycode)
2003 /* if the user specifies a keyboard layout, always use it */
2004 if (keyboard_layout) {
2005 key_event(vs, down, sym);
2007 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2008 do_key_event(vs, down, keycode, sym);
2012 static void framebuffer_update_request(VncState *vs, int incremental,
2013 int x, int y, int w, int h)
2015 int width = pixman_image_get_width(vs->vd->server);
2016 int height = pixman_image_get_height(vs->vd->server);
2018 vs->need_update = 1;
2024 vs->force_update = 1;
2025 vnc_set_area_dirty(vs->dirty, width, height, x, y, w, h);
2028 static void send_ext_key_event_ack(VncState *vs)
2030 vnc_lock_output(vs);
2031 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2032 vnc_write_u8(vs, 0);
2033 vnc_write_u16(vs, 1);
2034 vnc_framebuffer_update(vs, 0, 0,
2035 pixman_image_get_width(vs->vd->server),
2036 pixman_image_get_height(vs->vd->server),
2037 VNC_ENCODING_EXT_KEY_EVENT);
2038 vnc_unlock_output(vs);
2042 static void send_ext_audio_ack(VncState *vs)
2044 vnc_lock_output(vs);
2045 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2046 vnc_write_u8(vs, 0);
2047 vnc_write_u16(vs, 1);
2048 vnc_framebuffer_update(vs, 0, 0,
2049 pixman_image_get_width(vs->vd->server),
2050 pixman_image_get_height(vs->vd->server),
2051 VNC_ENCODING_AUDIO);
2052 vnc_unlock_output(vs);
2056 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2059 unsigned int enc = 0;
2062 vs->vnc_encoding = 0;
2063 vs->tight.compression = 9;
2064 vs->tight.quality = -1; /* Lossless by default */
2068 * Start from the end because the encodings are sent in order of preference.
2069 * This way the preferred encoding (first encoding defined in the array)
2070 * will be set at the end of the loop.
2072 for (i = n_encodings - 1; i >= 0; i--) {
2075 case VNC_ENCODING_RAW:
2076 vs->vnc_encoding = enc;
2078 case VNC_ENCODING_COPYRECT:
2079 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2081 case VNC_ENCODING_HEXTILE:
2082 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2083 vs->vnc_encoding = enc;
2085 case VNC_ENCODING_TIGHT:
2086 vs->features |= VNC_FEATURE_TIGHT_MASK;
2087 vs->vnc_encoding = enc;
2089 #ifdef CONFIG_VNC_PNG
2090 case VNC_ENCODING_TIGHT_PNG:
2091 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2092 vs->vnc_encoding = enc;
2095 case VNC_ENCODING_ZLIB:
2096 vs->features |= VNC_FEATURE_ZLIB_MASK;
2097 vs->vnc_encoding = enc;
2099 case VNC_ENCODING_ZRLE:
2100 vs->features |= VNC_FEATURE_ZRLE_MASK;
2101 vs->vnc_encoding = enc;
2103 case VNC_ENCODING_ZYWRLE:
2104 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2105 vs->vnc_encoding = enc;
2107 case VNC_ENCODING_DESKTOPRESIZE:
2108 vs->features |= VNC_FEATURE_RESIZE_MASK;
2110 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2111 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2113 case VNC_ENCODING_RICH_CURSOR:
2114 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2116 case VNC_ENCODING_EXT_KEY_EVENT:
2117 send_ext_key_event_ack(vs);
2119 case VNC_ENCODING_AUDIO:
2120 send_ext_audio_ack(vs);
2122 case VNC_ENCODING_WMVi:
2123 vs->features |= VNC_FEATURE_WMVI_MASK;
2125 case VNC_ENCODING_LED_STATE:
2126 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2128 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2129 vs->tight.compression = (enc & 0x0F);
2131 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2132 if (vs->vd->lossy) {
2133 vs->tight.quality = (enc & 0x0F);
2137 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2141 vnc_desktop_resize(vs);
2142 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2143 vnc_led_state_change(vs);
2146 static void set_pixel_conversion(VncState *vs)
2148 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2150 if (fmt == VNC_SERVER_FB_FORMAT) {
2151 vs->write_pixels = vnc_write_pixels_copy;
2152 vnc_hextile_set_pixel_conversion(vs, 0);
2154 vs->write_pixels = vnc_write_pixels_generic;
2155 vnc_hextile_set_pixel_conversion(vs, 1);
2159 static void set_pixel_format(VncState *vs,
2160 int bits_per_pixel, int depth,
2161 int big_endian_flag, int true_color_flag,
2162 int red_max, int green_max, int blue_max,
2163 int red_shift, int green_shift, int blue_shift)
2165 if (!true_color_flag) {
2166 vnc_client_error(vs);
2170 switch (bits_per_pixel) {
2176 vnc_client_error(vs);
2180 vs->client_pf.rmax = red_max;
2181 vs->client_pf.rbits = hweight_long(red_max);
2182 vs->client_pf.rshift = red_shift;
2183 vs->client_pf.rmask = red_max << red_shift;
2184 vs->client_pf.gmax = green_max;
2185 vs->client_pf.gbits = hweight_long(green_max);
2186 vs->client_pf.gshift = green_shift;
2187 vs->client_pf.gmask = green_max << green_shift;
2188 vs->client_pf.bmax = blue_max;
2189 vs->client_pf.bbits = hweight_long(blue_max);
2190 vs->client_pf.bshift = blue_shift;
2191 vs->client_pf.bmask = blue_max << blue_shift;
2192 vs->client_pf.bits_per_pixel = bits_per_pixel;
2193 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2194 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2195 vs->client_be = big_endian_flag;
2197 set_pixel_conversion(vs);
2199 graphic_hw_invalidate(vs->vd->dcl.con);
2200 graphic_hw_update(vs->vd->dcl.con);
2203 static void pixel_format_message (VncState *vs) {
2204 char pad[3] = { 0, 0, 0 };
2206 vs->client_pf = qemu_default_pixelformat(32);
2208 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2209 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2211 #ifdef HOST_WORDS_BIGENDIAN
2212 vnc_write_u8(vs, 1); /* big-endian-flag */
2214 vnc_write_u8(vs, 0); /* big-endian-flag */
2216 vnc_write_u8(vs, 1); /* true-color-flag */
2217 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2218 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2219 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2220 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2221 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2222 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2223 vnc_write(vs, pad, 3); /* padding */
2225 vnc_hextile_set_pixel_conversion(vs, 0);
2226 vs->write_pixels = vnc_write_pixels_copy;
2229 static void vnc_colordepth(VncState *vs)
2231 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2232 /* Sending a WMVi message to notify the client*/
2233 vnc_lock_output(vs);
2234 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2235 vnc_write_u8(vs, 0);
2236 vnc_write_u16(vs, 1); /* number of rects */
2237 vnc_framebuffer_update(vs, 0, 0,
2238 pixman_image_get_width(vs->vd->server),
2239 pixman_image_get_height(vs->vd->server),
2241 pixel_format_message(vs);
2242 vnc_unlock_output(vs);
2245 set_pixel_conversion(vs);
2249 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2253 VncDisplay *vd = vs->vd;
2256 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2260 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2264 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
2265 read_u8(data, 6), read_u8(data, 7),
2266 read_u16(data, 8), read_u16(data, 10),
2267 read_u16(data, 12), read_u8(data, 14),
2268 read_u8(data, 15), read_u8(data, 16));
2270 case VNC_MSG_CLIENT_SET_ENCODINGS:
2275 limit = read_u16(data, 2);
2277 return 4 + (limit * 4);
2279 limit = read_u16(data, 2);
2281 for (i = 0; i < limit; i++) {
2282 int32_t val = read_s32(data, 4 + (i * 4));
2283 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2286 set_encodings(vs, (int32_t *)(data + 4), limit);
2288 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2292 framebuffer_update_request(vs,
2293 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2294 read_u16(data, 6), read_u16(data, 8));
2296 case VNC_MSG_CLIENT_KEY_EVENT:
2300 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2302 case VNC_MSG_CLIENT_POINTER_EVENT:
2306 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2308 case VNC_MSG_CLIENT_CUT_TEXT:
2313 uint32_t dlen = read_u32(data, 4);
2314 if (dlen > (1 << 20)) {
2315 error_report("vnc: client_cut_text msg payload has %u bytes"
2316 " which exceeds our limit of 1MB.", dlen);
2317 vnc_client_error(vs);
2325 client_cut_text(vs, read_u32(data, 4), data + 8);
2327 case VNC_MSG_CLIENT_QEMU:
2331 switch (read_u8(data, 1)) {
2332 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2336 ext_key_event(vs, read_u16(data, 2),
2337 read_u32(data, 4), read_u32(data, 8));
2339 case VNC_MSG_CLIENT_QEMU_AUDIO:
2343 switch (read_u16 (data, 2)) {
2344 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2347 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2350 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2353 switch (read_u8(data, 4)) {
2354 case 0: vs->as.fmt = AUD_FMT_U8; break;
2355 case 1: vs->as.fmt = AUD_FMT_S8; break;
2356 case 2: vs->as.fmt = AUD_FMT_U16; break;
2357 case 3: vs->as.fmt = AUD_FMT_S16; break;
2358 case 4: vs->as.fmt = AUD_FMT_U32; break;
2359 case 5: vs->as.fmt = AUD_FMT_S32; break;
2361 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2362 vnc_client_error(vs);
2365 vs->as.nchannels = read_u8(data, 5);
2366 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2367 VNC_DEBUG("Invalid audio channel coount %d\n",
2369 vnc_client_error(vs);
2372 vs->as.freq = read_u32(data, 6);
2375 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2376 vnc_client_error(vs);
2382 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2383 vnc_client_error(vs);
2388 VNC_DEBUG("Msg: %d\n", data[0]);
2389 vnc_client_error(vs);
2393 vnc_read_when(vs, protocol_client_msg, 1);
2397 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2403 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2404 switch (vs->vd->share_policy) {
2405 case VNC_SHARE_POLICY_IGNORE:
2407 * Ignore the shared flag. Nothing to do here.
2409 * Doesn't conform to the rfb spec but is traditional qemu
2410 * behavior, thus left here as option for compatibility
2414 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2416 * Policy: Allow clients ask for exclusive access.
2418 * Implementation: When a client asks for exclusive access,
2419 * disconnect all others. Shared connects are allowed as long
2420 * as no exclusive connection exists.
2422 * This is how the rfb spec suggests to handle the shared flag.
2424 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2426 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2430 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2431 client->share_mode != VNC_SHARE_MODE_SHARED) {
2434 vnc_disconnect_start(client);
2437 if (mode == VNC_SHARE_MODE_SHARED) {
2438 if (vs->vd->num_exclusive > 0) {
2439 vnc_disconnect_start(vs);
2444 case VNC_SHARE_POLICY_FORCE_SHARED:
2446 * Policy: Shared connects only.
2447 * Implementation: Disallow clients asking for exclusive access.
2449 * Useful for shared desktop sessions where you don't want
2450 * someone forgetting to say -shared when running the vnc
2451 * client disconnect everybody else.
2453 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2454 vnc_disconnect_start(vs);
2459 vnc_set_share_mode(vs, mode);
2461 if (vs->vd->num_shared > vs->vd->connections_limit) {
2462 vnc_disconnect_start(vs);
2466 vs->client_width = pixman_image_get_width(vs->vd->server);
2467 vs->client_height = pixman_image_get_height(vs->vd->server);
2468 vnc_write_u16(vs, vs->client_width);
2469 vnc_write_u16(vs, vs->client_height);
2471 pixel_format_message(vs);
2474 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2476 size = snprintf(buf, sizeof(buf), "QEMU");
2478 vnc_write_u32(vs, size);
2479 vnc_write(vs, buf, size);
2482 vnc_client_cache_auth(vs);
2483 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2485 vnc_read_when(vs, protocol_client_msg, 1);
2490 void start_client_init(VncState *vs)
2492 vnc_read_when(vs, protocol_client_init, 1);
2495 static void make_challenge(VncState *vs)
2499 srand(time(NULL)+getpid()+getpid()*987654+rand());
2501 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2502 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2505 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2507 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2509 unsigned char key[8];
2510 time_t now = time(NULL);
2511 QCryptoCipher *cipher = NULL;
2514 if (!vs->vd->password) {
2515 VNC_DEBUG("No password configured on server");
2518 if (vs->vd->expires < now) {
2519 VNC_DEBUG("Password is expired");
2523 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2525 /* Calculate the expected challenge response */
2526 pwlen = strlen(vs->vd->password);
2527 for (i=0; i<sizeof(key); i++)
2528 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2530 cipher = qcrypto_cipher_new(
2531 QCRYPTO_CIPHER_ALG_DES_RFB,
2532 QCRYPTO_CIPHER_MODE_ECB,
2533 key, G_N_ELEMENTS(key),
2536 VNC_DEBUG("Cannot initialize cipher %s",
2537 error_get_pretty(err));
2542 if (qcrypto_cipher_encrypt(cipher,
2545 VNC_AUTH_CHALLENGE_SIZE,
2547 VNC_DEBUG("Cannot encrypt challenge %s",
2548 error_get_pretty(err));
2553 /* Compare expected vs actual challenge response */
2554 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2555 VNC_DEBUG("Client challenge response did not match\n");
2558 VNC_DEBUG("Accepting VNC challenge response\n");
2559 vnc_write_u32(vs, 0); /* Accept auth */
2562 start_client_init(vs);
2565 qcrypto_cipher_free(cipher);
2569 vnc_write_u32(vs, 1); /* Reject auth */
2570 if (vs->minor >= 8) {
2571 static const char err[] = "Authentication failed";
2572 vnc_write_u32(vs, sizeof(err));
2573 vnc_write(vs, err, sizeof(err));
2576 vnc_client_error(vs);
2577 qcrypto_cipher_free(cipher);
2581 void start_auth_vnc(VncState *vs)
2584 /* Send client a 'random' challenge */
2585 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2588 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2592 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2594 /* We only advertise 1 auth scheme at a time, so client
2595 * must pick the one we sent. Verify this */
2596 if (data[0] != vs->auth) { /* Reject auth */
2597 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2598 vnc_write_u32(vs, 1);
2599 if (vs->minor >= 8) {
2600 static const char err[] = "Authentication failed";
2601 vnc_write_u32(vs, sizeof(err));
2602 vnc_write(vs, err, sizeof(err));
2604 vnc_client_error(vs);
2605 } else { /* Accept requested auth */
2606 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2609 VNC_DEBUG("Accept auth none\n");
2610 if (vs->minor >= 8) {
2611 vnc_write_u32(vs, 0); /* Accept auth completion */
2614 start_client_init(vs);
2618 VNC_DEBUG("Start VNC auth\n");
2622 case VNC_AUTH_VENCRYPT:
2623 VNC_DEBUG("Accept VeNCrypt auth\n");
2624 start_auth_vencrypt(vs);
2627 #ifdef CONFIG_VNC_SASL
2629 VNC_DEBUG("Accept SASL auth\n");
2630 start_auth_sasl(vs);
2632 #endif /* CONFIG_VNC_SASL */
2634 default: /* Should not be possible, but just in case */
2635 VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2636 vnc_write_u8(vs, 1);
2637 if (vs->minor >= 8) {
2638 static const char err[] = "Authentication failed";
2639 vnc_write_u32(vs, sizeof(err));
2640 vnc_write(vs, err, sizeof(err));
2642 vnc_client_error(vs);
2648 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2652 memcpy(local, version, 12);
2655 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2656 VNC_DEBUG("Malformed protocol version %s\n", local);
2657 vnc_client_error(vs);
2660 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2661 if (vs->major != 3 ||
2667 VNC_DEBUG("Unsupported client version\n");
2668 vnc_write_u32(vs, VNC_AUTH_INVALID);
2670 vnc_client_error(vs);
2673 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2674 * as equivalent to v3.3 by servers
2676 if (vs->minor == 4 || vs->minor == 5)
2679 if (vs->minor == 3) {
2680 if (vs->auth == VNC_AUTH_NONE) {
2681 VNC_DEBUG("Tell client auth none\n");
2682 vnc_write_u32(vs, vs->auth);
2684 start_client_init(vs);
2685 } else if (vs->auth == VNC_AUTH_VNC) {
2686 VNC_DEBUG("Tell client VNC auth\n");
2687 vnc_write_u32(vs, vs->auth);
2691 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2692 vnc_write_u32(vs, VNC_AUTH_INVALID);
2694 vnc_client_error(vs);
2697 VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2698 vnc_write_u8(vs, 1); /* num auth */
2699 vnc_write_u8(vs, vs->auth);
2700 vnc_read_when(vs, protocol_client_auth, 1);
2707 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2709 struct VncSurface *vs = &vd->guest;
2711 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2714 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2718 w = (x + w) / VNC_STAT_RECT;
2719 h = (y + h) / VNC_STAT_RECT;
2723 for (j = y; j <= h; j++) {
2724 for (i = x; i <= w; i++) {
2725 vs->lossy_rect[j][i] = 1;
2730 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2733 int sty = y / VNC_STAT_RECT;
2734 int stx = x / VNC_STAT_RECT;
2737 y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2738 x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2740 QTAILQ_FOREACH(vs, &vd->clients, next) {
2743 /* kernel send buffers are full -> refresh later */
2744 if (vs->output.offset) {
2748 if (!vs->lossy_rect[sty][stx]) {
2752 vs->lossy_rect[sty][stx] = 0;
2753 for (j = 0; j < VNC_STAT_RECT; ++j) {
2754 bitmap_set(vs->dirty[y + j],
2755 x / VNC_DIRTY_PIXELS_PER_BIT,
2756 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2764 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2766 int width = pixman_image_get_width(vd->guest.fb);
2767 int height = pixman_image_get_height(vd->guest.fb);
2772 for (y = 0; y < height; y += VNC_STAT_RECT) {
2773 for (x = 0; x < width; x += VNC_STAT_RECT) {
2774 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2776 rect->updated = false;
2780 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2782 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2785 vd->guest.last_freq_check = *tv;
2787 for (y = 0; y < height; y += VNC_STAT_RECT) {
2788 for (x = 0; x < width; x += VNC_STAT_RECT) {
2789 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2790 int count = ARRAY_SIZE(rect->times);
2791 struct timeval min, max;
2793 if (!timerisset(&rect->times[count - 1])) {
2797 max = rect->times[(rect->idx + count - 1) % count];
2798 qemu_timersub(tv, &max, &res);
2800 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2802 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2803 memset(rect->times, 0, sizeof (rect->times));
2807 min = rect->times[rect->idx];
2808 max = rect->times[(rect->idx + count - 1) % count];
2809 qemu_timersub(&max, &min, &res);
2811 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2812 rect->freq /= count;
2813 rect->freq = 1. / rect->freq;
2819 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2825 x = (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2826 y = (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2828 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2829 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2830 total += vnc_stat_rect(vs->vd, i, j)->freq;
2842 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2846 rect = vnc_stat_rect(vd, x, y);
2847 if (rect->updated) {
2850 rect->times[rect->idx] = *tv;
2851 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2852 rect->updated = true;
2855 static int vnc_refresh_server_surface(VncDisplay *vd)
2857 int width = MIN(pixman_image_get_width(vd->guest.fb),
2858 pixman_image_get_width(vd->server));
2859 int height = MIN(pixman_image_get_height(vd->guest.fb),
2860 pixman_image_get_height(vd->server));
2861 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2862 uint8_t *guest_row0 = NULL, *server_row0;
2865 pixman_image_t *tmpbuf = NULL;
2867 struct timeval tv = { 0, 0 };
2869 if (!vd->non_adaptive) {
2870 gettimeofday(&tv, NULL);
2871 has_dirty = vnc_update_stats(vd, &tv);
2875 * Walk through the guest dirty map.
2876 * Check and copy modified bits from guest to server surface.
2877 * Update server dirty map.
2879 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2880 server_stride = guest_stride = guest_ll =
2881 pixman_image_get_stride(vd->server);
2882 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2884 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2885 int width = pixman_image_get_width(vd->server);
2886 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2889 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2890 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2891 guest_stride = pixman_image_get_stride(vd->guest.fb);
2892 guest_ll = pixman_image_get_width(vd->guest.fb) * ((guest_bpp + 7) / 8);
2894 line_bytes = MIN(server_stride, guest_ll);
2898 uint8_t *guest_ptr, *server_ptr;
2899 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2900 height * VNC_DIRTY_BPL(&vd->guest),
2901 y * VNC_DIRTY_BPL(&vd->guest));
2902 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2903 /* no more dirty bits */
2906 y = offset / VNC_DIRTY_BPL(&vd->guest);
2907 x = offset % VNC_DIRTY_BPL(&vd->guest);
2909 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2911 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2912 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2913 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2915 guest_ptr = guest_row0 + y * guest_stride;
2917 guest_ptr += x * cmp_bytes;
2919 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2920 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2921 int _cmp_bytes = cmp_bytes;
2922 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2925 if ((x + 1) * cmp_bytes > line_bytes) {
2926 _cmp_bytes = line_bytes - x * cmp_bytes;
2928 assert(_cmp_bytes >= 0);
2929 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2932 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2933 if (!vd->non_adaptive) {
2934 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2937 QTAILQ_FOREACH(vs, &vd->clients, next) {
2938 set_bit(x, vs->dirty[y]);
2945 qemu_pixman_image_unref(tmpbuf);
2949 static void vnc_refresh(DisplayChangeListener *dcl)
2951 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2953 int has_dirty, rects = 0;
2955 if (QTAILQ_EMPTY(&vd->clients)) {
2956 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2960 graphic_hw_update(vd->dcl.con);
2962 if (vnc_trylock_display(vd)) {
2963 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2967 has_dirty = vnc_refresh_server_surface(vd);
2968 vnc_unlock_display(vd);
2970 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2971 rects += vnc_update_client(vs, has_dirty, false);
2972 /* vs might be free()ed here */
2975 if (has_dirty && rects) {
2976 vd->dcl.update_interval /= 2;
2977 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
2978 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
2981 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
2982 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
2983 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
2988 static void vnc_connect(VncDisplay *vd, int csock,
2989 bool skipauth, bool websocket)
2991 VncState *vs = g_malloc0(sizeof(VncState));
2997 buffer_init(&vs->input, "vnc-input/%d", csock);
2998 buffer_init(&vs->output, "vnc-output/%d", csock);
2999 buffer_init(&vs->ws_input, "vnc-ws_input/%d", csock);
3000 buffer_init(&vs->ws_output, "vnc-ws_output/%d", csock);
3001 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%d", csock);
3003 buffer_init(&vs->tight.tight, "vnc-tight/%d", csock);
3004 buffer_init(&vs->tight.zlib, "vnc-tight-zlib/%d", csock);
3005 buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%d", csock);
3006 #ifdef CONFIG_VNC_JPEG
3007 buffer_init(&vs->tight.jpeg, "vnc-tight-jpeg/%d", csock);
3009 #ifdef CONFIG_VNC_PNG
3010 buffer_init(&vs->tight.png, "vnc-tight-png/%d", csock);
3012 buffer_init(&vs->zlib.zlib, "vnc-zlib/%d", csock);
3013 buffer_init(&vs->zrle.zrle, "vnc-zrle/%d", csock);
3014 buffer_init(&vs->zrle.fb, "vnc-zrle-fb/%d", csock);
3015 buffer_init(&vs->zrle.zlib, "vnc-zrle-zlib/%d", csock);
3018 vs->auth = VNC_AUTH_NONE;
3019 vs->subauth = VNC_AUTH_INVALID;
3022 vs->auth = vd->ws_auth;
3023 vs->subauth = VNC_AUTH_INVALID;
3025 vs->auth = vd->auth;
3026 vs->subauth = vd->subauth;
3029 VNC_DEBUG("Client sock=%d ws=%d auth=%d subauth=%d\n",
3030 csock, websocket, vs->auth, vs->subauth);
3032 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3033 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3034 vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
3037 VNC_DEBUG("New client on socket %d\n", csock);
3038 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3039 qemu_set_nonblock(vs->csock);
3043 qemu_set_fd_handler(vs->csock, vncws_tls_handshake_io, NULL, vs);
3045 qemu_set_fd_handler(vs->csock, vncws_handshake_read, NULL, vs);
3049 qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
3052 vnc_client_cache_addr(vs);
3053 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3054 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3056 if (!vs->websocket) {
3060 if (vd->num_connecting > vd->connections_limit) {
3061 QTAILQ_FOREACH(vs, &vd->clients, next) {
3062 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3063 vnc_disconnect_start(vs);
3070 void vnc_init_state(VncState *vs)
3072 vs->initialized = true;
3073 VncDisplay *vd = vs->vd;
3078 vs->as.freq = 44100;
3079 vs->as.nchannels = 2;
3080 vs->as.fmt = AUD_FMT_S16;
3081 vs->as.endianness = 0;
3083 qemu_mutex_init(&vs->output_mutex);
3084 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3086 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3088 graphic_hw_update(vd->dcl.con);
3090 vnc_write(vs, "RFB 003.008\n", 12);
3092 vnc_read_when(vs, protocol_version, 12);
3094 if (vs->vd->lock_key_sync)
3095 vs->led = qemu_add_led_event_handler(kbd_leds, vs);
3097 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3098 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3100 /* vs might be free()ed here */
3103 static void vnc_listen_read(void *opaque, bool websocket)
3105 VncDisplay *vs = opaque;
3106 struct sockaddr_in addr;
3107 socklen_t addrlen = sizeof(addr);
3111 graphic_hw_update(vs->dcl.con);
3113 csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
3115 csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
3119 socket_set_nodelay(csock);
3120 vnc_connect(vs, csock, false, websocket);
3124 static void vnc_listen_regular_read(void *opaque)
3126 vnc_listen_read(opaque, false);
3129 static void vnc_listen_websocket_read(void *opaque)
3131 vnc_listen_read(opaque, true);
3134 static const DisplayChangeListenerOps dcl_ops = {
3136 .dpy_refresh = vnc_refresh,
3137 .dpy_gfx_copy = vnc_dpy_copy,
3138 .dpy_gfx_update = vnc_dpy_update,
3139 .dpy_gfx_switch = vnc_dpy_switch,
3140 .dpy_gfx_check_format = qemu_pixman_check_format,
3141 .dpy_mouse_set = vnc_mouse_set,
3142 .dpy_cursor_define = vnc_dpy_cursor_define,
3145 void vnc_display_init(const char *id)
3149 if (vnc_display_find(id) != NULL) {
3152 vs = g_malloc0(sizeof(*vs));
3154 vs->id = strdup(id);
3155 QTAILQ_INSERT_TAIL(&vnc_displays, vs, next);
3160 QTAILQ_INIT(&vs->clients);
3161 vs->expires = TIME_MAX;
3163 if (keyboard_layout) {
3164 trace_vnc_key_map_init(keyboard_layout);
3165 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
3167 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
3170 if (!vs->kbd_layout)
3173 qemu_mutex_init(&vs->mutex);
3174 vnc_start_worker_thread();
3176 vs->dcl.ops = &dcl_ops;
3177 register_displaychangelistener(&vs->dcl);
3181 static void vnc_display_close(VncDisplay *vs)
3185 vs->enabled = false;
3186 vs->is_unix = false;
3187 if (vs->lsock != -1) {
3188 qemu_set_fd_handler(vs->lsock, NULL, NULL, NULL);
3192 vs->ws_enabled = false;
3193 if (vs->lwebsock != -1) {
3194 qemu_set_fd_handler(vs->lwebsock, NULL, NULL, NULL);
3195 close(vs->lwebsock);
3198 vs->auth = VNC_AUTH_INVALID;
3199 vs->subauth = VNC_AUTH_INVALID;
3201 object_unparent(OBJECT(vs->tlscreds));
3203 g_free(vs->tlsaclname);
3204 vs->tlsaclname = NULL;
3207 int vnc_display_password(const char *id, const char *password)
3209 VncDisplay *vs = vnc_display_find(id);
3214 if (vs->auth == VNC_AUTH_NONE) {
3215 error_printf_unless_qmp("If you want use passwords please enable "
3216 "password auth using '-vnc ${dpy},password'.");
3220 g_free(vs->password);
3221 vs->password = g_strdup(password);
3226 int vnc_display_pw_expire(const char *id, time_t expires)
3228 VncDisplay *vs = vnc_display_find(id);
3234 vs->expires = expires;
3238 char *vnc_display_local_addr(const char *id)
3240 VncDisplay *vs = vnc_display_find(id);
3243 return vnc_socket_local_addr("%s:%s", vs->lsock);
3246 static QemuOptsList qemu_vnc_opts = {
3248 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3249 .implied_opt_name = "vnc",
3253 .type = QEMU_OPT_STRING,
3255 .name = "websocket",
3256 .type = QEMU_OPT_STRING,
3258 .name = "tls-creds",
3259 .type = QEMU_OPT_STRING,
3261 /* Deprecated in favour of tls-creds */
3263 .type = QEMU_OPT_STRING,
3266 .type = QEMU_OPT_STRING,
3269 .type = QEMU_OPT_STRING,
3272 .type = QEMU_OPT_NUMBER,
3274 .name = "connections",
3275 .type = QEMU_OPT_NUMBER,
3278 .type = QEMU_OPT_NUMBER,
3281 .type = QEMU_OPT_BOOL,
3284 .type = QEMU_OPT_BOOL,
3287 .type = QEMU_OPT_BOOL,
3290 .type = QEMU_OPT_BOOL,
3292 .name = "lock-key-sync",
3293 .type = QEMU_OPT_BOOL,
3296 .type = QEMU_OPT_BOOL,
3298 /* Deprecated in favour of tls-creds */
3300 .type = QEMU_OPT_BOOL,
3302 /* Deprecated in favour of tls-creds */
3303 .name = "x509verify",
3304 .type = QEMU_OPT_STRING,
3307 .type = QEMU_OPT_BOOL,
3310 .type = QEMU_OPT_BOOL,
3312 .name = "non-adaptive",
3313 .type = QEMU_OPT_BOOL,
3315 { /* end of list */ }
3321 vnc_display_setup_auth(VncDisplay *vs,
3328 * We have a choice of 3 authentication options
3334 * The channel can be run in 2 modes
3339 * And TLS can use 2 types of credentials
3344 * We thus have 9 possible logical combinations
3349 * 4. tls + anon + none
3350 * 5. tls + anon + vnc
3351 * 6. tls + anon + sasl
3352 * 7. tls + x509 + none
3353 * 8. tls + x509 + vnc
3354 * 9. tls + x509 + sasl
3356 * These need to be mapped into the VNC auth schemes
3357 * in an appropriate manner. In regular VNC, all the
3358 * TLS options get mapped into VNC_AUTH_VENCRYPT
3361 * In websockets, the https:// protocol already provides
3362 * TLS support, so there is no need to make use of the
3363 * VeNCrypt extension. Furthermore, websockets browser
3364 * clients could not use VeNCrypt even if they wanted to,
3365 * as they cannot control when the TLS handshake takes
3366 * place. Thus there is no option but to rely on https://,
3367 * meaning combinations 4->6 and 7->9 will be mapped to
3368 * VNC auth schemes in the same way as combos 1->3.
3370 * Regardless of fact that we have a different mapping to
3371 * VNC auth mechs for plain VNC vs websockets VNC, the end
3372 * result has the same security characteristics.
3376 vs->auth = VNC_AUTH_VENCRYPT;
3380 if (object_dynamic_cast(OBJECT(vs->tlscreds),
3381 TYPE_QCRYPTO_TLS_CREDS_X509)) {
3382 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3383 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
3384 } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
3385 TYPE_QCRYPTO_TLS_CREDS_ANON)) {
3386 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3387 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3390 "Unsupported TLS cred type %s",
3391 object_get_typename(OBJECT(vs->tlscreds)));
3395 VNC_DEBUG("Initializing VNC server with password auth\n");
3396 vs->auth = VNC_AUTH_VNC;
3397 vs->subauth = VNC_AUTH_INVALID;
3400 vs->ws_auth = VNC_AUTH_VNC;
3402 vs->ws_auth = VNC_AUTH_INVALID;
3406 vs->auth = VNC_AUTH_VENCRYPT;
3410 if (object_dynamic_cast(OBJECT(vs->tlscreds),
3411 TYPE_QCRYPTO_TLS_CREDS_X509)) {
3412 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3413 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3414 } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
3415 TYPE_QCRYPTO_TLS_CREDS_ANON)) {
3416 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3417 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3420 "Unsupported TLS cred type %s",
3421 object_get_typename(OBJECT(vs->tlscreds)));
3425 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3426 vs->auth = VNC_AUTH_SASL;
3427 vs->subauth = VNC_AUTH_INVALID;
3430 vs->ws_auth = VNC_AUTH_SASL;
3432 vs->ws_auth = VNC_AUTH_INVALID;
3436 vs->auth = VNC_AUTH_VENCRYPT;
3440 if (object_dynamic_cast(OBJECT(vs->tlscreds),
3441 TYPE_QCRYPTO_TLS_CREDS_X509)) {
3442 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3443 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3444 } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
3445 TYPE_QCRYPTO_TLS_CREDS_ANON)) {
3446 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3447 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3450 "Unsupported TLS cred type %s",
3451 object_get_typename(OBJECT(vs->tlscreds)));
3455 VNC_DEBUG("Initializing VNC server with no auth\n");
3456 vs->auth = VNC_AUTH_NONE;
3457 vs->subauth = VNC_AUTH_INVALID;
3460 vs->ws_auth = VNC_AUTH_NONE;
3462 vs->ws_auth = VNC_AUTH_INVALID;
3470 * Handle back compat with old CLI syntax by creating some
3471 * suitable QCryptoTLSCreds objects
3473 static QCryptoTLSCreds *
3474 vnc_display_create_creds(bool x509,
3480 gchar *credsid = g_strdup_printf("tlsvnc%s", id);
3481 Object *parent = object_get_objects_root();
3486 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
3490 "endpoint", "server",
3492 "verify-peer", x509verify ? "yes" : "no",
3495 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
3499 "endpoint", "server",
3506 error_propagate(errp, err);
3510 return QCRYPTO_TLS_CREDS(creds);
3514 void vnc_display_open(const char *id, Error **errp)
3516 VncDisplay *vs = vnc_display_find(id);
3517 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3518 SocketAddress *saddr = NULL, *wsaddr = NULL;
3519 const char *share, *device_id;
3521 bool password = false;
3522 bool reverse = false;
3527 #ifdef CONFIG_VNC_SASL
3531 int lock_key_sync = 1;
3534 error_setg(errp, "VNC display not active");
3537 vnc_display_close(vs);
3542 vnc = qemu_opt_get(opts, "vnc");
3543 if (!vnc || strcmp(vnc, "none") == 0) {
3547 h = strrchr(vnc, ':');
3549 size_t hlen = h - vnc;
3551 const char *websocket = qemu_opt_get(opts, "websocket");
3552 int to = qemu_opt_get_number(opts, "to", 0);
3553 bool has_ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3554 bool has_ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3556 saddr = g_new0(SocketAddress, 1);
3558 if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3560 "SHA1 hash support is required for websockets");
3564 wsaddr = g_new0(SocketAddress, 1);
3565 vs->ws_enabled = true;
3568 if (strncmp(vnc, "unix:", 5) == 0) {
3569 saddr->type = SOCKET_ADDRESS_KIND_UNIX;
3570 saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
3571 saddr->u.q_unix->path = g_strdup(vnc + 5);
3573 if (vs->ws_enabled) {
3574 error_setg(errp, "UNIX sockets not supported with websock");
3578 unsigned long long baseport;
3579 saddr->type = SOCKET_ADDRESS_KIND_INET;
3580 saddr->u.inet = g_new0(InetSocketAddress, 1);
3581 if (vnc[0] == '[' && vnc[hlen - 1] == ']') {
3582 saddr->u.inet->host = g_strndup(vnc + 1, hlen - 2);
3584 saddr->u.inet->host = g_strndup(vnc, hlen);
3586 if (parse_uint_full(h + 1, &baseport, 10) < 0) {
3587 error_setg(errp, "can't convert to a number: %s", h + 1);
3590 if (baseport > 65535 ||
3591 baseport + 5900 > 65535) {
3592 error_setg(errp, "port %s out of range", h + 1);
3595 saddr->u.inet->port = g_strdup_printf(
3596 "%d", (int)baseport + 5900);
3599 saddr->u.inet->has_to = true;
3600 saddr->u.inet->to = to;
3601 saddr->u.inet->has_to = true;
3602 saddr->u.inet->to = to + 5900;
3604 saddr->u.inet->ipv4 = saddr->u.inet->has_ipv4 = has_ipv4;
3605 saddr->u.inet->ipv6 = saddr->u.inet->has_ipv6 = has_ipv6;
3607 if (vs->ws_enabled) {
3608 wsaddr->type = SOCKET_ADDRESS_KIND_INET;
3609 wsaddr->u.inet = g_new0(InetSocketAddress, 1);
3610 wsaddr->u.inet->host = g_strdup(saddr->u.inet->host);
3611 wsaddr->u.inet->port = g_strdup(websocket);
3614 wsaddr->u.inet->has_to = true;
3615 wsaddr->u.inet->to = to;
3617 wsaddr->u.inet->ipv4 = wsaddr->u.inet->has_ipv4 = has_ipv4;
3618 wsaddr->u.inet->ipv6 = wsaddr->u.inet->has_ipv6 = has_ipv6;
3622 error_setg(errp, "no vnc port specified");
3626 password = qemu_opt_get_bool(opts, "password", false);
3628 if (fips_get_state()) {
3630 "VNC password auth disabled due to FIPS mode, "
3631 "consider using the VeNCrypt or SASL authentication "
3632 "methods as an alternative");
3635 if (!qcrypto_cipher_supports(
3636 QCRYPTO_CIPHER_ALG_DES_RFB)) {
3638 "Cipher backend does not support DES RFB algorithm");
3643 reverse = qemu_opt_get_bool(opts, "reverse", false);
3644 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3645 sasl = qemu_opt_get_bool(opts, "sasl", false);
3646 #ifndef CONFIG_VNC_SASL
3648 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3651 #endif /* CONFIG_VNC_SASL */
3652 credid = qemu_opt_get(opts, "tls-creds");
3655 if (qemu_opt_get(opts, "tls") ||
3656 qemu_opt_get(opts, "x509") ||
3657 qemu_opt_get(opts, "x509verify")) {
3659 "'credid' parameter is mutually exclusive with "
3660 "'tls', 'x509' and 'x509verify' parameters");
3664 creds = object_resolve_path_component(
3665 object_get_objects_root(), credid);
3667 error_setg(errp, "No TLS credentials with id '%s'",
3671 vs->tlscreds = (QCryptoTLSCreds *)
3672 object_dynamic_cast(creds,
3673 TYPE_QCRYPTO_TLS_CREDS);
3674 if (!vs->tlscreds) {
3675 error_setg(errp, "Object with id '%s' is not TLS credentials",
3679 object_ref(OBJECT(vs->tlscreds));
3681 if (vs->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3683 "Expecting TLS credentials with a server endpoint");
3688 bool tls = false, x509 = false, x509verify = false;
3689 tls = qemu_opt_get_bool(opts, "tls", false);
3691 path = qemu_opt_get(opts, "x509");
3696 path = qemu_opt_get(opts, "x509verify");
3702 vs->tlscreds = vnc_display_create_creds(x509,
3707 if (!vs->tlscreds) {
3712 acl = qemu_opt_get_bool(opts, "acl", false);
3714 share = qemu_opt_get(opts, "share");
3716 if (strcmp(share, "ignore") == 0) {
3717 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
3718 } else if (strcmp(share, "allow-exclusive") == 0) {
3719 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3720 } else if (strcmp(share, "force-shared") == 0) {
3721 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3723 error_setg(errp, "unknown vnc share= option");
3727 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3729 vs->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3731 #ifdef CONFIG_VNC_JPEG
3732 vs->lossy = qemu_opt_get_bool(opts, "lossy", false);
3734 vs->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3735 /* adaptive updates are only used with tight encoding and
3736 * if lossy updates are enabled so we can disable all the
3737 * calculations otherwise */
3739 vs->non_adaptive = true;
3743 if (strcmp(vs->id, "default") == 0) {
3744 vs->tlsaclname = g_strdup("vnc.x509dname");
3746 vs->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vs->id);
3748 qemu_acl_init(vs->tlsaclname);
3750 #ifdef CONFIG_VNC_SASL
3754 if (strcmp(vs->id, "default") == 0) {
3755 aclname = g_strdup("vnc.username");
3757 aclname = g_strdup_printf("vnc.%s.username", vs->id);
3759 vs->sasl.acl = qemu_acl_init(aclname);
3764 if (vnc_display_setup_auth(vs, password, sasl, vs->ws_enabled, errp) < 0) {
3768 #ifdef CONFIG_VNC_SASL
3769 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3770 error_setg(errp, "Failed to initialize SASL auth: %s",
3771 sasl_errstring(saslErr, NULL, NULL));
3775 vs->lock_key_sync = lock_key_sync;
3777 device_id = qemu_opt_get(opts, "display");
3780 int head = qemu_opt_get_number(opts, "head", 0);
3782 dev = qdev_find_recursive(sysbus_get_default(), device_id);
3784 error_setg(errp, "Device '%s' not found", device_id);
3788 con = qemu_console_lookup_by_device(dev, head);
3790 error_setg(errp, "Device %s is not bound to a QemuConsole",
3798 if (con != vs->dcl.con) {
3799 unregister_displaychangelistener(&vs->dcl);
3801 register_displaychangelistener(&vs->dcl);
3805 /* connect to viewer */
3809 if (vs->ws_enabled) {
3810 error_setg(errp, "Cannot use websockets in reverse mode");
3813 csock = socket_connect(saddr, errp, NULL, NULL);
3817 vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
3818 vnc_connect(vs, csock, false, false);
3820 /* listen for connects */
3821 vs->lsock = socket_listen(saddr, errp);
3822 if (vs->lsock < 0) {
3825 vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
3826 if (vs->ws_enabled) {
3827 vs->lwebsock = socket_listen(wsaddr, errp);
3828 if (vs->lwebsock < 0) {
3829 if (vs->lsock != -1) {
3837 qemu_set_fd_handler(vs->lsock, vnc_listen_regular_read, NULL, vs);
3838 if (vs->ws_enabled) {
3839 qemu_set_fd_handler(vs->lwebsock, vnc_listen_websocket_read,
3844 qapi_free_SocketAddress(saddr);
3845 qapi_free_SocketAddress(wsaddr);
3849 qapi_free_SocketAddress(saddr);
3850 qapi_free_SocketAddress(wsaddr);
3851 vs->enabled = false;
3852 vs->ws_enabled = false;
3855 void vnc_display_add_client(const char *id, int csock, bool skipauth)
3857 VncDisplay *vs = vnc_display_find(id);
3862 vnc_connect(vs, csock, skipauth, false);
3865 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
3870 id = g_strdup("default");
3871 while (qemu_opts_find(olist, id)) {
3873 id = g_strdup_printf("vnc%d", i++);
3875 qemu_opts_set_id(opts, id);
3878 QemuOpts *vnc_parse(const char *str, Error **errp)
3880 QemuOptsList *olist = qemu_find_opts("vnc");
3881 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
3888 id = qemu_opts_id(opts);
3890 /* auto-assign id if not present */
3891 vnc_auto_assign_id(olist, opts);
3896 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
3898 Error *local_err = NULL;
3899 char *id = (char *)qemu_opts_id(opts);
3902 vnc_display_init(id);
3903 vnc_display_open(id, &local_err);
3904 if (local_err != NULL) {
3905 error_report("Failed to start VNC server: %s",
3906 error_get_pretty(local_err));
3907 error_free(local_err);
3913 static void vnc_register_config(void)
3915 qemu_add_opts(&qemu_vnc_opts);
3917 machine_init(vnc_register_config);