2 * QEMU VNC display driver
5 * Copyright (C) 2006 Fabrice Bellard
6 * Copyright (C) 2009 Red Hat, Inc
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 #include "qemu/osdep.h"
31 #include "hw/qdev-core.h"
32 #include "sysemu/sysemu.h"
33 #include "sysemu/runstate.h"
34 #include "qemu/error-report.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qemu/option.h"
38 #include "qemu/sockets.h"
39 #include "qemu/timer.h"
40 #include "authz/list.h"
41 #include "qemu/config-file.h"
42 #include "qapi/qapi-emit-events.h"
43 #include "qapi/qapi-events-ui.h"
44 #include "qapi/error.h"
45 #include "qapi/qapi-commands-ui.h"
47 #include "crypto/hash.h"
48 #include "crypto/tlscredsanon.h"
49 #include "crypto/tlscredsx509.h"
50 #include "crypto/random.h"
51 #include "qom/object_interfaces.h"
52 #include "qemu/cutils.h"
53 #include "qemu/help_option.h"
54 #include "io/dns-resolver.h"
56 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
57 #define VNC_REFRESH_INTERVAL_INC 50
58 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
59 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
60 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
62 #include "vnc_keysym.h"
63 #include "crypto/cipher.h"
65 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
66 QTAILQ_HEAD_INITIALIZER(vnc_displays);
68 static int vnc_cursor_define(VncState *vs);
69 static void vnc_update_throttle_offset(VncState *vs);
71 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
74 static const char *mn[] = {
76 [VNC_SHARE_MODE_CONNECTING] = "connecting",
77 [VNC_SHARE_MODE_SHARED] = "shared",
78 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
79 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
81 fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
82 vs->ioc, mn[vs->share_mode], mn[mode]);
85 switch (vs->share_mode) {
86 case VNC_SHARE_MODE_CONNECTING:
87 vs->vd->num_connecting--;
89 case VNC_SHARE_MODE_SHARED:
92 case VNC_SHARE_MODE_EXCLUSIVE:
93 vs->vd->num_exclusive--;
99 vs->share_mode = mode;
101 switch (vs->share_mode) {
102 case VNC_SHARE_MODE_CONNECTING:
103 vs->vd->num_connecting++;
105 case VNC_SHARE_MODE_SHARED:
106 vs->vd->num_shared++;
108 case VNC_SHARE_MODE_EXCLUSIVE:
109 vs->vd->num_exclusive++;
117 static void vnc_init_basic_info(SocketAddress *addr,
121 switch (addr->type) {
122 case SOCKET_ADDRESS_TYPE_INET:
123 info->host = g_strdup(addr->u.inet.host);
124 info->service = g_strdup(addr->u.inet.port);
125 if (addr->u.inet.ipv6) {
126 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
128 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
132 case SOCKET_ADDRESS_TYPE_UNIX:
133 info->host = g_strdup("");
134 info->service = g_strdup(addr->u.q_unix.path);
135 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
138 case SOCKET_ADDRESS_TYPE_VSOCK:
139 case SOCKET_ADDRESS_TYPE_FD:
140 error_setg(errp, "Unsupported socket address type %s",
141 SocketAddressType_str(addr->type));
150 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
154 SocketAddress *addr = NULL;
157 error_setg(errp, "No listener socket available");
161 addr = qio_channel_socket_get_local_address(ioc, errp);
166 vnc_init_basic_info(addr, info, errp);
167 qapi_free_SocketAddress(addr);
170 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
174 SocketAddress *addr = NULL;
176 addr = qio_channel_socket_get_remote_address(ioc, errp);
181 vnc_init_basic_info(addr, info, errp);
182 qapi_free_SocketAddress(addr);
185 static const char *vnc_auth_name(VncDisplay *vd) {
187 case VNC_AUTH_INVALID:
203 case VNC_AUTH_VENCRYPT:
204 switch (vd->subauth) {
205 case VNC_AUTH_VENCRYPT_PLAIN:
206 return "vencrypt+plain";
207 case VNC_AUTH_VENCRYPT_TLSNONE:
208 return "vencrypt+tls+none";
209 case VNC_AUTH_VENCRYPT_TLSVNC:
210 return "vencrypt+tls+vnc";
211 case VNC_AUTH_VENCRYPT_TLSPLAIN:
212 return "vencrypt+tls+plain";
213 case VNC_AUTH_VENCRYPT_X509NONE:
214 return "vencrypt+x509+none";
215 case VNC_AUTH_VENCRYPT_X509VNC:
216 return "vencrypt+x509+vnc";
217 case VNC_AUTH_VENCRYPT_X509PLAIN:
218 return "vencrypt+x509+plain";
219 case VNC_AUTH_VENCRYPT_TLSSASL:
220 return "vencrypt+tls+sasl";
221 case VNC_AUTH_VENCRYPT_X509SASL:
222 return "vencrypt+x509+sasl";
232 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
237 if (!vd->listener || !vd->listener->nsioc) {
241 info = g_malloc0(sizeof(*info));
242 vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
243 qapi_VncServerInfo_base(info), &err);
244 info->has_auth = true;
245 info->auth = g_strdup(vnc_auth_name(vd));
247 qapi_free_VncServerInfo(info);
254 static void vnc_client_cache_auth(VncState *client)
261 client->info->x509_dname =
262 qcrypto_tls_session_get_peer_name(client->tls);
263 client->info->has_x509_dname =
264 client->info->x509_dname != NULL;
266 #ifdef CONFIG_VNC_SASL
267 if (client->sasl.conn &&
268 client->sasl.username) {
269 client->info->has_sasl_username = true;
270 client->info->sasl_username = g_strdup(client->sasl.username);
275 static void vnc_client_cache_addr(VncState *client)
279 client->info = g_malloc0(sizeof(*client->info));
280 vnc_init_basic_info_from_remote_addr(client->sioc,
281 qapi_VncClientInfo_base(client->info),
283 client->info->websocket = client->websocket;
285 qapi_free_VncClientInfo(client->info);
291 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
299 si = vnc_server_info_get(vs->vd);
305 case QAPI_EVENT_VNC_CONNECTED:
306 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
308 case QAPI_EVENT_VNC_INITIALIZED:
309 qapi_event_send_vnc_initialized(si, vs->info);
311 case QAPI_EVENT_VNC_DISCONNECTED:
312 qapi_event_send_vnc_disconnected(si, vs->info);
318 qapi_free_VncServerInfo(si);
321 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
326 info = g_malloc0(sizeof(*info));
328 vnc_init_basic_info_from_remote_addr(client->sioc,
329 qapi_VncClientInfo_base(info),
333 qapi_free_VncClientInfo(info);
337 info->websocket = client->websocket;
340 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
341 info->has_x509_dname = info->x509_dname != NULL;
343 #ifdef CONFIG_VNC_SASL
344 if (client->sasl.conn && client->sasl.username) {
345 info->has_sasl_username = true;
346 info->sasl_username = g_strdup(client->sasl.username);
353 static VncDisplay *vnc_display_find(const char *id)
358 return QTAILQ_FIRST(&vnc_displays);
360 QTAILQ_FOREACH(vd, &vnc_displays, next) {
361 if (strcmp(id, vd->id) == 0) {
368 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
370 VncClientInfoList *prev = NULL;
373 QTAILQ_FOREACH(client, &vd->clients, next) {
374 QAPI_LIST_PREPEND(prev, qmp_query_vnc_client(client));
379 VncInfo *qmp_query_vnc(Error **errp)
381 VncInfo *info = g_malloc0(sizeof(*info));
382 VncDisplay *vd = vnc_display_find(NULL);
383 SocketAddress *addr = NULL;
385 if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
386 info->enabled = false;
388 info->enabled = true;
390 /* for compatibility with the original command */
391 info->has_clients = true;
392 info->clients = qmp_query_client_list(vd);
394 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
400 switch (addr->type) {
401 case SOCKET_ADDRESS_TYPE_INET:
402 info->host = g_strdup(addr->u.inet.host);
403 info->service = g_strdup(addr->u.inet.port);
404 if (addr->u.inet.ipv6) {
405 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
407 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
411 case SOCKET_ADDRESS_TYPE_UNIX:
412 info->host = g_strdup("");
413 info->service = g_strdup(addr->u.q_unix.path);
414 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
417 case SOCKET_ADDRESS_TYPE_VSOCK:
418 case SOCKET_ADDRESS_TYPE_FD:
419 error_setg(errp, "Unsupported socket address type %s",
420 SocketAddressType_str(addr->type));
426 info->has_host = true;
427 info->has_service = true;
428 info->has_family = true;
430 info->has_auth = true;
431 info->auth = g_strdup(vnc_auth_name(vd));
434 qapi_free_SocketAddress(addr);
438 qapi_free_SocketAddress(addr);
439 qapi_free_VncInfo(info);
444 static void qmp_query_auth(int auth, int subauth,
445 VncPrimaryAuth *qmp_auth,
446 VncVencryptSubAuth *qmp_vencrypt,
447 bool *qmp_has_vencrypt);
449 static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
453 VncServerInfo2List *prev)
455 VncServerInfo2 *info;
459 addr = qio_channel_socket_get_local_address(ioc, NULL);
464 info = g_new0(VncServerInfo2, 1);
465 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
466 qapi_free_SocketAddress(addr);
468 qapi_free_VncServerInfo2(info);
472 info->websocket = websocket;
474 qmp_query_auth(auth, subauth, &info->auth,
475 &info->vencrypt, &info->has_vencrypt);
477 QAPI_LIST_PREPEND(prev, info);
481 static void qmp_query_auth(int auth, int subauth,
482 VncPrimaryAuth *qmp_auth,
483 VncVencryptSubAuth *qmp_vencrypt,
484 bool *qmp_has_vencrypt)
488 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
491 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
494 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
497 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
500 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
503 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
505 case VNC_AUTH_VENCRYPT:
506 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
507 *qmp_has_vencrypt = true;
509 case VNC_AUTH_VENCRYPT_PLAIN:
510 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
512 case VNC_AUTH_VENCRYPT_TLSNONE:
513 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
515 case VNC_AUTH_VENCRYPT_TLSVNC:
516 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
518 case VNC_AUTH_VENCRYPT_TLSPLAIN:
519 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
521 case VNC_AUTH_VENCRYPT_X509NONE:
522 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
524 case VNC_AUTH_VENCRYPT_X509VNC:
525 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
527 case VNC_AUTH_VENCRYPT_X509PLAIN:
528 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
530 case VNC_AUTH_VENCRYPT_TLSSASL:
531 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
533 case VNC_AUTH_VENCRYPT_X509SASL:
534 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
537 *qmp_has_vencrypt = false;
542 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
546 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
551 VncInfo2List *qmp_query_vnc_servers(Error **errp)
553 VncInfo2List *prev = NULL;
559 QTAILQ_FOREACH(vd, &vnc_displays, next) {
560 info = g_new0(VncInfo2, 1);
561 info->id = g_strdup(vd->id);
562 info->clients = qmp_query_client_list(vd);
563 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
564 &info->vencrypt, &info->has_vencrypt);
566 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
567 "device", &error_abort));
568 info->has_display = true;
569 info->display = g_strdup(dev->id);
571 for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
572 info->server = qmp_query_server_entry(
573 vd->listener->sioc[i], false, vd->auth, vd->subauth,
576 for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
577 info->server = qmp_query_server_entry(
578 vd->wslistener->sioc[i], true, vd->ws_auth,
579 vd->ws_subauth, info->server);
582 QAPI_LIST_PREPEND(prev, info);
588 1) Get the queue working for IO.
589 2) there is some weirdness when using the -S option (the screen is grey
590 and not totally invalidated
591 3) resolutions > 1024
594 static int vnc_update_client(VncState *vs, int has_dirty);
595 static void vnc_disconnect_start(VncState *vs);
597 static void vnc_colordepth(VncState *vs);
598 static void framebuffer_update_request(VncState *vs, int incremental,
599 int x_position, int y_position,
601 static void vnc_refresh(DisplayChangeListener *dcl);
602 static int vnc_refresh_server_surface(VncDisplay *vd);
604 static int vnc_width(VncDisplay *vd)
606 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
607 VNC_DIRTY_PIXELS_PER_BIT));
610 static int vnc_height(VncDisplay *vd)
612 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
615 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
616 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
618 int x, int y, int w, int h)
620 int width = vnc_width(vd);
621 int height = vnc_height(vd);
623 /* this is needed this to ensure we updated all affected
624 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
625 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
626 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
630 w = MIN(x + w, width) - x;
631 h = MIN(y + h, height);
634 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
635 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
639 static void vnc_dpy_update(DisplayChangeListener *dcl,
640 int x, int y, int w, int h)
642 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
643 struct VncSurface *s = &vd->guest;
645 vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
648 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
651 vnc_write_u16(vs, x);
652 vnc_write_u16(vs, y);
653 vnc_write_u16(vs, w);
654 vnc_write_u16(vs, h);
656 vnc_write_s32(vs, encoding);
659 static void vnc_desktop_resize_ext(VncState *vs, int reject_reason)
662 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
664 vnc_write_u16(vs, 1); /* number of rects */
665 vnc_framebuffer_update(vs,
666 reject_reason ? 1 : 0,
668 vs->client_width, vs->client_height,
669 VNC_ENCODING_DESKTOP_RESIZE_EXT);
670 vnc_write_u8(vs, 1); /* number of screens */
671 vnc_write_u8(vs, 0); /* padding */
672 vnc_write_u8(vs, 0); /* padding */
673 vnc_write_u8(vs, 0); /* padding */
674 vnc_write_u32(vs, 0); /* screen id */
675 vnc_write_u16(vs, 0); /* screen x-pos */
676 vnc_write_u16(vs, 0); /* screen y-pos */
677 vnc_write_u16(vs, vs->client_width);
678 vnc_write_u16(vs, vs->client_height);
679 vnc_write_u32(vs, 0); /* screen flags */
680 vnc_unlock_output(vs);
684 static void vnc_desktop_resize(VncState *vs)
686 if (vs->ioc == NULL || (!vnc_has_feature(vs, VNC_FEATURE_RESIZE) &&
687 !vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT))) {
691 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
692 pixman_image_get_width(vs->vd->server) >= 0);
693 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
694 pixman_image_get_height(vs->vd->server) >= 0);
695 vs->client_width = pixman_image_get_width(vs->vd->server);
696 vs->client_height = pixman_image_get_height(vs->vd->server);
698 if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
699 vnc_desktop_resize_ext(vs, 0);
704 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
706 vnc_write_u16(vs, 1); /* number of rects */
707 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
708 VNC_ENCODING_DESKTOPRESIZE);
709 vnc_unlock_output(vs);
713 static void vnc_abort_display_jobs(VncDisplay *vd)
717 QTAILQ_FOREACH(vs, &vd->clients, next) {
720 vnc_unlock_output(vs);
722 QTAILQ_FOREACH(vs, &vd->clients, next) {
725 QTAILQ_FOREACH(vs, &vd->clients, next) {
727 if (vs->update == VNC_STATE_UPDATE_NONE &&
728 vs->job_update != VNC_STATE_UPDATE_NONE) {
729 /* job aborted before completion */
730 vs->update = vs->job_update;
731 vs->job_update = VNC_STATE_UPDATE_NONE;
734 vnc_unlock_output(vs);
738 int vnc_server_fb_stride(VncDisplay *vd)
740 return pixman_image_get_stride(vd->server);
743 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
747 ptr = (uint8_t *)pixman_image_get_data(vd->server);
748 ptr += y * vnc_server_fb_stride(vd);
749 ptr += x * VNC_SERVER_FB_BYTES;
753 static void vnc_update_server_surface(VncDisplay *vd)
757 qemu_pixman_image_unref(vd->server);
760 if (QTAILQ_EMPTY(&vd->clients)) {
764 width = vnc_width(vd);
765 height = vnc_height(vd);
766 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
770 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
771 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
775 static bool vnc_check_pageflip(DisplaySurface *s1,
778 return (s1 != NULL &&
780 surface_width(s1) == surface_width(s2) &&
781 surface_height(s1) == surface_height(s2) &&
782 surface_format(s1) == surface_format(s2));
786 static void vnc_dpy_switch(DisplayChangeListener *dcl,
787 DisplaySurface *surface)
789 static const char placeholder_msg[] =
790 "Display output is not active.";
791 static DisplaySurface *placeholder;
792 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
793 bool pageflip = vnc_check_pageflip(vd->ds, surface);
796 if (surface == NULL) {
797 if (placeholder == NULL) {
798 placeholder = qemu_create_message_surface(640, 480, placeholder_msg);
800 surface = placeholder;
803 vnc_abort_display_jobs(vd);
807 qemu_pixman_image_unref(vd->guest.fb);
808 vd->guest.fb = pixman_image_ref(surface->image);
809 vd->guest.format = surface->format;
812 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
813 surface_width(surface),
814 surface_height(surface));
819 vnc_update_server_surface(vd);
821 QTAILQ_FOREACH(vs, &vd->clients, next) {
823 vnc_desktop_resize(vs);
824 vnc_cursor_define(vs);
825 memset(vs->dirty, 0x00, sizeof(vs->dirty));
826 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
829 vnc_update_throttle_offset(vs);
834 static void vnc_write_pixels_copy(VncState *vs,
835 void *pixels, int size)
837 vnc_write(vs, pixels, size);
840 /* slowest but generic code. */
841 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
845 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
846 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
847 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
848 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
850 # error need some bits here if you change VNC_SERVER_FB_FORMAT
852 v = (r << vs->client_pf.rshift) |
853 (g << vs->client_pf.gshift) |
854 (b << vs->client_pf.bshift);
855 switch (vs->client_pf.bytes_per_pixel) {
885 static void vnc_write_pixels_generic(VncState *vs,
886 void *pixels1, int size)
890 if (VNC_SERVER_FB_BYTES == 4) {
891 uint32_t *pixels = pixels1;
894 for (i = 0; i < n; i++) {
895 vnc_convert_pixel(vs, buf, pixels[i]);
896 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
901 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
905 VncDisplay *vd = vs->vd;
907 row = vnc_server_fb_ptr(vd, x, y);
908 for (i = 0; i < h; i++) {
909 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
910 row += vnc_server_fb_stride(vd);
915 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
919 switch(vs->vnc_encoding) {
920 case VNC_ENCODING_ZLIB:
921 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
923 case VNC_ENCODING_HEXTILE:
924 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
925 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
927 case VNC_ENCODING_TIGHT:
928 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
930 case VNC_ENCODING_TIGHT_PNG:
931 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
933 case VNC_ENCODING_ZRLE:
934 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
936 case VNC_ENCODING_ZYWRLE:
937 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
940 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
941 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
947 static void vnc_mouse_set(DisplayChangeListener *dcl,
948 int x, int y, int visible)
950 /* can we ask the client(s) to move the pointer ??? */
953 static int vnc_cursor_define(VncState *vs)
955 QEMUCursor *c = vs->vd->cursor;
958 if (!vs->vd->cursor) {
962 if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
964 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
965 vnc_write_u8(vs, 0); /* padding */
966 vnc_write_u16(vs, 1); /* # of rects */
967 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
968 VNC_ENCODING_ALPHA_CURSOR);
969 vnc_write_s32(vs, VNC_ENCODING_RAW);
970 vnc_write(vs, c->data, c->width * c->height * 4);
971 vnc_unlock_output(vs);
974 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
976 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
977 vnc_write_u8(vs, 0); /* padding */
978 vnc_write_u16(vs, 1); /* # of rects */
979 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
980 VNC_ENCODING_RICH_CURSOR);
981 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
982 vnc_write_pixels_generic(vs, c->data, isize);
983 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
984 vnc_unlock_output(vs);
990 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
993 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
996 cursor_put(vd->cursor);
997 g_free(vd->cursor_mask);
1000 cursor_get(vd->cursor);
1001 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
1002 vd->cursor_mask = g_malloc0(vd->cursor_msize);
1003 cursor_get_mono_mask(c, 0, vd->cursor_mask);
1005 QTAILQ_FOREACH(vs, &vd->clients, next) {
1006 vnc_cursor_define(vs);
1010 static int find_and_clear_dirty_height(VncState *vs,
1011 int y, int last_x, int x, int height)
1015 for (h = 1; h < (height - y); h++) {
1016 if (!test_bit(last_x, vs->dirty[y + h])) {
1019 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1026 * Figure out how much pending data we should allow in the output
1027 * buffer before we throttle incremental display updates, and/or
1028 * drop audio samples.
1030 * We allow for equiv of 1 full display's worth of FB updates,
1031 * and 1 second of audio samples. If audio backlog was larger
1032 * than that the client would already suffering awful audio
1033 * glitches, so dropping samples is no worse really).
1035 static void vnc_update_throttle_offset(VncState *vs)
1038 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1040 if (vs->audio_cap) {
1042 switch (vs->as.fmt) {
1044 case AUDIO_FORMAT_U8:
1045 case AUDIO_FORMAT_S8:
1048 case AUDIO_FORMAT_U16:
1049 case AUDIO_FORMAT_S16:
1052 case AUDIO_FORMAT_U32:
1053 case AUDIO_FORMAT_S32:
1057 offset += vs->as.freq * bps * vs->as.nchannels;
1060 /* Put a floor of 1MB on offset, so that if we have a large pending
1061 * buffer and the display is resized to a small size & back again
1062 * we don't suddenly apply a tiny send limit
1064 offset = MAX(offset, 1024 * 1024);
1066 if (vs->throttle_output_offset != offset) {
1067 trace_vnc_client_throttle_threshold(
1068 vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1069 vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1072 vs->throttle_output_offset = offset;
1075 static bool vnc_should_update(VncState *vs)
1077 switch (vs->update) {
1078 case VNC_STATE_UPDATE_NONE:
1080 case VNC_STATE_UPDATE_INCREMENTAL:
1081 /* Only allow incremental updates if the pending send queue
1082 * is less than the permitted threshold, and the job worker
1083 * is completely idle.
1085 if (vs->output.offset < vs->throttle_output_offset &&
1086 vs->job_update == VNC_STATE_UPDATE_NONE) {
1089 trace_vnc_client_throttle_incremental(
1090 vs, vs->ioc, vs->job_update, vs->output.offset);
1092 case VNC_STATE_UPDATE_FORCE:
1093 /* Only allow forced updates if the pending send queue
1094 * does not contain a previous forced update, and the
1095 * job worker is completely idle.
1097 * Note this means we'll queue a forced update, even if
1098 * the output buffer size is otherwise over the throttle
1101 if (vs->force_update_offset == 0 &&
1102 vs->job_update == VNC_STATE_UPDATE_NONE) {
1105 trace_vnc_client_throttle_forced(
1106 vs, vs->ioc, vs->job_update, vs->force_update_offset);
1112 static int vnc_update_client(VncState *vs, int has_dirty)
1114 VncDisplay *vd = vs->vd;
1120 if (vs->disconnecting) {
1121 vnc_disconnect_finish(vs);
1125 vs->has_dirty += has_dirty;
1126 if (!vnc_should_update(vs)) {
1130 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1135 * Send screen updates to the vnc client using the server
1136 * surface and server dirty map. guest surface updates
1137 * happening in parallel don't disturb us, the next pass will
1138 * send them to the client.
1140 job = vnc_job_new(vs);
1142 height = pixman_image_get_height(vd->server);
1143 width = pixman_image_get_width(vd->server);
1149 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1150 height * VNC_DIRTY_BPL(vs),
1151 y * VNC_DIRTY_BPL(vs));
1152 if (offset == height * VNC_DIRTY_BPL(vs)) {
1153 /* no more dirty bits */
1156 y = offset / VNC_DIRTY_BPL(vs);
1157 x = offset % VNC_DIRTY_BPL(vs);
1158 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1159 VNC_DIRTY_BPL(vs), x);
1160 bitmap_clear(vs->dirty[y], x, x2 - x);
1161 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1162 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1164 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1165 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1167 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1175 vs->job_update = vs->update;
1176 vs->update = VNC_STATE_UPDATE_NONE;
1183 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1185 VncState *vs = opaque;
1187 assert(vs->magic == VNC_MAGIC);
1189 case AUD_CNOTIFY_DISABLE:
1190 vnc_lock_output(vs);
1191 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1192 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1193 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1194 vnc_unlock_output(vs);
1198 case AUD_CNOTIFY_ENABLE:
1199 vnc_lock_output(vs);
1200 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1201 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1202 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1203 vnc_unlock_output(vs);
1209 static void audio_capture_destroy(void *opaque)
1213 static void audio_capture(void *opaque, const void *buf, int size)
1215 VncState *vs = opaque;
1217 assert(vs->magic == VNC_MAGIC);
1218 vnc_lock_output(vs);
1219 if (vs->output.offset < vs->throttle_output_offset) {
1220 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1221 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1222 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1223 vnc_write_u32(vs, size);
1224 vnc_write(vs, buf, size);
1226 trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1228 vnc_unlock_output(vs);
1232 static void audio_add(VncState *vs)
1234 struct audio_capture_ops ops;
1236 if (vs->audio_cap) {
1237 error_report("audio already running");
1241 ops.notify = audio_capture_notify;
1242 ops.destroy = audio_capture_destroy;
1243 ops.capture = audio_capture;
1245 vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
1246 if (!vs->audio_cap) {
1247 error_report("Failed to add audio capture");
1251 static void audio_del(VncState *vs)
1253 if (vs->audio_cap) {
1254 AUD_del_capture(vs->audio_cap, vs);
1255 vs->audio_cap = NULL;
1259 static void vnc_disconnect_start(VncState *vs)
1261 if (vs->disconnecting) {
1264 trace_vnc_client_disconnect_start(vs, vs->ioc);
1265 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1267 g_source_remove(vs->ioc_tag);
1270 qio_channel_close(vs->ioc, NULL);
1271 vs->disconnecting = TRUE;
1274 void vnc_disconnect_finish(VncState *vs)
1278 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1280 vnc_jobs_join(vs); /* Wait encoding jobs */
1282 vnc_lock_output(vs);
1283 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1285 buffer_free(&vs->input);
1286 buffer_free(&vs->output);
1288 qapi_free_VncClientInfo(vs->info);
1291 vnc_tight_clear(vs);
1294 #ifdef CONFIG_VNC_SASL
1295 vnc_sasl_client_cleanup(vs);
1296 #endif /* CONFIG_VNC_SASL */
1298 qkbd_state_lift_all_keys(vs->vd->kbd);
1300 if (vs->mouse_mode_notifier.notify != NULL) {
1301 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1303 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1304 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1305 /* last client gone */
1306 vnc_update_server_surface(vs->vd);
1309 vnc_unlock_output(vs);
1311 qemu_mutex_destroy(&vs->output_mutex);
1312 if (vs->bh != NULL) {
1313 qemu_bh_delete(vs->bh);
1315 buffer_free(&vs->jobs_buffer);
1317 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1318 g_free(vs->lossy_rect[i]);
1320 g_free(vs->lossy_rect);
1322 object_unref(OBJECT(vs->ioc));
1324 object_unref(OBJECT(vs->sioc));
1332 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
1336 trace_vnc_client_eof(vs, vs->ioc);
1337 vnc_disconnect_start(vs);
1338 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1339 trace_vnc_client_io_error(vs, vs->ioc,
1340 err ? error_get_pretty(err) : "Unknown");
1341 vnc_disconnect_start(vs);
1351 void vnc_client_error(VncState *vs)
1353 VNC_DEBUG("Closing down client sock: protocol error\n");
1354 vnc_disconnect_start(vs);
1359 * Called to write a chunk of data to the client socket. The data may
1360 * be the raw data, or may have already been encoded by SASL.
1361 * The data will be written either straight onto the socket, or
1362 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1364 * NB, it is theoretically possible to have 2 layers of encryption,
1365 * both SASL, and this TLS layer. It is highly unlikely in practice
1366 * though, since SASL encryption will typically be a no-op if TLS
1369 * Returns the number of bytes written, which may be less than
1370 * the requested 'datalen' if the socket would block. Returns
1371 * 0 on I/O error, and disconnects the client socket.
1373 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1377 ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
1378 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1379 return vnc_client_io_error(vs, ret, err);
1384 * Called to write buffered data to the client socket, when not
1385 * using any SASL SSF encryption layers. Will write as much data
1386 * as possible without blocking. If all buffered data is written,
1387 * will switch the FD poll() handler back to read monitoring.
1389 * Returns the number of bytes written, which may be less than
1390 * the buffered output data if the socket would block. Returns
1391 * 0 on I/O error, and disconnects the client socket.
1393 static size_t vnc_client_write_plain(VncState *vs)
1398 #ifdef CONFIG_VNC_SASL
1399 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1400 vs->output.buffer, vs->output.capacity, vs->output.offset,
1401 vs->sasl.waitWriteSSF);
1403 if (vs->sasl.conn &&
1405 vs->sasl.waitWriteSSF) {
1406 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1408 vs->sasl.waitWriteSSF -= ret;
1410 #endif /* CONFIG_VNC_SASL */
1411 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1415 if (ret >= vs->force_update_offset) {
1416 if (vs->force_update_offset != 0) {
1417 trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1419 vs->force_update_offset = 0;
1421 vs->force_update_offset -= ret;
1423 offset = vs->output.offset;
1424 buffer_advance(&vs->output, ret);
1425 if (offset >= vs->throttle_output_offset &&
1426 vs->output.offset < vs->throttle_output_offset) {
1427 trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1430 if (vs->output.offset == 0) {
1432 g_source_remove(vs->ioc_tag);
1434 vs->ioc_tag = qio_channel_add_watch(
1435 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1436 vnc_client_io, vs, NULL);
1444 * First function called whenever there is data to be written to
1445 * the client socket. Will delegate actual work according to whether
1446 * SASL SSF layers are enabled (thus requiring encryption calls)
1448 static void vnc_client_write_locked(VncState *vs)
1450 #ifdef CONFIG_VNC_SASL
1451 if (vs->sasl.conn &&
1453 !vs->sasl.waitWriteSSF) {
1454 vnc_client_write_sasl(vs);
1456 #endif /* CONFIG_VNC_SASL */
1458 vnc_client_write_plain(vs);
1462 static void vnc_client_write(VncState *vs)
1464 assert(vs->magic == VNC_MAGIC);
1465 vnc_lock_output(vs);
1466 if (vs->output.offset) {
1467 vnc_client_write_locked(vs);
1468 } else if (vs->ioc != NULL) {
1470 g_source_remove(vs->ioc_tag);
1472 vs->ioc_tag = qio_channel_add_watch(
1473 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
1474 vnc_client_io, vs, NULL);
1476 vnc_unlock_output(vs);
1479 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1481 vs->read_handler = func;
1482 vs->read_handler_expect = expecting;
1487 * Called to read a chunk of data from the client socket. The data may
1488 * be the raw data, or may need to be further decoded by SASL.
1489 * The data will be read either straight from to the socket, or
1490 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1492 * NB, it is theoretically possible to have 2 layers of encryption,
1493 * both SASL, and this TLS layer. It is highly unlikely in practice
1494 * though, since SASL encryption will typically be a no-op if TLS
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 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1505 ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
1506 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1507 return vnc_client_io_error(vs, ret, err);
1512 * Called to read data from the client socket to the input buffer,
1513 * when not using any SASL SSF encryption layers. Will read as much
1514 * data as possible without blocking.
1516 * Returns the number of bytes read, which may be less than
1517 * the requested 'datalen' if the socket would block. Returns
1518 * 0 on I/O error or EOF, and disconnects the client socket.
1520 static size_t vnc_client_read_plain(VncState *vs)
1523 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1524 vs->input.buffer, vs->input.capacity, vs->input.offset);
1525 buffer_reserve(&vs->input, 4096);
1526 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1529 vs->input.offset += ret;
1533 static void vnc_jobs_bh(void *opaque)
1535 VncState *vs = opaque;
1537 assert(vs->magic == VNC_MAGIC);
1538 vnc_jobs_consume_buffer(vs);
1542 * First function called whenever there is more data to be read from
1543 * the client socket. Will delegate actual work according to whether
1544 * SASL SSF layers are enabled (thus requiring decryption calls)
1545 * Returns 0 on success, -1 if client disconnected
1547 static int vnc_client_read(VncState *vs)
1551 #ifdef CONFIG_VNC_SASL
1552 if (vs->sasl.conn && vs->sasl.runSSF)
1553 ret = vnc_client_read_sasl(vs);
1555 #endif /* CONFIG_VNC_SASL */
1556 ret = vnc_client_read_plain(vs);
1558 if (vs->disconnecting) {
1559 vnc_disconnect_finish(vs);
1565 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1566 size_t len = vs->read_handler_expect;
1569 ret = vs->read_handler(vs, vs->input.buffer, len);
1570 if (vs->disconnecting) {
1571 vnc_disconnect_finish(vs);
1576 buffer_advance(&vs->input, len);
1578 vs->read_handler_expect = ret;
1584 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1585 GIOCondition condition, void *opaque)
1587 VncState *vs = opaque;
1589 assert(vs->magic == VNC_MAGIC);
1591 if (condition & (G_IO_HUP | G_IO_ERR)) {
1592 vnc_disconnect_start(vs);
1596 if (condition & G_IO_IN) {
1597 if (vnc_client_read(vs) < 0) {
1598 /* vs is free()ed here */
1602 if (condition & G_IO_OUT) {
1603 vnc_client_write(vs);
1606 if (vs->disconnecting) {
1607 if (vs->ioc_tag != 0) {
1608 g_source_remove(vs->ioc_tag);
1617 * Scale factor to apply to vs->throttle_output_offset when checking for
1618 * hard limit. Worst case normal usage could be x2, if we have a complete
1619 * incremental update and complete forced update in the output buffer.
1620 * So x3 should be good enough, but we pick x5 to be conservative and thus
1621 * (hopefully) never trigger incorrectly.
1623 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1625 void vnc_write(VncState *vs, const void *data, size_t len)
1627 assert(vs->magic == VNC_MAGIC);
1628 if (vs->disconnecting) {
1631 /* Protection against malicious client/guest to prevent our output
1632 * buffer growing without bound if client stops reading data. This
1633 * should rarely trigger, because we have earlier throttling code
1634 * which stops issuing framebuffer updates and drops audio data
1635 * if the throttle_output_offset value is exceeded. So we only reach
1636 * this higher level if a huge number of pseudo-encodings get
1637 * triggered while data can't be sent on the socket.
1639 * NB throttle_output_offset can be zero during early protocol
1640 * handshake, or from the job thread's VncState clone
1642 if (vs->throttle_output_offset != 0 &&
1643 (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1644 vs->throttle_output_offset) {
1645 trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1646 vs->throttle_output_offset);
1647 vnc_disconnect_start(vs);
1650 buffer_reserve(&vs->output, len);
1652 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1654 g_source_remove(vs->ioc_tag);
1656 vs->ioc_tag = qio_channel_add_watch(
1657 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
1658 vnc_client_io, vs, NULL);
1661 buffer_append(&vs->output, data, len);
1664 void vnc_write_s32(VncState *vs, int32_t value)
1666 vnc_write_u32(vs, *(uint32_t *)&value);
1669 void vnc_write_u32(VncState *vs, uint32_t value)
1673 buf[0] = (value >> 24) & 0xFF;
1674 buf[1] = (value >> 16) & 0xFF;
1675 buf[2] = (value >> 8) & 0xFF;
1676 buf[3] = value & 0xFF;
1678 vnc_write(vs, buf, 4);
1681 void vnc_write_u16(VncState *vs, uint16_t value)
1685 buf[0] = (value >> 8) & 0xFF;
1686 buf[1] = value & 0xFF;
1688 vnc_write(vs, buf, 2);
1691 void vnc_write_u8(VncState *vs, uint8_t value)
1693 vnc_write(vs, (char *)&value, 1);
1696 void vnc_flush(VncState *vs)
1698 vnc_lock_output(vs);
1699 if (vs->ioc != NULL && vs->output.offset) {
1700 vnc_client_write_locked(vs);
1702 if (vs->disconnecting) {
1703 if (vs->ioc_tag != 0) {
1704 g_source_remove(vs->ioc_tag);
1708 vnc_unlock_output(vs);
1711 static uint8_t read_u8(uint8_t *data, size_t offset)
1713 return data[offset];
1716 static uint16_t read_u16(uint8_t *data, size_t offset)
1718 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1721 static int32_t read_s32(uint8_t *data, size_t offset)
1723 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1724 (data[offset + 2] << 8) | data[offset + 3]);
1727 uint32_t read_u32(uint8_t *data, size_t offset)
1729 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1730 (data[offset + 2] << 8) | data[offset + 3]);
1733 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1737 static void check_pointer_type_change(Notifier *notifier, void *data)
1739 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1740 int absolute = qemu_input_is_absolute();
1742 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1743 vnc_lock_output(vs);
1744 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1745 vnc_write_u8(vs, 0);
1746 vnc_write_u16(vs, 1);
1747 vnc_framebuffer_update(vs, absolute, 0,
1748 pixman_image_get_width(vs->vd->server),
1749 pixman_image_get_height(vs->vd->server),
1750 VNC_ENCODING_POINTER_TYPE_CHANGE);
1751 vnc_unlock_output(vs);
1754 vs->absolute = absolute;
1757 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1759 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1760 [INPUT_BUTTON_LEFT] = 0x01,
1761 [INPUT_BUTTON_MIDDLE] = 0x02,
1762 [INPUT_BUTTON_RIGHT] = 0x04,
1763 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1764 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1766 QemuConsole *con = vs->vd->dcl.con;
1767 int width = pixman_image_get_width(vs->vd->server);
1768 int height = pixman_image_get_height(vs->vd->server);
1770 if (vs->last_bmask != button_mask) {
1771 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1772 vs->last_bmask = button_mask;
1776 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1777 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1778 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1779 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1780 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1782 if (vs->last_x != -1) {
1783 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1784 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1789 qemu_input_event_sync();
1792 static void press_key(VncState *vs, QKeyCode qcode)
1794 qkbd_state_key_event(vs->vd->kbd, qcode, true);
1795 qkbd_state_key_event(vs->vd->kbd, qcode, false);
1798 static void vnc_led_state_change(VncState *vs)
1800 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1804 vnc_lock_output(vs);
1805 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1806 vnc_write_u8(vs, 0);
1807 vnc_write_u16(vs, 1);
1808 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1809 vnc_write_u8(vs, vs->vd->ledstate);
1810 vnc_unlock_output(vs);
1814 static void kbd_leds(void *opaque, int ledstate)
1816 VncDisplay *vd = opaque;
1819 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1820 (ledstate & QEMU_NUM_LOCK_LED),
1821 (ledstate & QEMU_SCROLL_LOCK_LED));
1823 if (ledstate == vd->ledstate) {
1827 vd->ledstate = ledstate;
1829 QTAILQ_FOREACH(client, &vd->clients, next) {
1830 vnc_led_state_change(client);
1834 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1836 QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1838 /* QEMU console switch */
1840 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1841 if (vs->vd->dcl.con == NULL && down &&
1842 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1843 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1844 /* Reset the modifiers sent to the current console */
1845 qkbd_state_lift_all_keys(vs->vd->kbd);
1846 console_select(qcode - Q_KEY_CODE_1);
1853 /* Turn off the lock state sync logic if the client support the led
1856 if (down && vs->vd->lock_key_sync &&
1857 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1858 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1859 /* If the numlock state needs to change then simulate an additional
1860 keypress before sending this one. This will happen if the user
1861 toggles numlock away from the VNC window.
1863 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1864 if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1865 trace_vnc_key_sync_numlock(true);
1866 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1869 if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1870 trace_vnc_key_sync_numlock(false);
1871 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1876 if (down && vs->vd->lock_key_sync &&
1877 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1878 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1879 /* If the capslock state needs to change then simulate an additional
1880 keypress before sending this one. This will happen if the user
1881 toggles capslock away from the VNC window.
1883 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1884 bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1885 bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1887 if (uppercase == shift) {
1888 trace_vnc_key_sync_capslock(false);
1889 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1892 if (uppercase != shift) {
1893 trace_vnc_key_sync_capslock(true);
1894 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1899 qkbd_state_key_event(vs->vd->kbd, qcode, down);
1900 if (!qemu_console_is_graphic(NULL)) {
1901 bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1902 bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1903 /* QEMU console emulation */
1906 case 0x2a: /* Left Shift */
1907 case 0x36: /* Right Shift */
1908 case 0x1d: /* Left CTRL */
1909 case 0x9d: /* Right CTRL */
1910 case 0x38: /* Left ALT */
1911 case 0xb8: /* Right ALT */
1914 kbd_put_keysym(QEMU_KEY_UP);
1917 kbd_put_keysym(QEMU_KEY_DOWN);
1920 kbd_put_keysym(QEMU_KEY_LEFT);
1923 kbd_put_keysym(QEMU_KEY_RIGHT);
1926 kbd_put_keysym(QEMU_KEY_DELETE);
1929 kbd_put_keysym(QEMU_KEY_HOME);
1932 kbd_put_keysym(QEMU_KEY_END);
1935 kbd_put_keysym(QEMU_KEY_PAGEUP);
1938 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1942 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1945 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1948 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1951 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1954 kbd_put_keysym('5');
1957 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1960 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1963 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1966 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1969 kbd_put_keysym('0');
1972 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1976 kbd_put_keysym('/');
1979 kbd_put_keysym('*');
1982 kbd_put_keysym('-');
1985 kbd_put_keysym('+');
1988 kbd_put_keysym('\n');
1993 kbd_put_keysym(sym & 0x1f);
1995 kbd_put_keysym(sym);
2003 static const char *code2name(int keycode)
2005 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
2008 static void key_event(VncState *vs, int down, uint32_t sym)
2013 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
2014 lsym = lsym - 'A' + 'a';
2017 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
2018 vs->vd->kbd, down) & SCANCODE_KEYMASK;
2019 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
2020 do_key_event(vs, down, keycode, sym);
2023 static void ext_key_event(VncState *vs, int down,
2024 uint32_t sym, uint16_t keycode)
2026 /* if the user specifies a keyboard layout, always use it */
2027 if (keyboard_layout) {
2028 key_event(vs, down, sym);
2030 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2031 do_key_event(vs, down, keycode, sym);
2035 static void framebuffer_update_request(VncState *vs, int incremental,
2036 int x, int y, int w, int h)
2039 if (vs->update != VNC_STATE_UPDATE_FORCE) {
2040 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2043 vs->update = VNC_STATE_UPDATE_FORCE;
2044 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2046 vnc_desktop_resize(vs);
2047 vnc_led_state_change(vs);
2048 vnc_cursor_define(vs);
2052 static void send_ext_key_event_ack(VncState *vs)
2054 vnc_lock_output(vs);
2055 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2056 vnc_write_u8(vs, 0);
2057 vnc_write_u16(vs, 1);
2058 vnc_framebuffer_update(vs, 0, 0,
2059 pixman_image_get_width(vs->vd->server),
2060 pixman_image_get_height(vs->vd->server),
2061 VNC_ENCODING_EXT_KEY_EVENT);
2062 vnc_unlock_output(vs);
2066 static void send_ext_audio_ack(VncState *vs)
2068 vnc_lock_output(vs);
2069 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2070 vnc_write_u8(vs, 0);
2071 vnc_write_u16(vs, 1);
2072 vnc_framebuffer_update(vs, 0, 0,
2073 pixman_image_get_width(vs->vd->server),
2074 pixman_image_get_height(vs->vd->server),
2075 VNC_ENCODING_AUDIO);
2076 vnc_unlock_output(vs);
2080 static void send_xvp_message(VncState *vs, int code)
2082 vnc_lock_output(vs);
2083 vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
2084 vnc_write_u8(vs, 0); /* pad */
2085 vnc_write_u8(vs, 1); /* version */
2086 vnc_write_u8(vs, code);
2087 vnc_unlock_output(vs);
2091 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2094 unsigned int enc = 0;
2097 vs->vnc_encoding = 0;
2098 vs->tight->compression = 9;
2099 vs->tight->quality = -1; /* Lossless by default */
2103 * Start from the end because the encodings are sent in order of preference.
2104 * This way the preferred encoding (first encoding defined in the array)
2105 * will be set at the end of the loop.
2107 for (i = n_encodings - 1; i >= 0; i--) {
2110 case VNC_ENCODING_RAW:
2111 vs->vnc_encoding = enc;
2113 case VNC_ENCODING_HEXTILE:
2114 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2115 vs->vnc_encoding = enc;
2117 case VNC_ENCODING_TIGHT:
2118 vs->features |= VNC_FEATURE_TIGHT_MASK;
2119 vs->vnc_encoding = enc;
2121 #ifdef CONFIG_VNC_PNG
2122 case VNC_ENCODING_TIGHT_PNG:
2123 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2124 vs->vnc_encoding = enc;
2127 case VNC_ENCODING_ZLIB:
2129 * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2130 * So prioritize ZRLE, even if the client hints that it prefers
2133 if ((vs->features & VNC_FEATURE_ZRLE_MASK) == 0) {
2134 vs->features |= VNC_FEATURE_ZLIB_MASK;
2135 vs->vnc_encoding = enc;
2138 case VNC_ENCODING_ZRLE:
2139 vs->features |= VNC_FEATURE_ZRLE_MASK;
2140 vs->vnc_encoding = enc;
2142 case VNC_ENCODING_ZYWRLE:
2143 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2144 vs->vnc_encoding = enc;
2146 case VNC_ENCODING_DESKTOPRESIZE:
2147 vs->features |= VNC_FEATURE_RESIZE_MASK;
2149 case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2150 vs->features |= VNC_FEATURE_RESIZE_EXT_MASK;
2152 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2153 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2155 case VNC_ENCODING_RICH_CURSOR:
2156 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2158 case VNC_ENCODING_ALPHA_CURSOR:
2159 vs->features |= VNC_FEATURE_ALPHA_CURSOR_MASK;
2161 case VNC_ENCODING_EXT_KEY_EVENT:
2162 send_ext_key_event_ack(vs);
2164 case VNC_ENCODING_AUDIO:
2165 send_ext_audio_ack(vs);
2167 case VNC_ENCODING_WMVi:
2168 vs->features |= VNC_FEATURE_WMVI_MASK;
2170 case VNC_ENCODING_LED_STATE:
2171 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2173 case VNC_ENCODING_XVP:
2174 if (vs->vd->power_control) {
2175 vs->features |= VNC_FEATURE_XVP;
2176 send_xvp_message(vs, VNC_XVP_CODE_INIT);
2179 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2180 vs->tight->compression = (enc & 0x0F);
2182 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2183 if (vs->vd->lossy) {
2184 vs->tight->quality = (enc & 0x0F);
2188 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2192 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2195 static void set_pixel_conversion(VncState *vs)
2197 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2199 if (fmt == VNC_SERVER_FB_FORMAT) {
2200 vs->write_pixels = vnc_write_pixels_copy;
2201 vnc_hextile_set_pixel_conversion(vs, 0);
2203 vs->write_pixels = vnc_write_pixels_generic;
2204 vnc_hextile_set_pixel_conversion(vs, 1);
2208 static void send_color_map(VncState *vs)
2212 vnc_lock_output(vs);
2213 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2214 vnc_write_u8(vs, 0); /* padding */
2215 vnc_write_u16(vs, 0); /* first color */
2216 vnc_write_u16(vs, 256); /* # of colors */
2218 for (i = 0; i < 256; i++) {
2219 PixelFormat *pf = &vs->client_pf;
2221 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2222 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2223 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2225 vnc_unlock_output(vs);
2228 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2229 int big_endian_flag, int true_color_flag,
2230 int red_max, int green_max, int blue_max,
2231 int red_shift, int green_shift, int blue_shift)
2233 if (!true_color_flag) {
2234 /* Expose a reasonable default 256 color map */
2244 switch (bits_per_pixel) {
2250 vnc_client_error(vs);
2254 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2255 vs->client_pf.rbits = ctpopl(red_max);
2256 vs->client_pf.rshift = red_shift;
2257 vs->client_pf.rmask = red_max << red_shift;
2258 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2259 vs->client_pf.gbits = ctpopl(green_max);
2260 vs->client_pf.gshift = green_shift;
2261 vs->client_pf.gmask = green_max << green_shift;
2262 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2263 vs->client_pf.bbits = ctpopl(blue_max);
2264 vs->client_pf.bshift = blue_shift;
2265 vs->client_pf.bmask = blue_max << blue_shift;
2266 vs->client_pf.bits_per_pixel = bits_per_pixel;
2267 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2268 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2269 vs->client_be = big_endian_flag;
2271 if (!true_color_flag) {
2275 set_pixel_conversion(vs);
2277 graphic_hw_invalidate(vs->vd->dcl.con);
2278 graphic_hw_update(vs->vd->dcl.con);
2281 static void pixel_format_message (VncState *vs) {
2282 char pad[3] = { 0, 0, 0 };
2284 vs->client_pf = qemu_default_pixelformat(32);
2286 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2287 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2289 #ifdef HOST_WORDS_BIGENDIAN
2290 vnc_write_u8(vs, 1); /* big-endian-flag */
2292 vnc_write_u8(vs, 0); /* big-endian-flag */
2294 vnc_write_u8(vs, 1); /* true-color-flag */
2295 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2296 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2297 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2298 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2299 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2300 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2301 vnc_write(vs, pad, 3); /* padding */
2303 vnc_hextile_set_pixel_conversion(vs, 0);
2304 vs->write_pixels = vnc_write_pixels_copy;
2307 static void vnc_colordepth(VncState *vs)
2309 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2310 /* Sending a WMVi message to notify the client*/
2311 vnc_lock_output(vs);
2312 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2313 vnc_write_u8(vs, 0);
2314 vnc_write_u16(vs, 1); /* number of rects */
2315 vnc_framebuffer_update(vs, 0, 0,
2316 pixman_image_get_width(vs->vd->server),
2317 pixman_image_get_height(vs->vd->server),
2319 pixel_format_message(vs);
2320 vnc_unlock_output(vs);
2323 set_pixel_conversion(vs);
2327 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2332 VncDisplay *vd = vs->vd;
2335 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2339 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2343 set_pixel_format(vs, read_u8(data, 4),
2344 read_u8(data, 6), read_u8(data, 7),
2345 read_u16(data, 8), read_u16(data, 10),
2346 read_u16(data, 12), read_u8(data, 14),
2347 read_u8(data, 15), read_u8(data, 16));
2349 case VNC_MSG_CLIENT_SET_ENCODINGS:
2354 limit = read_u16(data, 2);
2356 return 4 + (limit * 4);
2358 limit = read_u16(data, 2);
2360 for (i = 0; i < limit; i++) {
2361 int32_t val = read_s32(data, 4 + (i * 4));
2362 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2365 set_encodings(vs, (int32_t *)(data + 4), limit);
2367 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2371 framebuffer_update_request(vs,
2372 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2373 read_u16(data, 6), read_u16(data, 8));
2375 case VNC_MSG_CLIENT_KEY_EVENT:
2379 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2381 case VNC_MSG_CLIENT_POINTER_EVENT:
2385 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2387 case VNC_MSG_CLIENT_CUT_TEXT:
2392 uint32_t dlen = read_u32(data, 4);
2393 if (dlen > (1 << 20)) {
2394 error_report("vnc: client_cut_text msg payload has %u bytes"
2395 " which exceeds our limit of 1MB.", dlen);
2396 vnc_client_error(vs);
2404 client_cut_text(vs, read_u32(data, 4), data + 8);
2406 case VNC_MSG_CLIENT_XVP:
2407 if (!(vs->features & VNC_FEATURE_XVP)) {
2408 error_report("vnc: xvp client message while disabled");
2409 vnc_client_error(vs);
2416 uint8_t version = read_u8(data, 2);
2417 uint8_t action = read_u8(data, 3);
2420 error_report("vnc: xvp client message version %d != 1",
2422 vnc_client_error(vs);
2427 case VNC_XVP_ACTION_SHUTDOWN:
2428 qemu_system_powerdown_request();
2430 case VNC_XVP_ACTION_REBOOT:
2431 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2433 case VNC_XVP_ACTION_RESET:
2434 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
2437 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
2442 case VNC_MSG_CLIENT_QEMU:
2446 switch (read_u8(data, 1)) {
2447 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2451 ext_key_event(vs, read_u16(data, 2),
2452 read_u32(data, 4), read_u32(data, 8));
2454 case VNC_MSG_CLIENT_QEMU_AUDIO:
2458 switch (read_u16 (data, 2)) {
2459 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2462 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2465 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2468 switch (read_u8(data, 4)) {
2469 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
2470 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
2471 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
2472 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
2473 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
2474 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
2476 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2477 vnc_client_error(vs);
2480 vs->as.nchannels = read_u8(data, 5);
2481 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2482 VNC_DEBUG("Invalid audio channel count %d\n",
2484 vnc_client_error(vs);
2487 freq = read_u32(data, 6);
2488 /* No official limit for protocol, but 48khz is a sensible
2489 * upper bound for trustworthy clients, and this limit
2490 * protects calculations involving 'vs->as.freq' later.
2493 VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2494 vnc_client_error(vs);
2500 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2501 vnc_client_error(vs);
2507 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2508 vnc_client_error(vs);
2512 case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2521 screens = read_u8(data, 6);
2522 size = 8 + screens * 16;
2527 if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2529 memset(&info, 0, sizeof(info));
2530 info.width = read_u16(data, 2);
2531 info.height = read_u16(data, 4);
2532 dpy_set_ui_info(vs->vd->dcl.con, &info);
2533 vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2535 vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2541 VNC_DEBUG("Msg: %d\n", data[0]);
2542 vnc_client_error(vs);
2546 vnc_update_throttle_offset(vs);
2547 vnc_read_when(vs, protocol_client_msg, 1);
2551 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2557 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2558 switch (vs->vd->share_policy) {
2559 case VNC_SHARE_POLICY_IGNORE:
2561 * Ignore the shared flag. Nothing to do here.
2563 * Doesn't conform to the rfb spec but is traditional qemu
2564 * behavior, thus left here as option for compatibility
2568 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2570 * Policy: Allow clients ask for exclusive access.
2572 * Implementation: When a client asks for exclusive access,
2573 * disconnect all others. Shared connects are allowed as long
2574 * as no exclusive connection exists.
2576 * This is how the rfb spec suggests to handle the shared flag.
2578 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2580 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2584 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2585 client->share_mode != VNC_SHARE_MODE_SHARED) {
2588 vnc_disconnect_start(client);
2591 if (mode == VNC_SHARE_MODE_SHARED) {
2592 if (vs->vd->num_exclusive > 0) {
2593 vnc_disconnect_start(vs);
2598 case VNC_SHARE_POLICY_FORCE_SHARED:
2600 * Policy: Shared connects only.
2601 * Implementation: Disallow clients asking for exclusive access.
2603 * Useful for shared desktop sessions where you don't want
2604 * someone forgetting to say -shared when running the vnc
2605 * client disconnect everybody else.
2607 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2608 vnc_disconnect_start(vs);
2613 vnc_set_share_mode(vs, mode);
2615 if (vs->vd->num_shared > vs->vd->connections_limit) {
2616 vnc_disconnect_start(vs);
2620 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2621 pixman_image_get_width(vs->vd->server) >= 0);
2622 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2623 pixman_image_get_height(vs->vd->server) >= 0);
2624 vs->client_width = pixman_image_get_width(vs->vd->server);
2625 vs->client_height = pixman_image_get_height(vs->vd->server);
2626 vnc_write_u16(vs, vs->client_width);
2627 vnc_write_u16(vs, vs->client_height);
2629 pixel_format_message(vs);
2632 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2633 if (size > sizeof(buf)) {
2637 size = snprintf(buf, sizeof(buf), "QEMU");
2640 vnc_write_u32(vs, size);
2641 vnc_write(vs, buf, size);
2644 vnc_client_cache_auth(vs);
2645 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2647 vnc_read_when(vs, protocol_client_msg, 1);
2652 void start_client_init(VncState *vs)
2654 vnc_read_when(vs, protocol_client_init, 1);
2657 static void authentication_failed(VncState *vs)
2659 vnc_write_u32(vs, 1); /* Reject auth */
2660 if (vs->minor >= 8) {
2661 static const char err[] = "Authentication failed";
2662 vnc_write_u32(vs, sizeof(err));
2663 vnc_write(vs, err, sizeof(err));
2666 vnc_client_error(vs);
2669 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2671 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2673 unsigned char key[8];
2674 time_t now = time(NULL);
2675 QCryptoCipher *cipher = NULL;
2678 if (!vs->vd->password) {
2679 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2682 if (vs->vd->expires < now) {
2683 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2687 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2689 /* Calculate the expected challenge response */
2690 pwlen = strlen(vs->vd->password);
2691 for (i=0; i<sizeof(key); i++)
2692 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2694 cipher = qcrypto_cipher_new(
2695 QCRYPTO_CIPHER_ALG_DES_RFB,
2696 QCRYPTO_CIPHER_MODE_ECB,
2697 key, G_N_ELEMENTS(key),
2700 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2701 error_get_pretty(err));
2706 if (qcrypto_cipher_encrypt(cipher,
2709 VNC_AUTH_CHALLENGE_SIZE,
2711 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2712 error_get_pretty(err));
2717 /* Compare expected vs actual challenge response */
2718 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2719 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2722 trace_vnc_auth_pass(vs, vs->auth);
2723 vnc_write_u32(vs, 0); /* Accept auth */
2726 start_client_init(vs);
2729 qcrypto_cipher_free(cipher);
2733 authentication_failed(vs);
2734 qcrypto_cipher_free(cipher);
2738 void start_auth_vnc(VncState *vs)
2742 if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2743 trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2744 error_get_pretty(err));
2746 authentication_failed(vs);
2750 /* Send client a 'random' challenge */
2751 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2754 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2758 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2760 /* We only advertise 1 auth scheme at a time, so client
2761 * must pick the one we sent. Verify this */
2762 if (data[0] != vs->auth) { /* Reject auth */
2763 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2764 authentication_failed(vs);
2765 } else { /* Accept requested auth */
2766 trace_vnc_auth_start(vs, vs->auth);
2769 if (vs->minor >= 8) {
2770 vnc_write_u32(vs, 0); /* Accept auth completion */
2773 trace_vnc_auth_pass(vs, vs->auth);
2774 start_client_init(vs);
2781 case VNC_AUTH_VENCRYPT:
2782 start_auth_vencrypt(vs);
2785 #ifdef CONFIG_VNC_SASL
2787 start_auth_sasl(vs);
2789 #endif /* CONFIG_VNC_SASL */
2791 default: /* Should not be possible, but just in case */
2792 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2793 authentication_failed(vs);
2799 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2803 memcpy(local, version, 12);
2806 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2807 VNC_DEBUG("Malformed protocol version %s\n", local);
2808 vnc_client_error(vs);
2811 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2812 if (vs->major != 3 ||
2818 VNC_DEBUG("Unsupported client version\n");
2819 vnc_write_u32(vs, VNC_AUTH_INVALID);
2821 vnc_client_error(vs);
2824 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2825 * as equivalent to v3.3 by servers
2827 if (vs->minor == 4 || vs->minor == 5)
2830 if (vs->minor == 3) {
2831 trace_vnc_auth_start(vs, vs->auth);
2832 if (vs->auth == VNC_AUTH_NONE) {
2833 vnc_write_u32(vs, vs->auth);
2835 trace_vnc_auth_pass(vs, vs->auth);
2836 start_client_init(vs);
2837 } else if (vs->auth == VNC_AUTH_VNC) {
2838 VNC_DEBUG("Tell client VNC auth\n");
2839 vnc_write_u32(vs, vs->auth);
2843 trace_vnc_auth_fail(vs, vs->auth,
2844 "Unsupported auth method for v3.3", "");
2845 vnc_write_u32(vs, VNC_AUTH_INVALID);
2847 vnc_client_error(vs);
2850 vnc_write_u8(vs, 1); /* num auth */
2851 vnc_write_u8(vs, vs->auth);
2852 vnc_read_when(vs, protocol_client_auth, 1);
2859 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2861 struct VncSurface *vs = &vd->guest;
2863 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2866 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2870 w = (x + w) / VNC_STAT_RECT;
2871 h = (y + h) / VNC_STAT_RECT;
2875 for (j = y; j <= h; j++) {
2876 for (i = x; i <= w; i++) {
2877 vs->lossy_rect[j][i] = 1;
2882 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2885 int sty = y / VNC_STAT_RECT;
2886 int stx = x / VNC_STAT_RECT;
2889 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2890 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2892 QTAILQ_FOREACH(vs, &vd->clients, next) {
2895 /* kernel send buffers are full -> refresh later */
2896 if (vs->output.offset) {
2900 if (!vs->lossy_rect[sty][stx]) {
2904 vs->lossy_rect[sty][stx] = 0;
2905 for (j = 0; j < VNC_STAT_RECT; ++j) {
2906 bitmap_set(vs->dirty[y + j],
2907 x / VNC_DIRTY_PIXELS_PER_BIT,
2908 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2916 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2918 int width = MIN(pixman_image_get_width(vd->guest.fb),
2919 pixman_image_get_width(vd->server));
2920 int height = MIN(pixman_image_get_height(vd->guest.fb),
2921 pixman_image_get_height(vd->server));
2926 for (y = 0; y < height; y += VNC_STAT_RECT) {
2927 for (x = 0; x < width; x += VNC_STAT_RECT) {
2928 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2930 rect->updated = false;
2934 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2936 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2939 vd->guest.last_freq_check = *tv;
2941 for (y = 0; y < height; y += VNC_STAT_RECT) {
2942 for (x = 0; x < width; x += VNC_STAT_RECT) {
2943 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2944 int count = ARRAY_SIZE(rect->times);
2945 struct timeval min, max;
2947 if (!timerisset(&rect->times[count - 1])) {
2951 max = rect->times[(rect->idx + count - 1) % count];
2952 qemu_timersub(tv, &max, &res);
2954 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2956 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2957 memset(rect->times, 0, sizeof (rect->times));
2961 min = rect->times[rect->idx];
2962 max = rect->times[(rect->idx + count - 1) % count];
2963 qemu_timersub(&max, &min, &res);
2965 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2966 rect->freq /= count;
2967 rect->freq = 1. / rect->freq;
2973 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2979 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2980 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2982 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2983 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2984 total += vnc_stat_rect(vs->vd, i, j)->freq;
2996 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
3000 rect = vnc_stat_rect(vd, x, y);
3001 if (rect->updated) {
3004 rect->times[rect->idx] = *tv;
3005 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3006 rect->updated = true;
3009 static int vnc_refresh_server_surface(VncDisplay *vd)
3011 int width = MIN(pixman_image_get_width(vd->guest.fb),
3012 pixman_image_get_width(vd->server));
3013 int height = MIN(pixman_image_get_height(vd->guest.fb),
3014 pixman_image_get_height(vd->server));
3015 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
3016 uint8_t *guest_row0 = NULL, *server_row0;
3019 pixman_image_t *tmpbuf = NULL;
3021 struct timeval tv = { 0, 0 };
3023 if (!vd->non_adaptive) {
3024 gettimeofday(&tv, NULL);
3025 has_dirty = vnc_update_stats(vd, &tv);
3029 * Walk through the guest dirty map.
3030 * Check and copy modified bits from guest to server surface.
3031 * Update server dirty map.
3033 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3034 server_stride = guest_stride = guest_ll =
3035 pixman_image_get_stride(vd->server);
3036 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3038 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3039 int width = pixman_image_get_width(vd->server);
3040 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
3043 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
3044 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
3045 guest_stride = pixman_image_get_stride(vd->guest.fb);
3046 guest_ll = pixman_image_get_width(vd->guest.fb)
3047 * DIV_ROUND_UP(guest_bpp, 8);
3049 line_bytes = MIN(server_stride, guest_ll);
3053 uint8_t *guest_ptr, *server_ptr;
3054 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
3055 height * VNC_DIRTY_BPL(&vd->guest),
3056 y * VNC_DIRTY_BPL(&vd->guest));
3057 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
3058 /* no more dirty bits */
3061 y = offset / VNC_DIRTY_BPL(&vd->guest);
3062 x = offset % VNC_DIRTY_BPL(&vd->guest);
3064 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
3066 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3067 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
3068 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
3070 guest_ptr = guest_row0 + y * guest_stride;
3072 guest_ptr += x * cmp_bytes;
3074 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
3075 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3076 int _cmp_bytes = cmp_bytes;
3077 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
3080 if ((x + 1) * cmp_bytes > line_bytes) {
3081 _cmp_bytes = line_bytes - x * cmp_bytes;
3083 assert(_cmp_bytes >= 0);
3084 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
3087 memcpy(server_ptr, guest_ptr, _cmp_bytes);
3088 if (!vd->non_adaptive) {
3089 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
3092 QTAILQ_FOREACH(vs, &vd->clients, next) {
3093 set_bit(x, vs->dirty[y]);
3100 qemu_pixman_image_unref(tmpbuf);
3104 static void vnc_refresh(DisplayChangeListener *dcl)
3106 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
3108 int has_dirty, rects = 0;
3110 if (QTAILQ_EMPTY(&vd->clients)) {
3111 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
3115 graphic_hw_update(vd->dcl.con);
3117 if (vnc_trylock_display(vd)) {
3118 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3122 has_dirty = vnc_refresh_server_surface(vd);
3123 vnc_unlock_display(vd);
3125 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3126 rects += vnc_update_client(vs, has_dirty);
3127 /* vs might be free()ed here */
3130 if (has_dirty && rects) {
3131 vd->dcl.update_interval /= 2;
3132 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3133 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3136 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3137 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3138 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3143 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3144 bool skipauth, bool websocket)
3146 VncState *vs = g_new0(VncState, 1);
3147 bool first_client = QTAILQ_EMPTY(&vd->clients);
3150 trace_vnc_client_connect(vs, sioc);
3151 vs->zrle = g_new0(VncZrle, 1);
3152 vs->tight = g_new0(VncTight, 1);
3153 vs->magic = VNC_MAGIC;
3155 object_ref(OBJECT(vs->sioc));
3156 vs->ioc = QIO_CHANNEL(sioc);
3157 object_ref(OBJECT(vs->ioc));
3160 buffer_init(&vs->input, "vnc-input/%p", sioc);
3161 buffer_init(&vs->output, "vnc-output/%p", sioc);
3162 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
3164 buffer_init(&vs->tight->tight, "vnc-tight/%p", sioc);
3165 buffer_init(&vs->tight->zlib, "vnc-tight-zlib/%p", sioc);
3166 buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3167 #ifdef CONFIG_VNC_JPEG
3168 buffer_init(&vs->tight->jpeg, "vnc-tight-jpeg/%p", sioc);
3170 #ifdef CONFIG_VNC_PNG
3171 buffer_init(&vs->tight->png, "vnc-tight-png/%p", sioc);
3173 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
3174 buffer_init(&vs->zrle->zrle, "vnc-zrle/%p", sioc);
3175 buffer_init(&vs->zrle->fb, "vnc-zrle-fb/%p", sioc);
3176 buffer_init(&vs->zrle->zlib, "vnc-zrle-zlib/%p", sioc);
3179 vs->auth = VNC_AUTH_NONE;
3180 vs->subauth = VNC_AUTH_INVALID;
3183 vs->auth = vd->ws_auth;
3184 vs->subauth = VNC_AUTH_INVALID;
3186 vs->auth = vd->auth;
3187 vs->subauth = vd->subauth;
3190 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3191 sioc, websocket, vs->auth, vs->subauth);
3193 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3194 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3195 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3198 VNC_DEBUG("New client on socket %p\n", vs->sioc);
3199 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3200 qio_channel_set_blocking(vs->ioc, false, NULL);
3202 g_source_remove(vs->ioc_tag);
3207 vs->ioc_tag = qio_channel_add_watch(
3208 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3209 vncws_tls_handshake_io, vs, NULL);
3211 vs->ioc_tag = qio_channel_add_watch(
3212 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3213 vncws_handshake_io, vs, NULL);
3216 vs->ioc_tag = qio_channel_add_watch(
3217 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
3218 vnc_client_io, vs, NULL);
3221 vnc_client_cache_addr(vs);
3222 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3223 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3228 vs->as.freq = 44100;
3229 vs->as.nchannels = 2;
3230 vs->as.fmt = AUDIO_FORMAT_S16;
3231 vs->as.endianness = 0;
3233 qemu_mutex_init(&vs->output_mutex);
3234 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3236 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3238 vnc_update_server_surface(vd);
3241 graphic_hw_update(vd->dcl.con);
3243 if (!vs->websocket) {
3244 vnc_start_protocol(vs);
3247 if (vd->num_connecting > vd->connections_limit) {
3248 QTAILQ_FOREACH(vs, &vd->clients, next) {
3249 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3250 vnc_disconnect_start(vs);
3257 void vnc_start_protocol(VncState *vs)
3259 vnc_write(vs, "RFB 003.008\n", 12);
3261 vnc_read_when(vs, protocol_version, 12);
3263 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3264 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3267 static void vnc_listen_io(QIONetListener *listener,
3268 QIOChannelSocket *cioc,
3271 VncDisplay *vd = opaque;
3272 bool isWebsock = listener == vd->wslistener;
3274 qio_channel_set_name(QIO_CHANNEL(cioc),
3275 isWebsock ? "vnc-ws-server" : "vnc-server");
3276 qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3277 vnc_connect(vd, cioc, false, isWebsock);
3280 static const DisplayChangeListenerOps dcl_ops = {
3282 .dpy_refresh = vnc_refresh,
3283 .dpy_gfx_update = vnc_dpy_update,
3284 .dpy_gfx_switch = vnc_dpy_switch,
3285 .dpy_gfx_check_format = qemu_pixman_check_format,
3286 .dpy_mouse_set = vnc_mouse_set,
3287 .dpy_cursor_define = vnc_dpy_cursor_define,
3290 void vnc_display_init(const char *id, Error **errp)
3294 if (vnc_display_find(id) != NULL) {
3297 vd = g_malloc0(sizeof(*vd));
3299 vd->id = strdup(id);
3300 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3302 QTAILQ_INIT(&vd->clients);
3303 vd->expires = TIME_MAX;
3305 if (keyboard_layout) {
3306 trace_vnc_key_map_init(keyboard_layout);
3307 vd->kbd_layout = init_keyboard_layout(name2keysym,
3308 keyboard_layout, errp);
3310 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3313 if (!vd->kbd_layout) {
3317 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3318 vd->connections_limit = 32;
3320 qemu_mutex_init(&vd->mutex);
3321 vnc_start_worker_thread();
3323 vd->dcl.ops = &dcl_ops;
3324 register_displaychangelistener(&vd->dcl);
3325 vd->kbd = qkbd_state_init(vd->dcl.con);
3329 static void vnc_display_close(VncDisplay *vd)
3334 vd->is_unix = false;
3337 qio_net_listener_disconnect(vd->listener);
3338 object_unref(OBJECT(vd->listener));
3340 vd->listener = NULL;
3342 if (vd->wslistener) {
3343 qio_net_listener_disconnect(vd->wslistener);
3344 object_unref(OBJECT(vd->wslistener));
3346 vd->wslistener = NULL;
3348 vd->auth = VNC_AUTH_INVALID;
3349 vd->subauth = VNC_AUTH_INVALID;
3351 object_unref(OBJECT(vd->tlscreds));
3352 vd->tlscreds = NULL;
3355 object_unparent(OBJECT(vd->tlsauthz));
3356 vd->tlsauthz = NULL;
3358 g_free(vd->tlsauthzid);
3359 vd->tlsauthzid = NULL;
3360 if (vd->lock_key_sync) {
3361 qemu_remove_led_event_handler(vd->led);
3364 #ifdef CONFIG_VNC_SASL
3365 if (vd->sasl.authz) {
3366 object_unparent(OBJECT(vd->sasl.authz));
3367 vd->sasl.authz = NULL;
3369 g_free(vd->sasl.authzid);
3370 vd->sasl.authzid = NULL;
3374 int vnc_display_password(const char *id, const char *password)
3376 VncDisplay *vd = vnc_display_find(id);
3381 if (vd->auth == VNC_AUTH_NONE) {
3382 error_printf_unless_qmp("If you want use passwords please enable "
3383 "password auth using '-vnc ${dpy},password'.\n");
3387 g_free(vd->password);
3388 vd->password = g_strdup(password);
3393 int vnc_display_pw_expire(const char *id, time_t expires)
3395 VncDisplay *vd = vnc_display_find(id);
3401 vd->expires = expires;
3405 static void vnc_display_print_local_addr(VncDisplay *vd)
3407 SocketAddress *addr;
3409 if (!vd->listener || !vd->listener->nsioc) {
3413 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
3418 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3419 qapi_free_SocketAddress(addr);
3422 error_printf_unless_qmp("VNC server running on %s:%s\n",
3425 qapi_free_SocketAddress(addr);
3428 static QemuOptsList qemu_vnc_opts = {
3430 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3431 .implied_opt_name = "vnc",
3435 .type = QEMU_OPT_STRING,
3437 .name = "websocket",
3438 .type = QEMU_OPT_STRING,
3440 .name = "tls-creds",
3441 .type = QEMU_OPT_STRING,
3444 .type = QEMU_OPT_STRING,
3447 .type = QEMU_OPT_STRING,
3450 .type = QEMU_OPT_NUMBER,
3452 .name = "connections",
3453 .type = QEMU_OPT_NUMBER,
3456 .type = QEMU_OPT_NUMBER,
3459 .type = QEMU_OPT_BOOL,
3462 .type = QEMU_OPT_BOOL,
3465 .type = QEMU_OPT_BOOL,
3468 .type = QEMU_OPT_BOOL,
3470 .name = "lock-key-sync",
3471 .type = QEMU_OPT_BOOL,
3473 .name = "key-delay-ms",
3474 .type = QEMU_OPT_NUMBER,
3477 .type = QEMU_OPT_BOOL,
3480 .type = QEMU_OPT_BOOL,
3482 .name = "tls-authz",
3483 .type = QEMU_OPT_STRING,
3485 .name = "sasl-authz",
3486 .type = QEMU_OPT_STRING,
3489 .type = QEMU_OPT_BOOL,
3491 .name = "non-adaptive",
3492 .type = QEMU_OPT_BOOL,
3495 .type = QEMU_OPT_STRING,
3497 .name = "power-control",
3498 .type = QEMU_OPT_BOOL,
3500 { /* end of list */ }
3506 vnc_display_setup_auth(int *auth,
3508 QCryptoTLSCreds *tlscreds,
3515 * We have a choice of 3 authentication options
3521 * The channel can be run in 2 modes
3526 * And TLS can use 2 types of credentials
3531 * We thus have 9 possible logical combinations
3536 * 4. tls + anon + none
3537 * 5. tls + anon + vnc
3538 * 6. tls + anon + sasl
3539 * 7. tls + x509 + none
3540 * 8. tls + x509 + vnc
3541 * 9. tls + x509 + sasl
3543 * These need to be mapped into the VNC auth schemes
3544 * in an appropriate manner. In regular VNC, all the
3545 * TLS options get mapped into VNC_AUTH_VENCRYPT
3548 * In websockets, the https:// protocol already provides
3549 * TLS support, so there is no need to make use of the
3550 * VeNCrypt extension. Furthermore, websockets browser
3551 * clients could not use VeNCrypt even if they wanted to,
3552 * as they cannot control when the TLS handshake takes
3553 * place. Thus there is no option but to rely on https://,
3554 * meaning combinations 4->6 and 7->9 will be mapped to
3555 * VNC auth schemes in the same way as combos 1->3.
3557 * Regardless of fact that we have a different mapping to
3558 * VNC auth mechs for plain VNC vs websockets VNC, the end
3559 * result has the same security characteristics.
3561 if (websocket || !tlscreds) {
3563 VNC_DEBUG("Initializing VNC server with password auth\n");
3564 *auth = VNC_AUTH_VNC;
3566 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3567 *auth = VNC_AUTH_SASL;
3569 VNC_DEBUG("Initializing VNC server with no auth\n");
3570 *auth = VNC_AUTH_NONE;
3572 *subauth = VNC_AUTH_INVALID;
3574 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3575 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3576 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3577 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3579 if (!is_x509 && !is_anon) {
3581 "Unsupported TLS cred type %s",
3582 object_get_typename(OBJECT(tlscreds)));
3585 *auth = VNC_AUTH_VENCRYPT;
3588 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3589 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3591 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3592 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3597 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3598 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3600 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3601 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3605 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3606 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3608 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3609 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3617 static int vnc_display_get_address(const char *addrstr,
3626 SocketAddress **retaddr,
3630 SocketAddress *addr = NULL;
3632 addr = g_new0(SocketAddress, 1);
3634 if (strncmp(addrstr, "unix:", 5) == 0) {
3635 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3636 addr->u.q_unix.path = g_strdup(addrstr + 5);
3639 error_setg(errp, "UNIX sockets not supported with websock");
3644 error_setg(errp, "Port range not support with UNIX socket");
3651 unsigned long long baseport = 0;
3652 InetSocketAddress *inet;
3654 port = strrchr(addrstr, ':');
3660 error_setg(errp, "no vnc port specified");
3664 hostlen = port - addrstr;
3666 if (*port == '\0') {
3667 error_setg(errp, "vnc port cannot be empty");
3672 addr->type = SOCKET_ADDRESS_TYPE_INET;
3673 inet = &addr->u.inet;
3674 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3675 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3677 inet->host = g_strndup(addrstr, hostlen);
3679 /* plain VNC port is just an offset, for websocket
3680 * port is absolute */
3682 if (g_str_equal(addrstr, "") ||
3683 g_str_equal(addrstr, "on")) {
3684 if (displaynum == -1) {
3685 error_setg(errp, "explicit websocket port is required");
3688 inet->port = g_strdup_printf(
3689 "%d", displaynum + 5700);
3691 inet->has_to = true;
3692 inet->to = to + 5700;
3695 inet->port = g_strdup(port);
3698 int offset = reverse ? 0 : 5900;
3699 if (parse_uint_full(port, &baseport, 10) < 0) {
3700 error_setg(errp, "can't convert to a number: %s", port);
3703 if (baseport > 65535 ||
3704 baseport + offset > 65535) {
3705 error_setg(errp, "port %s out of range", port);
3708 inet->port = g_strdup_printf(
3709 "%d", (int)baseport + offset);
3712 inet->has_to = true;
3713 inet->to = to + offset;
3718 inet->has_ipv4 = has_ipv4;
3720 inet->has_ipv6 = has_ipv6;
3729 qapi_free_SocketAddress(addr);
3734 static void vnc_free_addresses(SocketAddress ***retsaddr,
3739 for (i = 0; i < *retnsaddr; i++) {
3740 qapi_free_SocketAddress((*retsaddr)[i]);
3748 static int vnc_display_get_addresses(QemuOpts *opts,
3750 SocketAddress ***retsaddr,
3752 SocketAddress ***retwsaddr,
3756 SocketAddress *saddr = NULL;
3757 SocketAddress *wsaddr = NULL;
3758 QemuOptsIter addriter;
3760 int to = qemu_opt_get_number(opts, "to", 0);
3761 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3762 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3763 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3764 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3765 int displaynum = -1;
3773 addr = qemu_opt_get(opts, "vnc");
3774 if (addr == NULL || g_str_equal(addr, "none")) {
3778 if (qemu_opt_get(opts, "websocket") &&
3779 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3781 "SHA1 hash support is required for websockets");
3785 qemu_opt_iter_init(&addriter, opts, "vnc");
3786 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3788 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3795 /* Historical compat - first listen address can be used
3796 * to set the default websocket port
3798 if (displaynum == -1) {
3801 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3802 (*retsaddr)[(*retnsaddr)++] = saddr;
3805 /* If we had multiple primary displays, we don't do defaults
3806 * for websocket, and require explicit config instead. */
3807 if (*retnsaddr > 1) {
3811 qemu_opt_iter_init(&addriter, opts, "websocket");
3812 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3813 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3816 &wsaddr, errp) < 0) {
3820 /* Historical compat - if only a single listen address was
3821 * provided, then this is used to set the default listen
3822 * address for websocket too
3824 if (*retnsaddr == 1 &&
3825 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3826 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3827 g_str_equal(wsaddr->u.inet.host, "") &&
3828 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3829 g_free(wsaddr->u.inet.host);
3830 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3833 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3834 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3840 vnc_free_addresses(retsaddr, retnsaddr);
3841 vnc_free_addresses(retwsaddr, retnwsaddr);
3846 static int vnc_display_connect(VncDisplay *vd,
3847 SocketAddress **saddr,
3849 SocketAddress **wsaddr,
3853 /* connect to viewer */
3854 QIOChannelSocket *sioc = NULL;
3856 error_setg(errp, "Cannot use websockets in reverse mode");
3860 error_setg(errp, "Expected a single address in reverse mode");
3863 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3864 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3865 sioc = qio_channel_socket_new();
3866 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3867 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3868 object_unref(OBJECT(sioc));
3871 vnc_connect(vd, sioc, false, false);
3872 object_unref(OBJECT(sioc));
3877 static int vnc_display_listen(VncDisplay *vd,
3878 SocketAddress **saddr,
3880 SocketAddress **wsaddr,
3887 vd->listener = qio_net_listener_new();
3888 qio_net_listener_set_name(vd->listener, "vnc-listen");
3889 for (i = 0; i < nsaddr; i++) {
3890 if (qio_net_listener_open_sync(vd->listener,
3897 qio_net_listener_set_client_func(vd->listener,
3898 vnc_listen_io, vd, NULL);
3902 vd->wslistener = qio_net_listener_new();
3903 qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3904 for (i = 0; i < nwsaddr; i++) {
3905 if (qio_net_listener_open_sync(vd->wslistener,
3912 qio_net_listener_set_client_func(vd->wslistener,
3913 vnc_listen_io, vd, NULL);
3920 void vnc_display_open(const char *id, Error **errp)
3922 VncDisplay *vd = vnc_display_find(id);
3923 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3924 SocketAddress **saddr = NULL, **wsaddr = NULL;
3925 size_t nsaddr, nwsaddr;
3926 const char *share, *device_id;
3928 bool password = false;
3929 bool reverse = false;
3933 const char *tlsauthz;
3934 const char *saslauthz;
3935 int lock_key_sync = 1;
3937 const char *audiodev;
3940 error_setg(errp, "VNC display not active");
3943 vnc_display_close(vd);
3949 reverse = qemu_opt_get_bool(opts, "reverse", false);
3950 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3951 &wsaddr, &nwsaddr, errp) < 0) {
3955 password = qemu_opt_get_bool(opts, "password", false);
3957 if (fips_get_state()) {
3959 "VNC password auth disabled due to FIPS mode, "
3960 "consider using the VeNCrypt or SASL authentication "
3961 "methods as an alternative");
3964 if (!qcrypto_cipher_supports(
3965 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3967 "Cipher backend does not support DES RFB algorithm");
3972 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3973 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3974 sasl = qemu_opt_get_bool(opts, "sasl", false);
3975 #ifndef CONFIG_VNC_SASL
3977 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3980 #endif /* CONFIG_VNC_SASL */
3981 credid = qemu_opt_get(opts, "tls-creds");
3984 creds = object_resolve_path_component(
3985 object_get_objects_root(), credid);
3987 error_setg(errp, "No TLS credentials with id '%s'",
3991 vd->tlscreds = (QCryptoTLSCreds *)
3992 object_dynamic_cast(creds,
3993 TYPE_QCRYPTO_TLS_CREDS);
3994 if (!vd->tlscreds) {
3995 error_setg(errp, "Object with id '%s' is not TLS credentials",
3999 object_ref(OBJECT(vd->tlscreds));
4001 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4003 "Expecting TLS credentials with a server endpoint");
4007 if (qemu_opt_get(opts, "acl")) {
4008 error_report("The 'acl' option to -vnc is deprecated. "
4009 "Please use the 'tls-authz' and 'sasl-authz' "
4012 acl = qemu_opt_get_bool(opts, "acl", false);
4013 tlsauthz = qemu_opt_get(opts, "tls-authz");
4014 if (acl && tlsauthz) {
4015 error_setg(errp, "'acl' option is mutually exclusive with the "
4016 "'tls-authz' option");
4019 if (tlsauthz && !vd->tlscreds) {
4020 error_setg(errp, "'tls-authz' provided but TLS is not enabled");
4024 saslauthz = qemu_opt_get(opts, "sasl-authz");
4025 if (acl && saslauthz) {
4026 error_setg(errp, "'acl' option is mutually exclusive with the "
4027 "'sasl-authz' option");
4030 if (saslauthz && !sasl) {
4031 error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
4035 share = qemu_opt_get(opts, "share");
4037 if (strcmp(share, "ignore") == 0) {
4038 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
4039 } else if (strcmp(share, "allow-exclusive") == 0) {
4040 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4041 } else if (strcmp(share, "force-shared") == 0) {
4042 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
4044 error_setg(errp, "unknown vnc share= option");
4048 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
4050 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
4052 #ifdef CONFIG_VNC_JPEG
4053 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
4055 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4056 /* adaptive updates are only used with tight encoding and
4057 * if lossy updates are enabled so we can disable all the
4058 * calculations otherwise */
4060 vd->non_adaptive = true;
4063 vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
4066 vd->tlsauthzid = g_strdup(tlsauthz);
4068 if (strcmp(vd->id, "default") == 0) {
4069 vd->tlsauthzid = g_strdup("vnc.x509dname");
4071 vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
4073 vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
4074 QAUTHZ_LIST_POLICY_DENY,
4077 #ifdef CONFIG_VNC_SASL
4080 vd->sasl.authzid = g_strdup(saslauthz);
4082 if (strcmp(vd->id, "default") == 0) {
4083 vd->sasl.authzid = g_strdup("vnc.username");
4085 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
4087 vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
4088 QAUTHZ_LIST_POLICY_DENY,
4094 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4095 vd->tlscreds, password,
4096 sasl, false, errp) < 0) {
4099 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4101 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4102 vd->tlscreds, password,
4103 sasl, true, errp) < 0) {
4106 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
4108 #ifdef CONFIG_VNC_SASL
4110 int saslErr = sasl_server_init(NULL, "qemu");
4112 if (saslErr != SASL_OK) {
4113 error_setg(errp, "Failed to initialize SASL auth: %s",
4114 sasl_errstring(saslErr, NULL, NULL));
4119 vd->lock_key_sync = lock_key_sync;
4120 if (lock_key_sync) {
4121 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4125 audiodev = qemu_opt_get(opts, "audiodev");
4127 vd->audio_state = audio_state_by_name(audiodev);
4128 if (!vd->audio_state) {
4129 error_setg(errp, "Audiodev '%s' not found", audiodev);
4134 device_id = qemu_opt_get(opts, "display");
4136 int head = qemu_opt_get_number(opts, "head", 0);
4139 con = qemu_console_lookup_by_device_name(device_id, head, &err);
4141 error_propagate(errp, err);
4148 if (con != vd->dcl.con) {
4149 qkbd_state_free(vd->kbd);
4150 unregister_displaychangelistener(&vd->dcl);
4152 register_displaychangelistener(&vd->dcl);
4153 vd->kbd = qkbd_state_init(vd->dcl.con);
4155 qkbd_state_set_delay(vd->kbd, key_delay_ms);
4157 if (saddr == NULL) {
4162 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4166 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4171 if (qemu_opt_get(opts, "to")) {
4172 vnc_display_print_local_addr(vd);
4176 vnc_free_addresses(&saddr, &nsaddr);
4177 vnc_free_addresses(&wsaddr, &nwsaddr);
4181 vnc_display_close(vd);
4185 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4187 VncDisplay *vd = vnc_display_find(id);
4188 QIOChannelSocket *sioc;
4194 sioc = qio_channel_socket_new_fd(csock, NULL);
4196 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4197 vnc_connect(vd, sioc, skipauth, false);
4198 object_unref(OBJECT(sioc));
4202 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4207 id = g_strdup("default");
4208 while (qemu_opts_find(olist, id)) {
4210 id = g_strdup_printf("vnc%d", i++);
4212 qemu_opts_set_id(opts, id);
4215 void vnc_parse(const char *str)
4217 QemuOptsList *olist = qemu_find_opts("vnc");
4218 QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
4225 id = qemu_opts_id(opts);
4227 /* auto-assign id if not present */
4228 vnc_auto_assign_id(olist, opts);
4232 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4234 Error *local_err = NULL;
4235 char *id = (char *)qemu_opts_id(opts);
4238 vnc_display_init(id, &local_err);
4240 error_propagate(errp, local_err);
4243 vnc_display_open(id, &local_err);
4244 if (local_err != NULL) {
4245 error_propagate(errp, local_err);
4251 static void vnc_register_config(void)
4253 qemu_add_opts(&qemu_vnc_opts);
4255 opts_init(vnc_register_config);