ui: fix VNC client throttling when forced update is requested
[qemu/ar7.git] / ui / vnc.c
blob4805ac41d0c96a85848951324748f96378083da7
1 /*
2 * QEMU VNC display driver
4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
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
24 * THE SOFTWARE.
27 #include "qemu/osdep.h"
28 #include "vnc.h"
29 #include "vnc-jobs.h"
30 #include "trace.h"
31 #include "sysemu/sysemu.h"
32 #include "qemu/error-report.h"
33 #include "qemu/sockets.h"
34 #include "qemu/timer.h"
35 #include "qemu/acl.h"
36 #include "qemu/config-file.h"
37 #include "qapi/qmp/qerror.h"
38 #include "qapi/qmp/types.h"
39 #include "qmp-commands.h"
40 #include "ui/input.h"
41 #include "qapi-event.h"
42 #include "crypto/hash.h"
43 #include "crypto/tlscredsanon.h"
44 #include "crypto/tlscredsx509.h"
45 #include "qom/object_interfaces.h"
46 #include "qemu/cutils.h"
47 #include "io/dns-resolver.h"
49 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
50 #define VNC_REFRESH_INTERVAL_INC 50
51 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
52 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
53 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
55 #include "vnc_keysym.h"
56 #include "crypto/cipher.h"
58 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
59 QTAILQ_HEAD_INITIALIZER(vnc_displays);
61 static int vnc_cursor_define(VncState *vs);
62 static void vnc_release_modifiers(VncState *vs);
63 static void vnc_update_throttle_offset(VncState *vs);
65 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
67 #ifdef _VNC_DEBUG
68 static const char *mn[] = {
69 [0] = "undefined",
70 [VNC_SHARE_MODE_CONNECTING] = "connecting",
71 [VNC_SHARE_MODE_SHARED] = "shared",
72 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
73 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
75 fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
76 vs->ioc, mn[vs->share_mode], mn[mode]);
77 #endif
79 switch (vs->share_mode) {
80 case VNC_SHARE_MODE_CONNECTING:
81 vs->vd->num_connecting--;
82 break;
83 case VNC_SHARE_MODE_SHARED:
84 vs->vd->num_shared--;
85 break;
86 case VNC_SHARE_MODE_EXCLUSIVE:
87 vs->vd->num_exclusive--;
88 break;
89 default:
90 break;
93 vs->share_mode = mode;
95 switch (vs->share_mode) {
96 case VNC_SHARE_MODE_CONNECTING:
97 vs->vd->num_connecting++;
98 break;
99 case VNC_SHARE_MODE_SHARED:
100 vs->vd->num_shared++;
101 break;
102 case VNC_SHARE_MODE_EXCLUSIVE:
103 vs->vd->num_exclusive++;
104 break;
105 default:
106 break;
111 static void vnc_init_basic_info(SocketAddress *addr,
112 VncBasicInfo *info,
113 Error **errp)
115 switch (addr->type) {
116 case SOCKET_ADDRESS_TYPE_INET:
117 info->host = g_strdup(addr->u.inet.host);
118 info->service = g_strdup(addr->u.inet.port);
119 if (addr->u.inet.ipv6) {
120 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
121 } else {
122 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
124 break;
126 case SOCKET_ADDRESS_TYPE_UNIX:
127 info->host = g_strdup("");
128 info->service = g_strdup(addr->u.q_unix.path);
129 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
130 break;
132 case SOCKET_ADDRESS_TYPE_VSOCK:
133 case SOCKET_ADDRESS_TYPE_FD:
134 error_setg(errp, "Unsupported socket address type %s",
135 SocketAddressType_str(addr->type));
136 break;
137 default:
138 abort();
141 return;
144 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
145 VncBasicInfo *info,
146 Error **errp)
148 SocketAddress *addr = NULL;
150 if (!ioc) {
151 error_setg(errp, "No listener socket available");
152 return;
155 addr = qio_channel_socket_get_local_address(ioc, errp);
156 if (!addr) {
157 return;
160 vnc_init_basic_info(addr, info, errp);
161 qapi_free_SocketAddress(addr);
164 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
165 VncBasicInfo *info,
166 Error **errp)
168 SocketAddress *addr = NULL;
170 addr = qio_channel_socket_get_remote_address(ioc, errp);
171 if (!addr) {
172 return;
175 vnc_init_basic_info(addr, info, errp);
176 qapi_free_SocketAddress(addr);
179 static const char *vnc_auth_name(VncDisplay *vd) {
180 switch (vd->auth) {
181 case VNC_AUTH_INVALID:
182 return "invalid";
183 case VNC_AUTH_NONE:
184 return "none";
185 case VNC_AUTH_VNC:
186 return "vnc";
187 case VNC_AUTH_RA2:
188 return "ra2";
189 case VNC_AUTH_RA2NE:
190 return "ra2ne";
191 case VNC_AUTH_TIGHT:
192 return "tight";
193 case VNC_AUTH_ULTRA:
194 return "ultra";
195 case VNC_AUTH_TLS:
196 return "tls";
197 case VNC_AUTH_VENCRYPT:
198 switch (vd->subauth) {
199 case VNC_AUTH_VENCRYPT_PLAIN:
200 return "vencrypt+plain";
201 case VNC_AUTH_VENCRYPT_TLSNONE:
202 return "vencrypt+tls+none";
203 case VNC_AUTH_VENCRYPT_TLSVNC:
204 return "vencrypt+tls+vnc";
205 case VNC_AUTH_VENCRYPT_TLSPLAIN:
206 return "vencrypt+tls+plain";
207 case VNC_AUTH_VENCRYPT_X509NONE:
208 return "vencrypt+x509+none";
209 case VNC_AUTH_VENCRYPT_X509VNC:
210 return "vencrypt+x509+vnc";
211 case VNC_AUTH_VENCRYPT_X509PLAIN:
212 return "vencrypt+x509+plain";
213 case VNC_AUTH_VENCRYPT_TLSSASL:
214 return "vencrypt+tls+sasl";
215 case VNC_AUTH_VENCRYPT_X509SASL:
216 return "vencrypt+x509+sasl";
217 default:
218 return "vencrypt";
220 case VNC_AUTH_SASL:
221 return "sasl";
223 return "unknown";
226 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
228 VncServerInfo *info;
229 Error *err = NULL;
231 if (!vd->nlsock) {
232 return NULL;
235 info = g_malloc0(sizeof(*info));
236 vnc_init_basic_info_from_server_addr(vd->lsock[0],
237 qapi_VncServerInfo_base(info), &err);
238 info->has_auth = true;
239 info->auth = g_strdup(vnc_auth_name(vd));
240 if (err) {
241 qapi_free_VncServerInfo(info);
242 info = NULL;
243 error_free(err);
245 return info;
248 static void vnc_client_cache_auth(VncState *client)
250 if (!client->info) {
251 return;
254 if (client->tls) {
255 client->info->x509_dname =
256 qcrypto_tls_session_get_peer_name(client->tls);
257 client->info->has_x509_dname =
258 client->info->x509_dname != NULL;
260 #ifdef CONFIG_VNC_SASL
261 if (client->sasl.conn &&
262 client->sasl.username) {
263 client->info->has_sasl_username = true;
264 client->info->sasl_username = g_strdup(client->sasl.username);
266 #endif
269 static void vnc_client_cache_addr(VncState *client)
271 Error *err = NULL;
273 client->info = g_malloc0(sizeof(*client->info));
274 vnc_init_basic_info_from_remote_addr(client->sioc,
275 qapi_VncClientInfo_base(client->info),
276 &err);
277 if (err) {
278 qapi_free_VncClientInfo(client->info);
279 client->info = NULL;
280 error_free(err);
284 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
286 VncServerInfo *si;
288 if (!vs->info) {
289 return;
292 si = vnc_server_info_get(vs->vd);
293 if (!si) {
294 return;
297 switch (event) {
298 case QAPI_EVENT_VNC_CONNECTED:
299 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info),
300 &error_abort);
301 break;
302 case QAPI_EVENT_VNC_INITIALIZED:
303 qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
304 break;
305 case QAPI_EVENT_VNC_DISCONNECTED:
306 qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
307 break;
308 default:
309 break;
312 qapi_free_VncServerInfo(si);
315 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
317 VncClientInfo *info;
318 Error *err = NULL;
320 info = g_malloc0(sizeof(*info));
322 vnc_init_basic_info_from_remote_addr(client->sioc,
323 qapi_VncClientInfo_base(info),
324 &err);
325 if (err) {
326 error_free(err);
327 qapi_free_VncClientInfo(info);
328 return NULL;
331 info->websocket = client->websocket;
333 if (client->tls) {
334 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
335 info->has_x509_dname = info->x509_dname != NULL;
337 #ifdef CONFIG_VNC_SASL
338 if (client->sasl.conn && client->sasl.username) {
339 info->has_sasl_username = true;
340 info->sasl_username = g_strdup(client->sasl.username);
342 #endif
344 return info;
347 static VncDisplay *vnc_display_find(const char *id)
349 VncDisplay *vd;
351 if (id == NULL) {
352 return QTAILQ_FIRST(&vnc_displays);
354 QTAILQ_FOREACH(vd, &vnc_displays, next) {
355 if (strcmp(id, vd->id) == 0) {
356 return vd;
359 return NULL;
362 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
364 VncClientInfoList *cinfo, *prev = NULL;
365 VncState *client;
367 QTAILQ_FOREACH(client, &vd->clients, next) {
368 cinfo = g_new0(VncClientInfoList, 1);
369 cinfo->value = qmp_query_vnc_client(client);
370 cinfo->next = prev;
371 prev = cinfo;
373 return prev;
376 VncInfo *qmp_query_vnc(Error **errp)
378 VncInfo *info = g_malloc0(sizeof(*info));
379 VncDisplay *vd = vnc_display_find(NULL);
380 SocketAddress *addr = NULL;
382 if (vd == NULL || !vd->nlsock) {
383 info->enabled = false;
384 } else {
385 info->enabled = true;
387 /* for compatibility with the original command */
388 info->has_clients = true;
389 info->clients = qmp_query_client_list(vd);
391 if (vd->lsock == NULL) {
392 return info;
395 addr = qio_channel_socket_get_local_address(vd->lsock[0], errp);
396 if (!addr) {
397 goto out_error;
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;
406 } else {
407 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
409 break;
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;
415 break;
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));
421 goto out_error;
422 default:
423 abort();
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);
435 return info;
437 out_error:
438 qapi_free_SocketAddress(addr);
439 qapi_free_VncInfo(info);
440 return NULL;
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,
450 bool websocket,
451 int auth,
452 int subauth,
453 VncServerInfo2List *prev)
455 VncServerInfo2List *list;
456 VncServerInfo2 *info;
457 Error *err = NULL;
458 SocketAddress *addr;
460 addr = qio_channel_socket_get_local_address(ioc, &err);
461 if (!addr) {
462 error_free(err);
463 return prev;
466 info = g_new0(VncServerInfo2, 1);
467 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
468 qapi_free_SocketAddress(addr);
469 if (err) {
470 qapi_free_VncServerInfo2(info);
471 error_free(err);
472 return prev;
474 info->websocket = websocket;
476 qmp_query_auth(auth, subauth, &info->auth,
477 &info->vencrypt, &info->has_vencrypt);
479 list = g_new0(VncServerInfo2List, 1);
480 list->value = info;
481 list->next = prev;
482 return list;
485 static void qmp_query_auth(int auth, int subauth,
486 VncPrimaryAuth *qmp_auth,
487 VncVencryptSubAuth *qmp_vencrypt,
488 bool *qmp_has_vencrypt)
490 switch (auth) {
491 case VNC_AUTH_VNC:
492 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
493 break;
494 case VNC_AUTH_RA2:
495 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
496 break;
497 case VNC_AUTH_RA2NE:
498 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
499 break;
500 case VNC_AUTH_TIGHT:
501 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
502 break;
503 case VNC_AUTH_ULTRA:
504 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
505 break;
506 case VNC_AUTH_TLS:
507 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
508 break;
509 case VNC_AUTH_VENCRYPT:
510 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
511 *qmp_has_vencrypt = true;
512 switch (subauth) {
513 case VNC_AUTH_VENCRYPT_PLAIN:
514 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
515 break;
516 case VNC_AUTH_VENCRYPT_TLSNONE:
517 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
518 break;
519 case VNC_AUTH_VENCRYPT_TLSVNC:
520 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
521 break;
522 case VNC_AUTH_VENCRYPT_TLSPLAIN:
523 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
524 break;
525 case VNC_AUTH_VENCRYPT_X509NONE:
526 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
527 break;
528 case VNC_AUTH_VENCRYPT_X509VNC:
529 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
530 break;
531 case VNC_AUTH_VENCRYPT_X509PLAIN:
532 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
533 break;
534 case VNC_AUTH_VENCRYPT_TLSSASL:
535 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
536 break;
537 case VNC_AUTH_VENCRYPT_X509SASL:
538 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
539 break;
540 default:
541 *qmp_has_vencrypt = false;
542 break;
544 break;
545 case VNC_AUTH_SASL:
546 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
547 break;
548 case VNC_AUTH_NONE:
549 default:
550 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
551 break;
555 VncInfo2List *qmp_query_vnc_servers(Error **errp)
557 VncInfo2List *item, *prev = NULL;
558 VncInfo2 *info;
559 VncDisplay *vd;
560 DeviceState *dev;
561 size_t i;
563 QTAILQ_FOREACH(vd, &vnc_displays, next) {
564 info = g_new0(VncInfo2, 1);
565 info->id = g_strdup(vd->id);
566 info->clients = qmp_query_client_list(vd);
567 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
568 &info->vencrypt, &info->has_vencrypt);
569 if (vd->dcl.con) {
570 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
571 "device", NULL));
572 info->has_display = true;
573 info->display = g_strdup(dev->id);
575 for (i = 0; i < vd->nlsock; i++) {
576 info->server = qmp_query_server_entry(
577 vd->lsock[i], false, vd->auth, vd->subauth, info->server);
579 for (i = 0; i < vd->nlwebsock; i++) {
580 info->server = qmp_query_server_entry(
581 vd->lwebsock[i], true, vd->ws_auth,
582 vd->ws_subauth, info->server);
585 item = g_new0(VncInfo2List, 1);
586 item->value = info;
587 item->next = prev;
588 prev = item;
590 return prev;
593 /* TODO
594 1) Get the queue working for IO.
595 2) there is some weirdness when using the -S option (the screen is grey
596 and not totally invalidated
597 3) resolutions > 1024
600 static int vnc_update_client(VncState *vs, int has_dirty);
601 static void vnc_disconnect_start(VncState *vs);
603 static void vnc_colordepth(VncState *vs);
604 static void framebuffer_update_request(VncState *vs, int incremental,
605 int x_position, int y_position,
606 int w, int h);
607 static void vnc_refresh(DisplayChangeListener *dcl);
608 static int vnc_refresh_server_surface(VncDisplay *vd);
610 static int vnc_width(VncDisplay *vd)
612 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
613 VNC_DIRTY_PIXELS_PER_BIT));
616 static int vnc_height(VncDisplay *vd)
618 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
621 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
622 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
623 VncDisplay *vd,
624 int x, int y, int w, int h)
626 int width = vnc_width(vd);
627 int height = vnc_height(vd);
629 /* this is needed this to ensure we updated all affected
630 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
631 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
632 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
634 x = MIN(x, width);
635 y = MIN(y, height);
636 w = MIN(x + w, width) - x;
637 h = MIN(y + h, height);
639 for (; y < h; y++) {
640 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
641 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
645 static void vnc_dpy_update(DisplayChangeListener *dcl,
646 int x, int y, int w, int h)
648 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
649 struct VncSurface *s = &vd->guest;
651 vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
654 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
655 int32_t encoding)
657 vnc_write_u16(vs, x);
658 vnc_write_u16(vs, y);
659 vnc_write_u16(vs, w);
660 vnc_write_u16(vs, h);
662 vnc_write_s32(vs, encoding);
666 static void vnc_desktop_resize(VncState *vs)
668 if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
669 return;
671 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
672 vs->client_height == pixman_image_get_height(vs->vd->server)) {
673 return;
675 vs->client_width = pixman_image_get_width(vs->vd->server);
676 vs->client_height = pixman_image_get_height(vs->vd->server);
677 vnc_lock_output(vs);
678 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
679 vnc_write_u8(vs, 0);
680 vnc_write_u16(vs, 1); /* number of rects */
681 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
682 VNC_ENCODING_DESKTOPRESIZE);
683 vnc_unlock_output(vs);
684 vnc_flush(vs);
687 static void vnc_abort_display_jobs(VncDisplay *vd)
689 VncState *vs;
691 QTAILQ_FOREACH(vs, &vd->clients, next) {
692 vnc_lock_output(vs);
693 vs->abort = true;
694 vnc_unlock_output(vs);
696 QTAILQ_FOREACH(vs, &vd->clients, next) {
697 vnc_jobs_join(vs);
699 QTAILQ_FOREACH(vs, &vd->clients, next) {
700 vnc_lock_output(vs);
701 vs->abort = false;
702 vnc_unlock_output(vs);
706 int vnc_server_fb_stride(VncDisplay *vd)
708 return pixman_image_get_stride(vd->server);
711 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
713 uint8_t *ptr;
715 ptr = (uint8_t *)pixman_image_get_data(vd->server);
716 ptr += y * vnc_server_fb_stride(vd);
717 ptr += x * VNC_SERVER_FB_BYTES;
718 return ptr;
721 static void vnc_update_server_surface(VncDisplay *vd)
723 int width, height;
725 qemu_pixman_image_unref(vd->server);
726 vd->server = NULL;
728 if (QTAILQ_EMPTY(&vd->clients)) {
729 return;
732 width = vnc_width(vd);
733 height = vnc_height(vd);
734 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
735 width, height,
736 NULL, 0);
738 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
739 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
740 width, height);
743 static void vnc_dpy_switch(DisplayChangeListener *dcl,
744 DisplaySurface *surface)
746 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
747 VncState *vs;
749 vnc_abort_display_jobs(vd);
750 vd->ds = surface;
752 /* server surface */
753 vnc_update_server_surface(vd);
755 /* guest surface */
756 qemu_pixman_image_unref(vd->guest.fb);
757 vd->guest.fb = pixman_image_ref(surface->image);
758 vd->guest.format = surface->format;
760 QTAILQ_FOREACH(vs, &vd->clients, next) {
761 vnc_colordepth(vs);
762 vnc_desktop_resize(vs);
763 if (vs->vd->cursor) {
764 vnc_cursor_define(vs);
766 memset(vs->dirty, 0x00, sizeof(vs->dirty));
767 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
768 vnc_width(vd),
769 vnc_height(vd));
770 vnc_update_throttle_offset(vs);
774 /* fastest code */
775 static void vnc_write_pixels_copy(VncState *vs,
776 void *pixels, int size)
778 vnc_write(vs, pixels, size);
781 /* slowest but generic code. */
782 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
784 uint8_t r, g, b;
786 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
787 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
788 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
789 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
790 #else
791 # error need some bits here if you change VNC_SERVER_FB_FORMAT
792 #endif
793 v = (r << vs->client_pf.rshift) |
794 (g << vs->client_pf.gshift) |
795 (b << vs->client_pf.bshift);
796 switch (vs->client_pf.bytes_per_pixel) {
797 case 1:
798 buf[0] = v;
799 break;
800 case 2:
801 if (vs->client_be) {
802 buf[0] = v >> 8;
803 buf[1] = v;
804 } else {
805 buf[1] = v >> 8;
806 buf[0] = v;
808 break;
809 default:
810 case 4:
811 if (vs->client_be) {
812 buf[0] = v >> 24;
813 buf[1] = v >> 16;
814 buf[2] = v >> 8;
815 buf[3] = v;
816 } else {
817 buf[3] = v >> 24;
818 buf[2] = v >> 16;
819 buf[1] = v >> 8;
820 buf[0] = v;
822 break;
826 static void vnc_write_pixels_generic(VncState *vs,
827 void *pixels1, int size)
829 uint8_t buf[4];
831 if (VNC_SERVER_FB_BYTES == 4) {
832 uint32_t *pixels = pixels1;
833 int n, i;
834 n = size >> 2;
835 for (i = 0; i < n; i++) {
836 vnc_convert_pixel(vs, buf, pixels[i]);
837 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
842 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
844 int i;
845 uint8_t *row;
846 VncDisplay *vd = vs->vd;
848 row = vnc_server_fb_ptr(vd, x, y);
849 for (i = 0; i < h; i++) {
850 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
851 row += vnc_server_fb_stride(vd);
853 return 1;
856 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
858 int n = 0;
859 bool encode_raw = false;
860 size_t saved_offs = vs->output.offset;
862 switch(vs->vnc_encoding) {
863 case VNC_ENCODING_ZLIB:
864 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
865 break;
866 case VNC_ENCODING_HEXTILE:
867 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
868 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
869 break;
870 case VNC_ENCODING_TIGHT:
871 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
872 break;
873 case VNC_ENCODING_TIGHT_PNG:
874 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
875 break;
876 case VNC_ENCODING_ZRLE:
877 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
878 break;
879 case VNC_ENCODING_ZYWRLE:
880 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
881 break;
882 default:
883 encode_raw = true;
884 break;
887 /* If the client has the same pixel format as our internal buffer and
888 * a RAW encoding would need less space fall back to RAW encoding to
889 * save bandwidth and processing power in the client. */
890 if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
891 12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
892 vs->output.offset = saved_offs;
893 encode_raw = true;
896 if (encode_raw) {
897 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
898 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
901 return n;
904 static void vnc_mouse_set(DisplayChangeListener *dcl,
905 int x, int y, int visible)
907 /* can we ask the client(s) to move the pointer ??? */
910 static int vnc_cursor_define(VncState *vs)
912 QEMUCursor *c = vs->vd->cursor;
913 int isize;
915 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
916 vnc_lock_output(vs);
917 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
918 vnc_write_u8(vs, 0); /* padding */
919 vnc_write_u16(vs, 1); /* # of rects */
920 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
921 VNC_ENCODING_RICH_CURSOR);
922 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
923 vnc_write_pixels_generic(vs, c->data, isize);
924 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
925 vnc_unlock_output(vs);
926 return 0;
928 return -1;
931 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
932 QEMUCursor *c)
934 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
935 VncState *vs;
937 cursor_put(vd->cursor);
938 g_free(vd->cursor_mask);
940 vd->cursor = c;
941 cursor_get(vd->cursor);
942 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
943 vd->cursor_mask = g_malloc0(vd->cursor_msize);
944 cursor_get_mono_mask(c, 0, vd->cursor_mask);
946 QTAILQ_FOREACH(vs, &vd->clients, next) {
947 vnc_cursor_define(vs);
951 static int find_and_clear_dirty_height(VncState *vs,
952 int y, int last_x, int x, int height)
954 int h;
956 for (h = 1; h < (height - y); h++) {
957 if (!test_bit(last_x, vs->dirty[y + h])) {
958 break;
960 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
963 return h;
967 * Figure out how much pending data we should allow in the output
968 * buffer before we throttle incremental display updates, and/or
969 * drop audio samples.
971 * We allow for equiv of 1 full display's worth of FB updates,
972 * and 1 second of audio samples. If audio backlog was larger
973 * than that the client would already suffering awful audio
974 * glitches, so dropping samples is no worse really).
976 static void vnc_update_throttle_offset(VncState *vs)
978 size_t offset =
979 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
981 if (vs->audio_cap) {
982 int freq = vs->as.freq;
983 /* We don't limit freq when reading settings from client, so
984 * it could be upto MAX_INT in size. 48khz is a sensible
985 * upper bound for trustworthy clients */
986 int bps;
987 if (freq > 48000) {
988 freq = 48000;
990 switch (vs->as.fmt) {
991 default:
992 case AUD_FMT_U8:
993 case AUD_FMT_S8:
994 bps = 1;
995 break;
996 case AUD_FMT_U16:
997 case AUD_FMT_S16:
998 bps = 2;
999 break;
1000 case AUD_FMT_U32:
1001 case AUD_FMT_S32:
1002 bps = 4;
1003 break;
1005 offset += freq * bps * vs->as.nchannels;
1008 /* Put a floor of 1MB on offset, so that if we have a large pending
1009 * buffer and the display is resized to a small size & back again
1010 * we don't suddenly apply a tiny send limit
1012 offset = MAX(offset, 1024 * 1024);
1014 vs->throttle_output_offset = offset;
1017 static bool vnc_should_update(VncState *vs)
1019 switch (vs->update) {
1020 case VNC_STATE_UPDATE_NONE:
1021 break;
1022 case VNC_STATE_UPDATE_INCREMENTAL:
1023 /* Only allow incremental updates if the pending send queue
1024 * is less than the permitted threshold, and the job worker
1025 * is completely idle.
1027 if (vs->output.offset < vs->throttle_output_offset &&
1028 vs->job_update == VNC_STATE_UPDATE_NONE) {
1029 return true;
1031 break;
1032 case VNC_STATE_UPDATE_FORCE:
1033 /* Only allow forced updates if the pending send queue
1034 * does not contain a previous forced update, and the
1035 * job worker is completely idle.
1037 * Note this means we'll queue a forced update, even if
1038 * the output buffer size is otherwise over the throttle
1039 * output limit.
1041 if (vs->force_update_offset == 0 &&
1042 vs->job_update == VNC_STATE_UPDATE_NONE) {
1043 return true;
1045 break;
1047 return false;
1050 static int vnc_update_client(VncState *vs, int has_dirty)
1052 VncDisplay *vd = vs->vd;
1053 VncJob *job;
1054 int y;
1055 int height, width;
1056 int n = 0;
1058 if (vs->disconnecting) {
1059 vnc_disconnect_finish(vs);
1060 return 0;
1063 vs->has_dirty += has_dirty;
1064 if (!vnc_should_update(vs)) {
1065 return 0;
1068 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1069 return 0;
1073 * Send screen updates to the vnc client using the server
1074 * surface and server dirty map. guest surface updates
1075 * happening in parallel don't disturb us, the next pass will
1076 * send them to the client.
1078 job = vnc_job_new(vs);
1080 height = pixman_image_get_height(vd->server);
1081 width = pixman_image_get_width(vd->server);
1083 y = 0;
1084 for (;;) {
1085 int x, h;
1086 unsigned long x2;
1087 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1088 height * VNC_DIRTY_BPL(vs),
1089 y * VNC_DIRTY_BPL(vs));
1090 if (offset == height * VNC_DIRTY_BPL(vs)) {
1091 /* no more dirty bits */
1092 break;
1094 y = offset / VNC_DIRTY_BPL(vs);
1095 x = offset % VNC_DIRTY_BPL(vs);
1096 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1097 VNC_DIRTY_BPL(vs), x);
1098 bitmap_clear(vs->dirty[y], x, x2 - x);
1099 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1100 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1101 if (x2 > x) {
1102 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1103 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1105 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1106 y += h;
1107 if (y == height) {
1108 break;
1113 vs->job_update = vs->update;
1114 vs->update = VNC_STATE_UPDATE_NONE;
1115 vnc_job_push(job);
1116 vs->has_dirty = 0;
1117 return n;
1120 /* audio */
1121 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1123 VncState *vs = opaque;
1125 switch (cmd) {
1126 case AUD_CNOTIFY_DISABLE:
1127 vnc_lock_output(vs);
1128 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1129 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1130 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1131 vnc_unlock_output(vs);
1132 vnc_flush(vs);
1133 break;
1135 case AUD_CNOTIFY_ENABLE:
1136 vnc_lock_output(vs);
1137 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1138 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1139 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1140 vnc_unlock_output(vs);
1141 vnc_flush(vs);
1142 break;
1146 static void audio_capture_destroy(void *opaque)
1150 static void audio_capture(void *opaque, void *buf, int size)
1152 VncState *vs = opaque;
1154 vnc_lock_output(vs);
1155 if (vs->output.offset < vs->throttle_output_offset) {
1156 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1157 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1158 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1159 vnc_write_u32(vs, size);
1160 vnc_write(vs, buf, size);
1162 vnc_unlock_output(vs);
1163 vnc_flush(vs);
1166 static void audio_add(VncState *vs)
1168 struct audio_capture_ops ops;
1170 if (vs->audio_cap) {
1171 error_report("audio already running");
1172 return;
1175 ops.notify = audio_capture_notify;
1176 ops.destroy = audio_capture_destroy;
1177 ops.capture = audio_capture;
1179 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1180 if (!vs->audio_cap) {
1181 error_report("Failed to add audio capture");
1185 static void audio_del(VncState *vs)
1187 if (vs->audio_cap) {
1188 AUD_del_capture(vs->audio_cap, vs);
1189 vs->audio_cap = NULL;
1193 static void vnc_disconnect_start(VncState *vs)
1195 if (vs->disconnecting) {
1196 return;
1198 trace_vnc_client_disconnect_start(vs, vs->ioc);
1199 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1200 if (vs->ioc_tag) {
1201 g_source_remove(vs->ioc_tag);
1202 vs->ioc_tag = 0;
1204 qio_channel_close(vs->ioc, NULL);
1205 vs->disconnecting = TRUE;
1208 void vnc_disconnect_finish(VncState *vs)
1210 int i;
1212 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1214 vnc_jobs_join(vs); /* Wait encoding jobs */
1216 vnc_lock_output(vs);
1217 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1219 buffer_free(&vs->input);
1220 buffer_free(&vs->output);
1222 qapi_free_VncClientInfo(vs->info);
1224 vnc_zlib_clear(vs);
1225 vnc_tight_clear(vs);
1226 vnc_zrle_clear(vs);
1228 #ifdef CONFIG_VNC_SASL
1229 vnc_sasl_client_cleanup(vs);
1230 #endif /* CONFIG_VNC_SASL */
1231 audio_del(vs);
1232 vnc_release_modifiers(vs);
1234 if (vs->mouse_mode_notifier.notify != NULL) {
1235 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1237 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1238 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1239 /* last client gone */
1240 vnc_update_server_surface(vs->vd);
1243 vnc_unlock_output(vs);
1245 qemu_mutex_destroy(&vs->output_mutex);
1246 if (vs->bh != NULL) {
1247 qemu_bh_delete(vs->bh);
1249 buffer_free(&vs->jobs_buffer);
1251 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1252 g_free(vs->lossy_rect[i]);
1254 g_free(vs->lossy_rect);
1256 object_unref(OBJECT(vs->ioc));
1257 vs->ioc = NULL;
1258 object_unref(OBJECT(vs->sioc));
1259 vs->sioc = NULL;
1260 g_free(vs);
1263 ssize_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
1265 if (ret <= 0) {
1266 if (ret == 0) {
1267 trace_vnc_client_eof(vs, vs->ioc);
1268 vnc_disconnect_start(vs);
1269 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1270 trace_vnc_client_io_error(vs, vs->ioc,
1271 errp ? error_get_pretty(*errp) :
1272 "Unknown");
1273 vnc_disconnect_start(vs);
1276 if (errp) {
1277 error_free(*errp);
1278 *errp = NULL;
1280 return 0;
1282 return ret;
1286 void vnc_client_error(VncState *vs)
1288 VNC_DEBUG("Closing down client sock: protocol error\n");
1289 vnc_disconnect_start(vs);
1294 * Called to write a chunk of data to the client socket. The data may
1295 * be the raw data, or may have already been encoded by SASL.
1296 * The data will be written either straight onto the socket, or
1297 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1299 * NB, it is theoretically possible to have 2 layers of encryption,
1300 * both SASL, and this TLS layer. It is highly unlikely in practice
1301 * though, since SASL encryption will typically be a no-op if TLS
1302 * is active
1304 * Returns the number of bytes written, which may be less than
1305 * the requested 'datalen' if the socket would block. Returns
1306 * -1 on error, and disconnects the client socket.
1308 ssize_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1310 Error *err = NULL;
1311 ssize_t ret;
1312 ret = qio_channel_write(
1313 vs->ioc, (const char *)data, datalen, &err);
1314 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1315 return vnc_client_io_error(vs, ret, &err);
1320 * Called to write buffered data to the client socket, when not
1321 * using any SASL SSF encryption layers. Will write as much data
1322 * as possible without blocking. If all buffered data is written,
1323 * will switch the FD poll() handler back to read monitoring.
1325 * Returns the number of bytes written, which may be less than
1326 * the buffered output data if the socket would block. Returns
1327 * -1 on error, and disconnects the client socket.
1329 static ssize_t vnc_client_write_plain(VncState *vs)
1331 ssize_t ret;
1333 #ifdef CONFIG_VNC_SASL
1334 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1335 vs->output.buffer, vs->output.capacity, vs->output.offset,
1336 vs->sasl.waitWriteSSF);
1338 if (vs->sasl.conn &&
1339 vs->sasl.runSSF &&
1340 vs->sasl.waitWriteSSF) {
1341 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1342 if (ret)
1343 vs->sasl.waitWriteSSF -= ret;
1344 } else
1345 #endif /* CONFIG_VNC_SASL */
1346 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1347 if (!ret)
1348 return 0;
1350 if (ret >= vs->force_update_offset) {
1351 vs->force_update_offset = 0;
1352 } else {
1353 vs->force_update_offset -= ret;
1355 buffer_advance(&vs->output, ret);
1357 if (vs->output.offset == 0) {
1358 if (vs->ioc_tag) {
1359 g_source_remove(vs->ioc_tag);
1361 vs->ioc_tag = qio_channel_add_watch(
1362 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1365 return ret;
1370 * First function called whenever there is data to be written to
1371 * the client socket. Will delegate actual work according to whether
1372 * SASL SSF layers are enabled (thus requiring encryption calls)
1374 static void vnc_client_write_locked(VncState *vs)
1376 #ifdef CONFIG_VNC_SASL
1377 if (vs->sasl.conn &&
1378 vs->sasl.runSSF &&
1379 !vs->sasl.waitWriteSSF) {
1380 vnc_client_write_sasl(vs);
1381 } else
1382 #endif /* CONFIG_VNC_SASL */
1384 vnc_client_write_plain(vs);
1388 static void vnc_client_write(VncState *vs)
1391 vnc_lock_output(vs);
1392 if (vs->output.offset) {
1393 vnc_client_write_locked(vs);
1394 } else if (vs->ioc != NULL) {
1395 if (vs->ioc_tag) {
1396 g_source_remove(vs->ioc_tag);
1398 vs->ioc_tag = qio_channel_add_watch(
1399 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1401 vnc_unlock_output(vs);
1404 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1406 vs->read_handler = func;
1407 vs->read_handler_expect = expecting;
1412 * Called to read a chunk of data from the client socket. The data may
1413 * be the raw data, or may need to be further decoded by SASL.
1414 * The data will be read either straight from to the socket, or
1415 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1417 * NB, it is theoretically possible to have 2 layers of encryption,
1418 * both SASL, and this TLS layer. It is highly unlikely in practice
1419 * though, since SASL encryption will typically be a no-op if TLS
1420 * is active
1422 * Returns the number of bytes read, which may be less than
1423 * the requested 'datalen' if the socket would block. Returns
1424 * -1 on error, and disconnects the client socket.
1426 ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1428 ssize_t ret;
1429 Error *err = NULL;
1430 ret = qio_channel_read(
1431 vs->ioc, (char *)data, datalen, &err);
1432 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1433 return vnc_client_io_error(vs, ret, &err);
1438 * Called to read data from the client socket to the input buffer,
1439 * when not using any SASL SSF encryption layers. Will read as much
1440 * data as possible without blocking.
1442 * Returns the number of bytes read. Returns -1 on error, and
1443 * disconnects the client socket.
1445 static ssize_t vnc_client_read_plain(VncState *vs)
1447 ssize_t ret;
1448 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1449 vs->input.buffer, vs->input.capacity, vs->input.offset);
1450 buffer_reserve(&vs->input, 4096);
1451 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1452 if (!ret)
1453 return 0;
1454 vs->input.offset += ret;
1455 return ret;
1458 static void vnc_jobs_bh(void *opaque)
1460 VncState *vs = opaque;
1462 vnc_jobs_consume_buffer(vs);
1466 * First function called whenever there is more data to be read from
1467 * the client socket. Will delegate actual work according to whether
1468 * SASL SSF layers are enabled (thus requiring decryption calls)
1469 * Returns 0 on success, -1 if client disconnected
1471 static int vnc_client_read(VncState *vs)
1473 ssize_t ret;
1475 #ifdef CONFIG_VNC_SASL
1476 if (vs->sasl.conn && vs->sasl.runSSF)
1477 ret = vnc_client_read_sasl(vs);
1478 else
1479 #endif /* CONFIG_VNC_SASL */
1480 ret = vnc_client_read_plain(vs);
1481 if (!ret) {
1482 if (vs->disconnecting) {
1483 vnc_disconnect_finish(vs);
1484 return -1;
1486 return 0;
1489 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1490 size_t len = vs->read_handler_expect;
1491 int ret;
1493 ret = vs->read_handler(vs, vs->input.buffer, len);
1494 if (vs->disconnecting) {
1495 vnc_disconnect_finish(vs);
1496 return -1;
1499 if (!ret) {
1500 buffer_advance(&vs->input, len);
1501 } else {
1502 vs->read_handler_expect = ret;
1505 return 0;
1508 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1509 GIOCondition condition, void *opaque)
1511 VncState *vs = opaque;
1512 if (condition & G_IO_IN) {
1513 if (vnc_client_read(vs) < 0) {
1514 return TRUE;
1517 if (condition & G_IO_OUT) {
1518 vnc_client_write(vs);
1520 return TRUE;
1524 void vnc_write(VncState *vs, const void *data, size_t len)
1526 buffer_reserve(&vs->output, len);
1528 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1529 if (vs->ioc_tag) {
1530 g_source_remove(vs->ioc_tag);
1532 vs->ioc_tag = qio_channel_add_watch(
1533 vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1536 buffer_append(&vs->output, data, len);
1539 void vnc_write_s32(VncState *vs, int32_t value)
1541 vnc_write_u32(vs, *(uint32_t *)&value);
1544 void vnc_write_u32(VncState *vs, uint32_t value)
1546 uint8_t buf[4];
1548 buf[0] = (value >> 24) & 0xFF;
1549 buf[1] = (value >> 16) & 0xFF;
1550 buf[2] = (value >> 8) & 0xFF;
1551 buf[3] = value & 0xFF;
1553 vnc_write(vs, buf, 4);
1556 void vnc_write_u16(VncState *vs, uint16_t value)
1558 uint8_t buf[2];
1560 buf[0] = (value >> 8) & 0xFF;
1561 buf[1] = value & 0xFF;
1563 vnc_write(vs, buf, 2);
1566 void vnc_write_u8(VncState *vs, uint8_t value)
1568 vnc_write(vs, (char *)&value, 1);
1571 void vnc_flush(VncState *vs)
1573 vnc_lock_output(vs);
1574 if (vs->ioc != NULL && vs->output.offset) {
1575 vnc_client_write_locked(vs);
1577 vnc_unlock_output(vs);
1580 static uint8_t read_u8(uint8_t *data, size_t offset)
1582 return data[offset];
1585 static uint16_t read_u16(uint8_t *data, size_t offset)
1587 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1590 static int32_t read_s32(uint8_t *data, size_t offset)
1592 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1593 (data[offset + 2] << 8) | data[offset + 3]);
1596 uint32_t read_u32(uint8_t *data, size_t offset)
1598 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1599 (data[offset + 2] << 8) | data[offset + 3]);
1602 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1606 static void check_pointer_type_change(Notifier *notifier, void *data)
1608 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1609 int absolute = qemu_input_is_absolute();
1611 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1612 vnc_lock_output(vs);
1613 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1614 vnc_write_u8(vs, 0);
1615 vnc_write_u16(vs, 1);
1616 vnc_framebuffer_update(vs, absolute, 0,
1617 pixman_image_get_width(vs->vd->server),
1618 pixman_image_get_height(vs->vd->server),
1619 VNC_ENCODING_POINTER_TYPE_CHANGE);
1620 vnc_unlock_output(vs);
1621 vnc_flush(vs);
1623 vs->absolute = absolute;
1626 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1628 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1629 [INPUT_BUTTON_LEFT] = 0x01,
1630 [INPUT_BUTTON_MIDDLE] = 0x02,
1631 [INPUT_BUTTON_RIGHT] = 0x04,
1632 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1633 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1635 QemuConsole *con = vs->vd->dcl.con;
1636 int width = pixman_image_get_width(vs->vd->server);
1637 int height = pixman_image_get_height(vs->vd->server);
1639 if (vs->last_bmask != button_mask) {
1640 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1641 vs->last_bmask = button_mask;
1644 if (vs->absolute) {
1645 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1646 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1647 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1648 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1649 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1650 } else {
1651 if (vs->last_x != -1) {
1652 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1653 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1655 vs->last_x = x;
1656 vs->last_y = y;
1658 qemu_input_event_sync();
1661 static void reset_keys(VncState *vs)
1663 int i;
1664 for(i = 0; i < 256; i++) {
1665 if (vs->modifiers_state[i]) {
1666 qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1667 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1668 vs->modifiers_state[i] = 0;
1673 static void press_key(VncState *vs, int keysym)
1675 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1676 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1677 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1678 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1679 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1682 static void vnc_led_state_change(VncState *vs)
1684 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1685 return;
1688 vnc_lock_output(vs);
1689 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1690 vnc_write_u8(vs, 0);
1691 vnc_write_u16(vs, 1);
1692 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1693 vnc_write_u8(vs, vs->vd->ledstate);
1694 vnc_unlock_output(vs);
1695 vnc_flush(vs);
1698 static void kbd_leds(void *opaque, int ledstate)
1700 VncDisplay *vd = opaque;
1701 VncState *client;
1703 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1704 (ledstate & QEMU_NUM_LOCK_LED),
1705 (ledstate & QEMU_SCROLL_LOCK_LED));
1707 if (ledstate == vd->ledstate) {
1708 return;
1711 vd->ledstate = ledstate;
1713 QTAILQ_FOREACH(client, &vd->clients, next) {
1714 vnc_led_state_change(client);
1718 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1720 /* QEMU console switch */
1721 switch(keycode) {
1722 case 0x2a: /* Left Shift */
1723 case 0x36: /* Right Shift */
1724 case 0x1d: /* Left CTRL */
1725 case 0x9d: /* Right CTRL */
1726 case 0x38: /* Left ALT */
1727 case 0xb8: /* Right ALT */
1728 if (down)
1729 vs->modifiers_state[keycode] = 1;
1730 else
1731 vs->modifiers_state[keycode] = 0;
1732 break;
1733 case 0x02 ... 0x0a: /* '1' to '9' keys */
1734 if (vs->vd->dcl.con == NULL &&
1735 down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1736 /* Reset the modifiers sent to the current console */
1737 reset_keys(vs);
1738 console_select(keycode - 0x02);
1739 return;
1741 break;
1742 case 0x3a: /* CapsLock */
1743 case 0x45: /* NumLock */
1744 if (down)
1745 vs->modifiers_state[keycode] ^= 1;
1746 break;
1749 /* Turn off the lock state sync logic if the client support the led
1750 state extension.
1752 if (down && vs->vd->lock_key_sync &&
1753 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1754 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1755 /* If the numlock state needs to change then simulate an additional
1756 keypress before sending this one. This will happen if the user
1757 toggles numlock away from the VNC window.
1759 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1760 if (!vs->modifiers_state[0x45]) {
1761 trace_vnc_key_sync_numlock(true);
1762 vs->modifiers_state[0x45] = 1;
1763 press_key(vs, 0xff7f);
1765 } else {
1766 if (vs->modifiers_state[0x45]) {
1767 trace_vnc_key_sync_numlock(false);
1768 vs->modifiers_state[0x45] = 0;
1769 press_key(vs, 0xff7f);
1774 if (down && vs->vd->lock_key_sync &&
1775 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1776 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1777 /* If the capslock state needs to change then simulate an additional
1778 keypress before sending this one. This will happen if the user
1779 toggles capslock away from the VNC window.
1781 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1782 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1783 int capslock = !!(vs->modifiers_state[0x3a]);
1784 if (capslock) {
1785 if (uppercase == shift) {
1786 trace_vnc_key_sync_capslock(false);
1787 vs->modifiers_state[0x3a] = 0;
1788 press_key(vs, 0xffe5);
1790 } else {
1791 if (uppercase != shift) {
1792 trace_vnc_key_sync_capslock(true);
1793 vs->modifiers_state[0x3a] = 1;
1794 press_key(vs, 0xffe5);
1799 if (qemu_console_is_graphic(NULL)) {
1800 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1801 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1802 } else {
1803 bool numlock = vs->modifiers_state[0x45];
1804 bool control = (vs->modifiers_state[0x1d] ||
1805 vs->modifiers_state[0x9d]);
1806 /* QEMU console emulation */
1807 if (down) {
1808 switch (keycode) {
1809 case 0x2a: /* Left Shift */
1810 case 0x36: /* Right Shift */
1811 case 0x1d: /* Left CTRL */
1812 case 0x9d: /* Right CTRL */
1813 case 0x38: /* Left ALT */
1814 case 0xb8: /* Right ALT */
1815 break;
1816 case 0xc8:
1817 kbd_put_keysym(QEMU_KEY_UP);
1818 break;
1819 case 0xd0:
1820 kbd_put_keysym(QEMU_KEY_DOWN);
1821 break;
1822 case 0xcb:
1823 kbd_put_keysym(QEMU_KEY_LEFT);
1824 break;
1825 case 0xcd:
1826 kbd_put_keysym(QEMU_KEY_RIGHT);
1827 break;
1828 case 0xd3:
1829 kbd_put_keysym(QEMU_KEY_DELETE);
1830 break;
1831 case 0xc7:
1832 kbd_put_keysym(QEMU_KEY_HOME);
1833 break;
1834 case 0xcf:
1835 kbd_put_keysym(QEMU_KEY_END);
1836 break;
1837 case 0xc9:
1838 kbd_put_keysym(QEMU_KEY_PAGEUP);
1839 break;
1840 case 0xd1:
1841 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1842 break;
1844 case 0x47:
1845 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1846 break;
1847 case 0x48:
1848 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1849 break;
1850 case 0x49:
1851 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1852 break;
1853 case 0x4b:
1854 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1855 break;
1856 case 0x4c:
1857 kbd_put_keysym('5');
1858 break;
1859 case 0x4d:
1860 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1861 break;
1862 case 0x4f:
1863 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1864 break;
1865 case 0x50:
1866 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1867 break;
1868 case 0x51:
1869 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1870 break;
1871 case 0x52:
1872 kbd_put_keysym('0');
1873 break;
1874 case 0x53:
1875 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1876 break;
1878 case 0xb5:
1879 kbd_put_keysym('/');
1880 break;
1881 case 0x37:
1882 kbd_put_keysym('*');
1883 break;
1884 case 0x4a:
1885 kbd_put_keysym('-');
1886 break;
1887 case 0x4e:
1888 kbd_put_keysym('+');
1889 break;
1890 case 0x9c:
1891 kbd_put_keysym('\n');
1892 break;
1894 default:
1895 if (control) {
1896 kbd_put_keysym(sym & 0x1f);
1897 } else {
1898 kbd_put_keysym(sym);
1900 break;
1906 static void vnc_release_modifiers(VncState *vs)
1908 static const int keycodes[] = {
1909 /* shift, control, alt keys, both left & right */
1910 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1912 int i, keycode;
1914 if (!qemu_console_is_graphic(NULL)) {
1915 return;
1917 for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1918 keycode = keycodes[i];
1919 if (!vs->modifiers_state[keycode]) {
1920 continue;
1922 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1923 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1927 static const char *code2name(int keycode)
1929 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
1932 static void key_event(VncState *vs, int down, uint32_t sym)
1934 int keycode;
1935 int lsym = sym;
1937 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1938 lsym = lsym - 'A' + 'a';
1941 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1942 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1943 do_key_event(vs, down, keycode, sym);
1946 static void ext_key_event(VncState *vs, int down,
1947 uint32_t sym, uint16_t keycode)
1949 /* if the user specifies a keyboard layout, always use it */
1950 if (keyboard_layout) {
1951 key_event(vs, down, sym);
1952 } else {
1953 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
1954 do_key_event(vs, down, keycode, sym);
1958 static void framebuffer_update_request(VncState *vs, int incremental,
1959 int x, int y, int w, int h)
1961 if (incremental) {
1962 if (vs->update != VNC_STATE_UPDATE_FORCE) {
1963 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
1965 } else {
1966 vs->update = VNC_STATE_UPDATE_FORCE;
1967 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
1971 static void send_ext_key_event_ack(VncState *vs)
1973 vnc_lock_output(vs);
1974 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1975 vnc_write_u8(vs, 0);
1976 vnc_write_u16(vs, 1);
1977 vnc_framebuffer_update(vs, 0, 0,
1978 pixman_image_get_width(vs->vd->server),
1979 pixman_image_get_height(vs->vd->server),
1980 VNC_ENCODING_EXT_KEY_EVENT);
1981 vnc_unlock_output(vs);
1982 vnc_flush(vs);
1985 static void send_ext_audio_ack(VncState *vs)
1987 vnc_lock_output(vs);
1988 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1989 vnc_write_u8(vs, 0);
1990 vnc_write_u16(vs, 1);
1991 vnc_framebuffer_update(vs, 0, 0,
1992 pixman_image_get_width(vs->vd->server),
1993 pixman_image_get_height(vs->vd->server),
1994 VNC_ENCODING_AUDIO);
1995 vnc_unlock_output(vs);
1996 vnc_flush(vs);
1999 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2001 int i;
2002 unsigned int enc = 0;
2004 vs->features = 0;
2005 vs->vnc_encoding = 0;
2006 vs->tight.compression = 9;
2007 vs->tight.quality = -1; /* Lossless by default */
2008 vs->absolute = -1;
2011 * Start from the end because the encodings are sent in order of preference.
2012 * This way the preferred encoding (first encoding defined in the array)
2013 * will be set at the end of the loop.
2015 for (i = n_encodings - 1; i >= 0; i--) {
2016 enc = encodings[i];
2017 switch (enc) {
2018 case VNC_ENCODING_RAW:
2019 vs->vnc_encoding = enc;
2020 break;
2021 case VNC_ENCODING_COPYRECT:
2022 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2023 break;
2024 case VNC_ENCODING_HEXTILE:
2025 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2026 vs->vnc_encoding = enc;
2027 break;
2028 case VNC_ENCODING_TIGHT:
2029 vs->features |= VNC_FEATURE_TIGHT_MASK;
2030 vs->vnc_encoding = enc;
2031 break;
2032 #ifdef CONFIG_VNC_PNG
2033 case VNC_ENCODING_TIGHT_PNG:
2034 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2035 vs->vnc_encoding = enc;
2036 break;
2037 #endif
2038 case VNC_ENCODING_ZLIB:
2039 vs->features |= VNC_FEATURE_ZLIB_MASK;
2040 vs->vnc_encoding = enc;
2041 break;
2042 case VNC_ENCODING_ZRLE:
2043 vs->features |= VNC_FEATURE_ZRLE_MASK;
2044 vs->vnc_encoding = enc;
2045 break;
2046 case VNC_ENCODING_ZYWRLE:
2047 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2048 vs->vnc_encoding = enc;
2049 break;
2050 case VNC_ENCODING_DESKTOPRESIZE:
2051 vs->features |= VNC_FEATURE_RESIZE_MASK;
2052 break;
2053 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2054 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2055 break;
2056 case VNC_ENCODING_RICH_CURSOR:
2057 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2058 if (vs->vd->cursor) {
2059 vnc_cursor_define(vs);
2061 break;
2062 case VNC_ENCODING_EXT_KEY_EVENT:
2063 send_ext_key_event_ack(vs);
2064 break;
2065 case VNC_ENCODING_AUDIO:
2066 send_ext_audio_ack(vs);
2067 break;
2068 case VNC_ENCODING_WMVi:
2069 vs->features |= VNC_FEATURE_WMVI_MASK;
2070 break;
2071 case VNC_ENCODING_LED_STATE:
2072 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2073 break;
2074 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2075 vs->tight.compression = (enc & 0x0F);
2076 break;
2077 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2078 if (vs->vd->lossy) {
2079 vs->tight.quality = (enc & 0x0F);
2081 break;
2082 default:
2083 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2084 break;
2087 vnc_desktop_resize(vs);
2088 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2089 vnc_led_state_change(vs);
2092 static void set_pixel_conversion(VncState *vs)
2094 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2096 if (fmt == VNC_SERVER_FB_FORMAT) {
2097 vs->write_pixels = vnc_write_pixels_copy;
2098 vnc_hextile_set_pixel_conversion(vs, 0);
2099 } else {
2100 vs->write_pixels = vnc_write_pixels_generic;
2101 vnc_hextile_set_pixel_conversion(vs, 1);
2105 static void send_color_map(VncState *vs)
2107 int i;
2109 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2110 vnc_write_u8(vs, 0); /* padding */
2111 vnc_write_u16(vs, 0); /* first color */
2112 vnc_write_u16(vs, 256); /* # of colors */
2114 for (i = 0; i < 256; i++) {
2115 PixelFormat *pf = &vs->client_pf;
2117 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2118 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2119 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2123 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2124 int big_endian_flag, int true_color_flag,
2125 int red_max, int green_max, int blue_max,
2126 int red_shift, int green_shift, int blue_shift)
2128 if (!true_color_flag) {
2129 /* Expose a reasonable default 256 color map */
2130 bits_per_pixel = 8;
2131 red_max = 7;
2132 green_max = 7;
2133 blue_max = 3;
2134 red_shift = 0;
2135 green_shift = 3;
2136 blue_shift = 6;
2139 switch (bits_per_pixel) {
2140 case 8:
2141 case 16:
2142 case 32:
2143 break;
2144 default:
2145 vnc_client_error(vs);
2146 return;
2149 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2150 vs->client_pf.rbits = ctpopl(red_max);
2151 vs->client_pf.rshift = red_shift;
2152 vs->client_pf.rmask = red_max << red_shift;
2153 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2154 vs->client_pf.gbits = ctpopl(green_max);
2155 vs->client_pf.gshift = green_shift;
2156 vs->client_pf.gmask = green_max << green_shift;
2157 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2158 vs->client_pf.bbits = ctpopl(blue_max);
2159 vs->client_pf.bshift = blue_shift;
2160 vs->client_pf.bmask = blue_max << blue_shift;
2161 vs->client_pf.bits_per_pixel = bits_per_pixel;
2162 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2163 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2164 vs->client_be = big_endian_flag;
2166 if (!true_color_flag) {
2167 send_color_map(vs);
2170 set_pixel_conversion(vs);
2172 graphic_hw_invalidate(vs->vd->dcl.con);
2173 graphic_hw_update(vs->vd->dcl.con);
2176 static void pixel_format_message (VncState *vs) {
2177 char pad[3] = { 0, 0, 0 };
2179 vs->client_pf = qemu_default_pixelformat(32);
2181 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2182 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2184 #ifdef HOST_WORDS_BIGENDIAN
2185 vnc_write_u8(vs, 1); /* big-endian-flag */
2186 #else
2187 vnc_write_u8(vs, 0); /* big-endian-flag */
2188 #endif
2189 vnc_write_u8(vs, 1); /* true-color-flag */
2190 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2191 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2192 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2193 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2194 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2195 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2196 vnc_write(vs, pad, 3); /* padding */
2198 vnc_hextile_set_pixel_conversion(vs, 0);
2199 vs->write_pixels = vnc_write_pixels_copy;
2202 static void vnc_colordepth(VncState *vs)
2204 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2205 /* Sending a WMVi message to notify the client*/
2206 vnc_lock_output(vs);
2207 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2208 vnc_write_u8(vs, 0);
2209 vnc_write_u16(vs, 1); /* number of rects */
2210 vnc_framebuffer_update(vs, 0, 0,
2211 pixman_image_get_width(vs->vd->server),
2212 pixman_image_get_height(vs->vd->server),
2213 VNC_ENCODING_WMVi);
2214 pixel_format_message(vs);
2215 vnc_unlock_output(vs);
2216 vnc_flush(vs);
2217 } else {
2218 set_pixel_conversion(vs);
2222 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2224 int i;
2225 uint16_t limit;
2226 VncDisplay *vd = vs->vd;
2228 if (data[0] > 3) {
2229 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2232 switch (data[0]) {
2233 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2234 if (len == 1)
2235 return 20;
2237 set_pixel_format(vs, read_u8(data, 4),
2238 read_u8(data, 6), read_u8(data, 7),
2239 read_u16(data, 8), read_u16(data, 10),
2240 read_u16(data, 12), read_u8(data, 14),
2241 read_u8(data, 15), read_u8(data, 16));
2242 break;
2243 case VNC_MSG_CLIENT_SET_ENCODINGS:
2244 if (len == 1)
2245 return 4;
2247 if (len == 4) {
2248 limit = read_u16(data, 2);
2249 if (limit > 0)
2250 return 4 + (limit * 4);
2251 } else
2252 limit = read_u16(data, 2);
2254 for (i = 0; i < limit; i++) {
2255 int32_t val = read_s32(data, 4 + (i * 4));
2256 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2259 set_encodings(vs, (int32_t *)(data + 4), limit);
2260 break;
2261 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2262 if (len == 1)
2263 return 10;
2265 framebuffer_update_request(vs,
2266 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2267 read_u16(data, 6), read_u16(data, 8));
2268 break;
2269 case VNC_MSG_CLIENT_KEY_EVENT:
2270 if (len == 1)
2271 return 8;
2273 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2274 break;
2275 case VNC_MSG_CLIENT_POINTER_EVENT:
2276 if (len == 1)
2277 return 6;
2279 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2280 break;
2281 case VNC_MSG_CLIENT_CUT_TEXT:
2282 if (len == 1) {
2283 return 8;
2285 if (len == 8) {
2286 uint32_t dlen = read_u32(data, 4);
2287 if (dlen > (1 << 20)) {
2288 error_report("vnc: client_cut_text msg payload has %u bytes"
2289 " which exceeds our limit of 1MB.", dlen);
2290 vnc_client_error(vs);
2291 break;
2293 if (dlen > 0) {
2294 return 8 + dlen;
2298 client_cut_text(vs, read_u32(data, 4), data + 8);
2299 break;
2300 case VNC_MSG_CLIENT_QEMU:
2301 if (len == 1)
2302 return 2;
2304 switch (read_u8(data, 1)) {
2305 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2306 if (len == 2)
2307 return 12;
2309 ext_key_event(vs, read_u16(data, 2),
2310 read_u32(data, 4), read_u32(data, 8));
2311 break;
2312 case VNC_MSG_CLIENT_QEMU_AUDIO:
2313 if (len == 2)
2314 return 4;
2316 switch (read_u16 (data, 2)) {
2317 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2318 audio_add(vs);
2319 break;
2320 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2321 audio_del(vs);
2322 break;
2323 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2324 if (len == 4)
2325 return 10;
2326 switch (read_u8(data, 4)) {
2327 case 0: vs->as.fmt = AUD_FMT_U8; break;
2328 case 1: vs->as.fmt = AUD_FMT_S8; break;
2329 case 2: vs->as.fmt = AUD_FMT_U16; break;
2330 case 3: vs->as.fmt = AUD_FMT_S16; break;
2331 case 4: vs->as.fmt = AUD_FMT_U32; break;
2332 case 5: vs->as.fmt = AUD_FMT_S32; break;
2333 default:
2334 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2335 vnc_client_error(vs);
2336 break;
2338 vs->as.nchannels = read_u8(data, 5);
2339 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2340 VNC_DEBUG("Invalid audio channel count %d\n",
2341 read_u8(data, 5));
2342 vnc_client_error(vs);
2343 break;
2345 vs->as.freq = read_u32(data, 6);
2346 break;
2347 default:
2348 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2349 vnc_client_error(vs);
2350 break;
2352 break;
2354 default:
2355 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2356 vnc_client_error(vs);
2357 break;
2359 break;
2360 default:
2361 VNC_DEBUG("Msg: %d\n", data[0]);
2362 vnc_client_error(vs);
2363 break;
2366 vnc_update_throttle_offset(vs);
2367 vnc_read_when(vs, protocol_client_msg, 1);
2368 return 0;
2371 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2373 char buf[1024];
2374 VncShareMode mode;
2375 int size;
2377 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2378 switch (vs->vd->share_policy) {
2379 case VNC_SHARE_POLICY_IGNORE:
2381 * Ignore the shared flag. Nothing to do here.
2383 * Doesn't conform to the rfb spec but is traditional qemu
2384 * behavior, thus left here as option for compatibility
2385 * reasons.
2387 break;
2388 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2390 * Policy: Allow clients ask for exclusive access.
2392 * Implementation: When a client asks for exclusive access,
2393 * disconnect all others. Shared connects are allowed as long
2394 * as no exclusive connection exists.
2396 * This is how the rfb spec suggests to handle the shared flag.
2398 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2399 VncState *client;
2400 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2401 if (vs == client) {
2402 continue;
2404 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2405 client->share_mode != VNC_SHARE_MODE_SHARED) {
2406 continue;
2408 vnc_disconnect_start(client);
2411 if (mode == VNC_SHARE_MODE_SHARED) {
2412 if (vs->vd->num_exclusive > 0) {
2413 vnc_disconnect_start(vs);
2414 return 0;
2417 break;
2418 case VNC_SHARE_POLICY_FORCE_SHARED:
2420 * Policy: Shared connects only.
2421 * Implementation: Disallow clients asking for exclusive access.
2423 * Useful for shared desktop sessions where you don't want
2424 * someone forgetting to say -shared when running the vnc
2425 * client disconnect everybody else.
2427 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2428 vnc_disconnect_start(vs);
2429 return 0;
2431 break;
2433 vnc_set_share_mode(vs, mode);
2435 if (vs->vd->num_shared > vs->vd->connections_limit) {
2436 vnc_disconnect_start(vs);
2437 return 0;
2440 vs->client_width = pixman_image_get_width(vs->vd->server);
2441 vs->client_height = pixman_image_get_height(vs->vd->server);
2442 vnc_write_u16(vs, vs->client_width);
2443 vnc_write_u16(vs, vs->client_height);
2445 pixel_format_message(vs);
2447 if (qemu_name) {
2448 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2449 if (size > sizeof(buf)) {
2450 size = sizeof(buf);
2452 } else {
2453 size = snprintf(buf, sizeof(buf), "QEMU");
2456 vnc_write_u32(vs, size);
2457 vnc_write(vs, buf, size);
2458 vnc_flush(vs);
2460 vnc_client_cache_auth(vs);
2461 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2463 vnc_read_when(vs, protocol_client_msg, 1);
2465 return 0;
2468 void start_client_init(VncState *vs)
2470 vnc_read_when(vs, protocol_client_init, 1);
2473 static void make_challenge(VncState *vs)
2475 int i;
2477 srand(time(NULL)+getpid()+getpid()*987654+rand());
2479 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2480 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2483 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2485 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2486 size_t i, pwlen;
2487 unsigned char key[8];
2488 time_t now = time(NULL);
2489 QCryptoCipher *cipher = NULL;
2490 Error *err = NULL;
2492 if (!vs->vd->password) {
2493 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2494 goto reject;
2496 if (vs->vd->expires < now) {
2497 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2498 goto reject;
2501 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2503 /* Calculate the expected challenge response */
2504 pwlen = strlen(vs->vd->password);
2505 for (i=0; i<sizeof(key); i++)
2506 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2508 cipher = qcrypto_cipher_new(
2509 QCRYPTO_CIPHER_ALG_DES_RFB,
2510 QCRYPTO_CIPHER_MODE_ECB,
2511 key, G_N_ELEMENTS(key),
2512 &err);
2513 if (!cipher) {
2514 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2515 error_get_pretty(err));
2516 error_free(err);
2517 goto reject;
2520 if (qcrypto_cipher_encrypt(cipher,
2521 vs->challenge,
2522 response,
2523 VNC_AUTH_CHALLENGE_SIZE,
2524 &err) < 0) {
2525 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2526 error_get_pretty(err));
2527 error_free(err);
2528 goto reject;
2531 /* Compare expected vs actual challenge response */
2532 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2533 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2534 goto reject;
2535 } else {
2536 trace_vnc_auth_pass(vs, vs->auth);
2537 vnc_write_u32(vs, 0); /* Accept auth */
2538 vnc_flush(vs);
2540 start_client_init(vs);
2543 qcrypto_cipher_free(cipher);
2544 return 0;
2546 reject:
2547 vnc_write_u32(vs, 1); /* Reject auth */
2548 if (vs->minor >= 8) {
2549 static const char err[] = "Authentication failed";
2550 vnc_write_u32(vs, sizeof(err));
2551 vnc_write(vs, err, sizeof(err));
2553 vnc_flush(vs);
2554 vnc_client_error(vs);
2555 qcrypto_cipher_free(cipher);
2556 return 0;
2559 void start_auth_vnc(VncState *vs)
2561 make_challenge(vs);
2562 /* Send client a 'random' challenge */
2563 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2564 vnc_flush(vs);
2566 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2570 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2572 /* We only advertise 1 auth scheme at a time, so client
2573 * must pick the one we sent. Verify this */
2574 if (data[0] != vs->auth) { /* Reject auth */
2575 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2576 vnc_write_u32(vs, 1);
2577 if (vs->minor >= 8) {
2578 static const char err[] = "Authentication failed";
2579 vnc_write_u32(vs, sizeof(err));
2580 vnc_write(vs, err, sizeof(err));
2582 vnc_client_error(vs);
2583 } else { /* Accept requested auth */
2584 trace_vnc_auth_start(vs, vs->auth);
2585 switch (vs->auth) {
2586 case VNC_AUTH_NONE:
2587 if (vs->minor >= 8) {
2588 vnc_write_u32(vs, 0); /* Accept auth completion */
2589 vnc_flush(vs);
2591 trace_vnc_auth_pass(vs, vs->auth);
2592 start_client_init(vs);
2593 break;
2595 case VNC_AUTH_VNC:
2596 start_auth_vnc(vs);
2597 break;
2599 case VNC_AUTH_VENCRYPT:
2600 start_auth_vencrypt(vs);
2601 break;
2603 #ifdef CONFIG_VNC_SASL
2604 case VNC_AUTH_SASL:
2605 start_auth_sasl(vs);
2606 break;
2607 #endif /* CONFIG_VNC_SASL */
2609 default: /* Should not be possible, but just in case */
2610 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2611 vnc_write_u8(vs, 1);
2612 if (vs->minor >= 8) {
2613 static const char err[] = "Authentication failed";
2614 vnc_write_u32(vs, sizeof(err));
2615 vnc_write(vs, err, sizeof(err));
2617 vnc_client_error(vs);
2620 return 0;
2623 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2625 char local[13];
2627 memcpy(local, version, 12);
2628 local[12] = 0;
2630 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2631 VNC_DEBUG("Malformed protocol version %s\n", local);
2632 vnc_client_error(vs);
2633 return 0;
2635 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2636 if (vs->major != 3 ||
2637 (vs->minor != 3 &&
2638 vs->minor != 4 &&
2639 vs->minor != 5 &&
2640 vs->minor != 7 &&
2641 vs->minor != 8)) {
2642 VNC_DEBUG("Unsupported client version\n");
2643 vnc_write_u32(vs, VNC_AUTH_INVALID);
2644 vnc_flush(vs);
2645 vnc_client_error(vs);
2646 return 0;
2648 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2649 * as equivalent to v3.3 by servers
2651 if (vs->minor == 4 || vs->minor == 5)
2652 vs->minor = 3;
2654 if (vs->minor == 3) {
2655 trace_vnc_auth_start(vs, vs->auth);
2656 if (vs->auth == VNC_AUTH_NONE) {
2657 vnc_write_u32(vs, vs->auth);
2658 vnc_flush(vs);
2659 trace_vnc_auth_pass(vs, vs->auth);
2660 start_client_init(vs);
2661 } else if (vs->auth == VNC_AUTH_VNC) {
2662 VNC_DEBUG("Tell client VNC auth\n");
2663 vnc_write_u32(vs, vs->auth);
2664 vnc_flush(vs);
2665 start_auth_vnc(vs);
2666 } else {
2667 trace_vnc_auth_fail(vs, vs->auth,
2668 "Unsupported auth method for v3.3", "");
2669 vnc_write_u32(vs, VNC_AUTH_INVALID);
2670 vnc_flush(vs);
2671 vnc_client_error(vs);
2673 } else {
2674 vnc_write_u8(vs, 1); /* num auth */
2675 vnc_write_u8(vs, vs->auth);
2676 vnc_read_when(vs, protocol_client_auth, 1);
2677 vnc_flush(vs);
2680 return 0;
2683 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2685 struct VncSurface *vs = &vd->guest;
2687 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2690 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2692 int i, j;
2694 w = (x + w) / VNC_STAT_RECT;
2695 h = (y + h) / VNC_STAT_RECT;
2696 x /= VNC_STAT_RECT;
2697 y /= VNC_STAT_RECT;
2699 for (j = y; j <= h; j++) {
2700 for (i = x; i <= w; i++) {
2701 vs->lossy_rect[j][i] = 1;
2706 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2708 VncState *vs;
2709 int sty = y / VNC_STAT_RECT;
2710 int stx = x / VNC_STAT_RECT;
2711 int has_dirty = 0;
2713 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2714 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2716 QTAILQ_FOREACH(vs, &vd->clients, next) {
2717 int j;
2719 /* kernel send buffers are full -> refresh later */
2720 if (vs->output.offset) {
2721 continue;
2724 if (!vs->lossy_rect[sty][stx]) {
2725 continue;
2728 vs->lossy_rect[sty][stx] = 0;
2729 for (j = 0; j < VNC_STAT_RECT; ++j) {
2730 bitmap_set(vs->dirty[y + j],
2731 x / VNC_DIRTY_PIXELS_PER_BIT,
2732 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2734 has_dirty++;
2737 return has_dirty;
2740 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2742 int width = MIN(pixman_image_get_width(vd->guest.fb),
2743 pixman_image_get_width(vd->server));
2744 int height = MIN(pixman_image_get_height(vd->guest.fb),
2745 pixman_image_get_height(vd->server));
2746 int x, y;
2747 struct timeval res;
2748 int has_dirty = 0;
2750 for (y = 0; y < height; y += VNC_STAT_RECT) {
2751 for (x = 0; x < width; x += VNC_STAT_RECT) {
2752 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2754 rect->updated = false;
2758 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2760 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2761 return has_dirty;
2763 vd->guest.last_freq_check = *tv;
2765 for (y = 0; y < height; y += VNC_STAT_RECT) {
2766 for (x = 0; x < width; x += VNC_STAT_RECT) {
2767 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2768 int count = ARRAY_SIZE(rect->times);
2769 struct timeval min, max;
2771 if (!timerisset(&rect->times[count - 1])) {
2772 continue ;
2775 max = rect->times[(rect->idx + count - 1) % count];
2776 qemu_timersub(tv, &max, &res);
2778 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2779 rect->freq = 0;
2780 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2781 memset(rect->times, 0, sizeof (rect->times));
2782 continue ;
2785 min = rect->times[rect->idx];
2786 max = rect->times[(rect->idx + count - 1) % count];
2787 qemu_timersub(&max, &min, &res);
2789 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2790 rect->freq /= count;
2791 rect->freq = 1. / rect->freq;
2794 return has_dirty;
2797 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2799 int i, j;
2800 double total = 0;
2801 int num = 0;
2803 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2804 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2806 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2807 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2808 total += vnc_stat_rect(vs->vd, i, j)->freq;
2809 num++;
2813 if (num) {
2814 return total / num;
2815 } else {
2816 return 0;
2820 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2822 VncRectStat *rect;
2824 rect = vnc_stat_rect(vd, x, y);
2825 if (rect->updated) {
2826 return ;
2828 rect->times[rect->idx] = *tv;
2829 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2830 rect->updated = true;
2833 static int vnc_refresh_server_surface(VncDisplay *vd)
2835 int width = MIN(pixman_image_get_width(vd->guest.fb),
2836 pixman_image_get_width(vd->server));
2837 int height = MIN(pixman_image_get_height(vd->guest.fb),
2838 pixman_image_get_height(vd->server));
2839 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2840 uint8_t *guest_row0 = NULL, *server_row0;
2841 VncState *vs;
2842 int has_dirty = 0;
2843 pixman_image_t *tmpbuf = NULL;
2845 struct timeval tv = { 0, 0 };
2847 if (!vd->non_adaptive) {
2848 gettimeofday(&tv, NULL);
2849 has_dirty = vnc_update_stats(vd, &tv);
2853 * Walk through the guest dirty map.
2854 * Check and copy modified bits from guest to server surface.
2855 * Update server dirty map.
2857 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2858 server_stride = guest_stride = guest_ll =
2859 pixman_image_get_stride(vd->server);
2860 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2861 server_stride);
2862 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2863 int width = pixman_image_get_width(vd->server);
2864 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2865 } else {
2866 int guest_bpp =
2867 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2868 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2869 guest_stride = pixman_image_get_stride(vd->guest.fb);
2870 guest_ll = pixman_image_get_width(vd->guest.fb) * (DIV_ROUND_UP(guest_bpp, 8));
2872 line_bytes = MIN(server_stride, guest_ll);
2874 for (;;) {
2875 int x;
2876 uint8_t *guest_ptr, *server_ptr;
2877 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2878 height * VNC_DIRTY_BPL(&vd->guest),
2879 y * VNC_DIRTY_BPL(&vd->guest));
2880 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2881 /* no more dirty bits */
2882 break;
2884 y = offset / VNC_DIRTY_BPL(&vd->guest);
2885 x = offset % VNC_DIRTY_BPL(&vd->guest);
2887 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2889 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2890 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2891 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2892 } else {
2893 guest_ptr = guest_row0 + y * guest_stride;
2895 guest_ptr += x * cmp_bytes;
2897 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2898 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2899 int _cmp_bytes = cmp_bytes;
2900 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2901 continue;
2903 if ((x + 1) * cmp_bytes > line_bytes) {
2904 _cmp_bytes = line_bytes - x * cmp_bytes;
2906 assert(_cmp_bytes >= 0);
2907 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2908 continue;
2910 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2911 if (!vd->non_adaptive) {
2912 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2913 y, &tv);
2915 QTAILQ_FOREACH(vs, &vd->clients, next) {
2916 set_bit(x, vs->dirty[y]);
2918 has_dirty++;
2921 y++;
2923 qemu_pixman_image_unref(tmpbuf);
2924 return has_dirty;
2927 static void vnc_refresh(DisplayChangeListener *dcl)
2929 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2930 VncState *vs, *vn;
2931 int has_dirty, rects = 0;
2933 if (QTAILQ_EMPTY(&vd->clients)) {
2934 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2935 return;
2938 graphic_hw_update(vd->dcl.con);
2940 if (vnc_trylock_display(vd)) {
2941 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2942 return;
2945 has_dirty = vnc_refresh_server_surface(vd);
2946 vnc_unlock_display(vd);
2948 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2949 rects += vnc_update_client(vs, has_dirty);
2950 /* vs might be free()ed here */
2953 if (has_dirty && rects) {
2954 vd->dcl.update_interval /= 2;
2955 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
2956 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
2958 } else {
2959 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
2960 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
2961 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
2966 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
2967 bool skipauth, bool websocket)
2969 VncState *vs = g_new0(VncState, 1);
2970 bool first_client = QTAILQ_EMPTY(&vd->clients);
2971 int i;
2973 trace_vnc_client_connect(vs, sioc);
2974 vs->sioc = sioc;
2975 object_ref(OBJECT(vs->sioc));
2976 vs->ioc = QIO_CHANNEL(sioc);
2977 object_ref(OBJECT(vs->ioc));
2978 vs->vd = vd;
2980 buffer_init(&vs->input, "vnc-input/%p", sioc);
2981 buffer_init(&vs->output, "vnc-output/%p", sioc);
2982 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
2984 buffer_init(&vs->tight.tight, "vnc-tight/%p", sioc);
2985 buffer_init(&vs->tight.zlib, "vnc-tight-zlib/%p", sioc);
2986 buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
2987 #ifdef CONFIG_VNC_JPEG
2988 buffer_init(&vs->tight.jpeg, "vnc-tight-jpeg/%p", sioc);
2989 #endif
2990 #ifdef CONFIG_VNC_PNG
2991 buffer_init(&vs->tight.png, "vnc-tight-png/%p", sioc);
2992 #endif
2993 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
2994 buffer_init(&vs->zrle.zrle, "vnc-zrle/%p", sioc);
2995 buffer_init(&vs->zrle.fb, "vnc-zrle-fb/%p", sioc);
2996 buffer_init(&vs->zrle.zlib, "vnc-zrle-zlib/%p", sioc);
2998 if (skipauth) {
2999 vs->auth = VNC_AUTH_NONE;
3000 vs->subauth = VNC_AUTH_INVALID;
3001 } else {
3002 if (websocket) {
3003 vs->auth = vd->ws_auth;
3004 vs->subauth = VNC_AUTH_INVALID;
3005 } else {
3006 vs->auth = vd->auth;
3007 vs->subauth = vd->subauth;
3010 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3011 sioc, websocket, vs->auth, vs->subauth);
3013 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3014 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3015 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3018 VNC_DEBUG("New client on socket %p\n", vs->sioc);
3019 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3020 qio_channel_set_blocking(vs->ioc, false, NULL);
3021 if (vs->ioc_tag) {
3022 g_source_remove(vs->ioc_tag);
3024 if (websocket) {
3025 vs->websocket = 1;
3026 if (vd->tlscreds) {
3027 vs->ioc_tag = qio_channel_add_watch(
3028 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
3029 } else {
3030 vs->ioc_tag = qio_channel_add_watch(
3031 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
3033 } else {
3034 vs->ioc_tag = qio_channel_add_watch(
3035 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
3038 vnc_client_cache_addr(vs);
3039 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3040 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3042 vs->last_x = -1;
3043 vs->last_y = -1;
3045 vs->as.freq = 44100;
3046 vs->as.nchannels = 2;
3047 vs->as.fmt = AUD_FMT_S16;
3048 vs->as.endianness = 0;
3050 qemu_mutex_init(&vs->output_mutex);
3051 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3053 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3054 if (first_client) {
3055 vnc_update_server_surface(vd);
3058 graphic_hw_update(vd->dcl.con);
3060 if (!vs->websocket) {
3061 vnc_start_protocol(vs);
3064 if (vd->num_connecting > vd->connections_limit) {
3065 QTAILQ_FOREACH(vs, &vd->clients, next) {
3066 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3067 vnc_disconnect_start(vs);
3068 return;
3074 void vnc_start_protocol(VncState *vs)
3076 vnc_write(vs, "RFB 003.008\n", 12);
3077 vnc_flush(vs);
3078 vnc_read_when(vs, protocol_version, 12);
3080 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3081 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3084 static gboolean vnc_listen_io(QIOChannel *ioc,
3085 GIOCondition condition,
3086 void *opaque)
3088 VncDisplay *vd = opaque;
3089 QIOChannelSocket *sioc = NULL;
3090 Error *err = NULL;
3091 bool isWebsock = false;
3092 size_t i;
3094 for (i = 0; i < vd->nlwebsock; i++) {
3095 if (ioc == QIO_CHANNEL(vd->lwebsock[i])) {
3096 isWebsock = true;
3097 break;
3101 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), &err);
3102 if (sioc != NULL) {
3103 qio_channel_set_name(QIO_CHANNEL(sioc),
3104 isWebsock ? "vnc-ws-server" : "vnc-server");
3105 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
3106 vnc_connect(vd, sioc, false, isWebsock);
3107 object_unref(OBJECT(sioc));
3108 } else {
3109 /* client probably closed connection before we got there */
3110 error_free(err);
3113 return TRUE;
3116 static const DisplayChangeListenerOps dcl_ops = {
3117 .dpy_name = "vnc",
3118 .dpy_refresh = vnc_refresh,
3119 .dpy_gfx_update = vnc_dpy_update,
3120 .dpy_gfx_switch = vnc_dpy_switch,
3121 .dpy_gfx_check_format = qemu_pixman_check_format,
3122 .dpy_mouse_set = vnc_mouse_set,
3123 .dpy_cursor_define = vnc_dpy_cursor_define,
3126 void vnc_display_init(const char *id)
3128 VncDisplay *vd;
3130 if (vnc_display_find(id) != NULL) {
3131 return;
3133 vd = g_malloc0(sizeof(*vd));
3135 vd->id = strdup(id);
3136 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3138 QTAILQ_INIT(&vd->clients);
3139 vd->expires = TIME_MAX;
3141 if (keyboard_layout) {
3142 trace_vnc_key_map_init(keyboard_layout);
3143 vd->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
3144 } else {
3145 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
3148 if (!vd->kbd_layout) {
3149 exit(1);
3152 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3153 vd->connections_limit = 32;
3155 qemu_mutex_init(&vd->mutex);
3156 vnc_start_worker_thread();
3158 vd->dcl.ops = &dcl_ops;
3159 register_displaychangelistener(&vd->dcl);
3163 static void vnc_display_close(VncDisplay *vd)
3165 size_t i;
3166 if (!vd) {
3167 return;
3169 vd->is_unix = false;
3170 for (i = 0; i < vd->nlsock; i++) {
3171 if (vd->lsock_tag[i]) {
3172 g_source_remove(vd->lsock_tag[i]);
3174 object_unref(OBJECT(vd->lsock[i]));
3176 g_free(vd->lsock);
3177 g_free(vd->lsock_tag);
3178 vd->lsock = NULL;
3179 vd->lsock_tag = NULL;
3180 vd->nlsock = 0;
3182 for (i = 0; i < vd->nlwebsock; i++) {
3183 if (vd->lwebsock_tag[i]) {
3184 g_source_remove(vd->lwebsock_tag[i]);
3186 object_unref(OBJECT(vd->lwebsock[i]));
3188 g_free(vd->lwebsock);
3189 g_free(vd->lwebsock_tag);
3190 vd->lwebsock = NULL;
3191 vd->lwebsock_tag = NULL;
3192 vd->nlwebsock = 0;
3194 vd->auth = VNC_AUTH_INVALID;
3195 vd->subauth = VNC_AUTH_INVALID;
3196 if (vd->tlscreds) {
3197 object_unparent(OBJECT(vd->tlscreds));
3198 vd->tlscreds = NULL;
3200 g_free(vd->tlsaclname);
3201 vd->tlsaclname = NULL;
3202 if (vd->lock_key_sync) {
3203 qemu_remove_led_event_handler(vd->led);
3204 vd->led = NULL;
3208 int vnc_display_password(const char *id, const char *password)
3210 VncDisplay *vd = vnc_display_find(id);
3212 if (!vd) {
3213 return -EINVAL;
3215 if (vd->auth == VNC_AUTH_NONE) {
3216 error_printf_unless_qmp("If you want use passwords please enable "
3217 "password auth using '-vnc ${dpy},password'.\n");
3218 return -EINVAL;
3221 g_free(vd->password);
3222 vd->password = g_strdup(password);
3224 return 0;
3227 int vnc_display_pw_expire(const char *id, time_t expires)
3229 VncDisplay *vd = vnc_display_find(id);
3231 if (!vd) {
3232 return -EINVAL;
3235 vd->expires = expires;
3236 return 0;
3239 static void vnc_display_print_local_addr(VncDisplay *vd)
3241 SocketAddress *addr;
3242 Error *err = NULL;
3244 if (!vd->nlsock) {
3245 return;
3248 addr = qio_channel_socket_get_local_address(vd->lsock[0], &err);
3249 if (!addr) {
3250 return;
3253 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3254 qapi_free_SocketAddress(addr);
3255 return;
3257 error_printf_unless_qmp("VNC server running on %s:%s\n",
3258 addr->u.inet.host,
3259 addr->u.inet.port);
3260 qapi_free_SocketAddress(addr);
3263 static QemuOptsList qemu_vnc_opts = {
3264 .name = "vnc",
3265 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3266 .implied_opt_name = "vnc",
3267 .desc = {
3269 .name = "vnc",
3270 .type = QEMU_OPT_STRING,
3272 .name = "websocket",
3273 .type = QEMU_OPT_STRING,
3275 .name = "tls-creds",
3276 .type = QEMU_OPT_STRING,
3278 /* Deprecated in favour of tls-creds */
3279 .name = "x509",
3280 .type = QEMU_OPT_STRING,
3282 .name = "share",
3283 .type = QEMU_OPT_STRING,
3285 .name = "display",
3286 .type = QEMU_OPT_STRING,
3288 .name = "head",
3289 .type = QEMU_OPT_NUMBER,
3291 .name = "connections",
3292 .type = QEMU_OPT_NUMBER,
3294 .name = "to",
3295 .type = QEMU_OPT_NUMBER,
3297 .name = "ipv4",
3298 .type = QEMU_OPT_BOOL,
3300 .name = "ipv6",
3301 .type = QEMU_OPT_BOOL,
3303 .name = "password",
3304 .type = QEMU_OPT_BOOL,
3306 .name = "reverse",
3307 .type = QEMU_OPT_BOOL,
3309 .name = "lock-key-sync",
3310 .type = QEMU_OPT_BOOL,
3312 .name = "key-delay-ms",
3313 .type = QEMU_OPT_NUMBER,
3315 .name = "sasl",
3316 .type = QEMU_OPT_BOOL,
3318 /* Deprecated in favour of tls-creds */
3319 .name = "tls",
3320 .type = QEMU_OPT_BOOL,
3322 /* Deprecated in favour of tls-creds */
3323 .name = "x509verify",
3324 .type = QEMU_OPT_STRING,
3326 .name = "acl",
3327 .type = QEMU_OPT_BOOL,
3329 .name = "lossy",
3330 .type = QEMU_OPT_BOOL,
3332 .name = "non-adaptive",
3333 .type = QEMU_OPT_BOOL,
3335 { /* end of list */ }
3340 static int
3341 vnc_display_setup_auth(int *auth,
3342 int *subauth,
3343 QCryptoTLSCreds *tlscreds,
3344 bool password,
3345 bool sasl,
3346 bool websocket,
3347 Error **errp)
3350 * We have a choice of 3 authentication options
3352 * 1. none
3353 * 2. vnc
3354 * 3. sasl
3356 * The channel can be run in 2 modes
3358 * 1. clear
3359 * 2. tls
3361 * And TLS can use 2 types of credentials
3363 * 1. anon
3364 * 2. x509
3366 * We thus have 9 possible logical combinations
3368 * 1. clear + none
3369 * 2. clear + vnc
3370 * 3. clear + sasl
3371 * 4. tls + anon + none
3372 * 5. tls + anon + vnc
3373 * 6. tls + anon + sasl
3374 * 7. tls + x509 + none
3375 * 8. tls + x509 + vnc
3376 * 9. tls + x509 + sasl
3378 * These need to be mapped into the VNC auth schemes
3379 * in an appropriate manner. In regular VNC, all the
3380 * TLS options get mapped into VNC_AUTH_VENCRYPT
3381 * sub-auth types.
3383 * In websockets, the https:// protocol already provides
3384 * TLS support, so there is no need to make use of the
3385 * VeNCrypt extension. Furthermore, websockets browser
3386 * clients could not use VeNCrypt even if they wanted to,
3387 * as they cannot control when the TLS handshake takes
3388 * place. Thus there is no option but to rely on https://,
3389 * meaning combinations 4->6 and 7->9 will be mapped to
3390 * VNC auth schemes in the same way as combos 1->3.
3392 * Regardless of fact that we have a different mapping to
3393 * VNC auth mechs for plain VNC vs websockets VNC, the end
3394 * result has the same security characteristics.
3396 if (websocket || !tlscreds) {
3397 if (password) {
3398 VNC_DEBUG("Initializing VNC server with password auth\n");
3399 *auth = VNC_AUTH_VNC;
3400 } else if (sasl) {
3401 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3402 *auth = VNC_AUTH_SASL;
3403 } else {
3404 VNC_DEBUG("Initializing VNC server with no auth\n");
3405 *auth = VNC_AUTH_NONE;
3407 *subauth = VNC_AUTH_INVALID;
3408 } else {
3409 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3410 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3411 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3412 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3414 if (!is_x509 && !is_anon) {
3415 error_setg(errp,
3416 "Unsupported TLS cred type %s",
3417 object_get_typename(OBJECT(tlscreds)));
3418 return -1;
3420 *auth = VNC_AUTH_VENCRYPT;
3421 if (password) {
3422 if (is_x509) {
3423 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3424 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3425 } else {
3426 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3427 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3430 } else if (sasl) {
3431 if (is_x509) {
3432 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3433 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3434 } else {
3435 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3436 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3438 } else {
3439 if (is_x509) {
3440 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3441 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3442 } else {
3443 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3444 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3448 return 0;
3453 * Handle back compat with old CLI syntax by creating some
3454 * suitable QCryptoTLSCreds objects
3456 static QCryptoTLSCreds *
3457 vnc_display_create_creds(bool x509,
3458 bool x509verify,
3459 const char *dir,
3460 const char *id,
3461 Error **errp)
3463 gchar *credsid = g_strdup_printf("tlsvnc%s", id);
3464 Object *parent = object_get_objects_root();
3465 Object *creds;
3466 Error *err = NULL;
3468 if (x509) {
3469 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
3470 parent,
3471 credsid,
3472 &err,
3473 "endpoint", "server",
3474 "dir", dir,
3475 "verify-peer", x509verify ? "yes" : "no",
3476 NULL);
3477 } else {
3478 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
3479 parent,
3480 credsid,
3481 &err,
3482 "endpoint", "server",
3483 NULL);
3486 g_free(credsid);
3488 if (err) {
3489 error_propagate(errp, err);
3490 return NULL;
3493 return QCRYPTO_TLS_CREDS(creds);
3497 static int vnc_display_get_address(const char *addrstr,
3498 bool websocket,
3499 bool reverse,
3500 int displaynum,
3501 int to,
3502 bool has_ipv4,
3503 bool has_ipv6,
3504 bool ipv4,
3505 bool ipv6,
3506 SocketAddress **retaddr,
3507 Error **errp)
3509 int ret = -1;
3510 SocketAddress *addr = NULL;
3512 addr = g_new0(SocketAddress, 1);
3514 if (strncmp(addrstr, "unix:", 5) == 0) {
3515 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3516 addr->u.q_unix.path = g_strdup(addrstr + 5);
3518 if (websocket) {
3519 error_setg(errp, "UNIX sockets not supported with websock");
3520 goto cleanup;
3523 if (to) {
3524 error_setg(errp, "Port range not support with UNIX socket");
3525 goto cleanup;
3527 ret = 0;
3528 } else {
3529 const char *port;
3530 size_t hostlen;
3531 unsigned long long baseport = 0;
3532 InetSocketAddress *inet;
3534 port = strrchr(addrstr, ':');
3535 if (!port) {
3536 if (websocket) {
3537 hostlen = 0;
3538 port = addrstr;
3539 } else {
3540 error_setg(errp, "no vnc port specified");
3541 goto cleanup;
3543 } else {
3544 hostlen = port - addrstr;
3545 port++;
3546 if (*port == '\0') {
3547 error_setg(errp, "vnc port cannot be empty");
3548 goto cleanup;
3552 addr->type = SOCKET_ADDRESS_TYPE_INET;
3553 inet = &addr->u.inet;
3554 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3555 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3556 } else {
3557 inet->host = g_strndup(addrstr, hostlen);
3559 /* plain VNC port is just an offset, for websocket
3560 * port is absolute */
3561 if (websocket) {
3562 if (g_str_equal(addrstr, "") ||
3563 g_str_equal(addrstr, "on")) {
3564 if (displaynum == -1) {
3565 error_setg(errp, "explicit websocket port is required");
3566 goto cleanup;
3568 inet->port = g_strdup_printf(
3569 "%d", displaynum + 5700);
3570 if (to) {
3571 inet->has_to = true;
3572 inet->to = to + 5700;
3574 } else {
3575 inet->port = g_strdup(port);
3577 } else {
3578 int offset = reverse ? 0 : 5900;
3579 if (parse_uint_full(port, &baseport, 10) < 0) {
3580 error_setg(errp, "can't convert to a number: %s", port);
3581 goto cleanup;
3583 if (baseport > 65535 ||
3584 baseport + offset > 65535) {
3585 error_setg(errp, "port %s out of range", port);
3586 goto cleanup;
3588 inet->port = g_strdup_printf(
3589 "%d", (int)baseport + offset);
3591 if (to) {
3592 inet->has_to = true;
3593 inet->to = to + offset;
3597 inet->ipv4 = ipv4;
3598 inet->has_ipv4 = has_ipv4;
3599 inet->ipv6 = ipv6;
3600 inet->has_ipv6 = has_ipv6;
3602 ret = baseport;
3605 *retaddr = addr;
3607 cleanup:
3608 if (ret < 0) {
3609 qapi_free_SocketAddress(addr);
3611 return ret;
3614 static void vnc_free_addresses(SocketAddress ***retsaddr,
3615 size_t *retnsaddr)
3617 size_t i;
3619 for (i = 0; i < *retnsaddr; i++) {
3620 qapi_free_SocketAddress((*retsaddr)[i]);
3622 g_free(*retsaddr);
3624 *retsaddr = NULL;
3625 *retnsaddr = 0;
3628 static int vnc_display_get_addresses(QemuOpts *opts,
3629 bool reverse,
3630 SocketAddress ***retsaddr,
3631 size_t *retnsaddr,
3632 SocketAddress ***retwsaddr,
3633 size_t *retnwsaddr,
3634 Error **errp)
3636 SocketAddress *saddr = NULL;
3637 SocketAddress *wsaddr = NULL;
3638 QemuOptsIter addriter;
3639 const char *addr;
3640 int to = qemu_opt_get_number(opts, "to", 0);
3641 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3642 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3643 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3644 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3645 int displaynum = -1;
3646 int ret = -1;
3648 *retsaddr = NULL;
3649 *retnsaddr = 0;
3650 *retwsaddr = NULL;
3651 *retnwsaddr = 0;
3653 addr = qemu_opt_get(opts, "vnc");
3654 if (addr == NULL || g_str_equal(addr, "none")) {
3655 ret = 0;
3656 goto cleanup;
3658 if (qemu_opt_get(opts, "websocket") &&
3659 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3660 error_setg(errp,
3661 "SHA1 hash support is required for websockets");
3662 goto cleanup;
3665 qemu_opt_iter_init(&addriter, opts, "vnc");
3666 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3667 int rv;
3668 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3669 has_ipv4, has_ipv6,
3670 ipv4, ipv6,
3671 &saddr, errp);
3672 if (rv < 0) {
3673 goto cleanup;
3675 /* Historical compat - first listen address can be used
3676 * to set the default websocket port
3678 if (displaynum == -1) {
3679 displaynum = rv;
3681 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3682 (*retsaddr)[(*retnsaddr)++] = saddr;
3685 /* If we had multiple primary displays, we don't do defaults
3686 * for websocket, and require explicit config instead. */
3687 if (*retnsaddr > 1) {
3688 displaynum = -1;
3691 qemu_opt_iter_init(&addriter, opts, "websocket");
3692 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3693 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3694 has_ipv4, has_ipv6,
3695 ipv4, ipv6,
3696 &wsaddr, errp) < 0) {
3697 goto cleanup;
3700 /* Historical compat - if only a single listen address was
3701 * provided, then this is used to set the default listen
3702 * address for websocket too
3704 if (*retnsaddr == 1 &&
3705 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3706 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3707 g_str_equal(wsaddr->u.inet.host, "") &&
3708 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3709 g_free(wsaddr->u.inet.host);
3710 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3713 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3714 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3717 ret = 0;
3718 cleanup:
3719 if (ret < 0) {
3720 vnc_free_addresses(retsaddr, retnsaddr);
3721 vnc_free_addresses(retwsaddr, retnwsaddr);
3723 return ret;
3726 static int vnc_display_connect(VncDisplay *vd,
3727 SocketAddress **saddr,
3728 size_t nsaddr,
3729 SocketAddress **wsaddr,
3730 size_t nwsaddr,
3731 Error **errp)
3733 /* connect to viewer */
3734 QIOChannelSocket *sioc = NULL;
3735 if (nwsaddr != 0) {
3736 error_setg(errp, "Cannot use websockets in reverse mode");
3737 return -1;
3739 if (nsaddr != 1) {
3740 error_setg(errp, "Expected a single address in reverse mode");
3741 return -1;
3743 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3744 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3745 sioc = qio_channel_socket_new();
3746 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3747 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3748 return -1;
3750 vnc_connect(vd, sioc, false, false);
3751 object_unref(OBJECT(sioc));
3752 return 0;
3756 static int vnc_display_listen_addr(VncDisplay *vd,
3757 SocketAddress *addr,
3758 const char *name,
3759 QIOChannelSocket ***lsock,
3760 guint **lsock_tag,
3761 size_t *nlsock,
3762 Error **errp)
3764 QIODNSResolver *resolver = qio_dns_resolver_get_instance();
3765 SocketAddress **rawaddrs = NULL;
3766 size_t nrawaddrs = 0;
3767 Error *listenerr = NULL;
3768 bool listening = false;
3769 size_t i;
3771 if (qio_dns_resolver_lookup_sync(resolver, addr, &nrawaddrs,
3772 &rawaddrs, errp) < 0) {
3773 return -1;
3776 for (i = 0; i < nrawaddrs; i++) {
3777 QIOChannelSocket *sioc = qio_channel_socket_new();
3779 qio_channel_set_name(QIO_CHANNEL(sioc), name);
3780 if (qio_channel_socket_listen_sync(
3781 sioc, rawaddrs[i], listenerr == NULL ? &listenerr : NULL) < 0) {
3782 object_unref(OBJECT(sioc));
3783 continue;
3785 listening = true;
3786 (*nlsock)++;
3787 *lsock = g_renew(QIOChannelSocket *, *lsock, *nlsock);
3788 *lsock_tag = g_renew(guint, *lsock_tag, *nlsock);
3790 (*lsock)[*nlsock - 1] = sioc;
3791 (*lsock_tag)[*nlsock - 1] = 0;
3794 for (i = 0; i < nrawaddrs; i++) {
3795 qapi_free_SocketAddress(rawaddrs[i]);
3797 g_free(rawaddrs);
3799 if (listenerr) {
3800 if (!listening) {
3801 error_propagate(errp, listenerr);
3802 return -1;
3803 } else {
3804 error_free(listenerr);
3808 for (i = 0; i < *nlsock; i++) {
3809 (*lsock_tag)[i] = qio_channel_add_watch(
3810 QIO_CHANNEL((*lsock)[i]),
3811 G_IO_IN, vnc_listen_io, vd, NULL);
3814 return 0;
3818 static int vnc_display_listen(VncDisplay *vd,
3819 SocketAddress **saddr,
3820 size_t nsaddr,
3821 SocketAddress **wsaddr,
3822 size_t nwsaddr,
3823 Error **errp)
3825 size_t i;
3827 for (i = 0; i < nsaddr; i++) {
3828 if (vnc_display_listen_addr(vd, saddr[i],
3829 "vnc-listen",
3830 &vd->lsock,
3831 &vd->lsock_tag,
3832 &vd->nlsock,
3833 errp) < 0) {
3834 return -1;
3837 for (i = 0; i < nwsaddr; i++) {
3838 if (vnc_display_listen_addr(vd, wsaddr[i],
3839 "vnc-ws-listen",
3840 &vd->lwebsock,
3841 &vd->lwebsock_tag,
3842 &vd->nlwebsock,
3843 errp) < 0) {
3844 return -1;
3848 return 0;
3852 void vnc_display_open(const char *id, Error **errp)
3854 VncDisplay *vd = vnc_display_find(id);
3855 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3856 SocketAddress **saddr = NULL, **wsaddr = NULL;
3857 size_t nsaddr, nwsaddr;
3858 const char *share, *device_id;
3859 QemuConsole *con;
3860 bool password = false;
3861 bool reverse = false;
3862 const char *credid;
3863 bool sasl = false;
3864 #ifdef CONFIG_VNC_SASL
3865 int saslErr;
3866 #endif
3867 int acl = 0;
3868 int lock_key_sync = 1;
3869 int key_delay_ms;
3871 if (!vd) {
3872 error_setg(errp, "VNC display not active");
3873 return;
3875 vnc_display_close(vd);
3877 if (!opts) {
3878 return;
3881 reverse = qemu_opt_get_bool(opts, "reverse", false);
3882 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3883 &wsaddr, &nwsaddr, errp) < 0) {
3884 goto fail;
3887 password = qemu_opt_get_bool(opts, "password", false);
3888 if (password) {
3889 if (fips_get_state()) {
3890 error_setg(errp,
3891 "VNC password auth disabled due to FIPS mode, "
3892 "consider using the VeNCrypt or SASL authentication "
3893 "methods as an alternative");
3894 goto fail;
3896 if (!qcrypto_cipher_supports(
3897 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3898 error_setg(errp,
3899 "Cipher backend does not support DES RFB algorithm");
3900 goto fail;
3904 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3905 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3906 sasl = qemu_opt_get_bool(opts, "sasl", false);
3907 #ifndef CONFIG_VNC_SASL
3908 if (sasl) {
3909 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3910 goto fail;
3912 #endif /* CONFIG_VNC_SASL */
3913 credid = qemu_opt_get(opts, "tls-creds");
3914 if (credid) {
3915 Object *creds;
3916 if (qemu_opt_get(opts, "tls") ||
3917 qemu_opt_get(opts, "x509") ||
3918 qemu_opt_get(opts, "x509verify")) {
3919 error_setg(errp,
3920 "'tls-creds' parameter is mutually exclusive with "
3921 "'tls', 'x509' and 'x509verify' parameters");
3922 goto fail;
3925 creds = object_resolve_path_component(
3926 object_get_objects_root(), credid);
3927 if (!creds) {
3928 error_setg(errp, "No TLS credentials with id '%s'",
3929 credid);
3930 goto fail;
3932 vd->tlscreds = (QCryptoTLSCreds *)
3933 object_dynamic_cast(creds,
3934 TYPE_QCRYPTO_TLS_CREDS);
3935 if (!vd->tlscreds) {
3936 error_setg(errp, "Object with id '%s' is not TLS credentials",
3937 credid);
3938 goto fail;
3940 object_ref(OBJECT(vd->tlscreds));
3942 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3943 error_setg(errp,
3944 "Expecting TLS credentials with a server endpoint");
3945 goto fail;
3947 } else {
3948 const char *path;
3949 bool tls = false, x509 = false, x509verify = false;
3950 tls = qemu_opt_get_bool(opts, "tls", false);
3951 if (tls) {
3952 path = qemu_opt_get(opts, "x509");
3954 if (path) {
3955 x509 = true;
3956 } else {
3957 path = qemu_opt_get(opts, "x509verify");
3958 if (path) {
3959 x509 = true;
3960 x509verify = true;
3963 vd->tlscreds = vnc_display_create_creds(x509,
3964 x509verify,
3965 path,
3966 vd->id,
3967 errp);
3968 if (!vd->tlscreds) {
3969 goto fail;
3973 acl = qemu_opt_get_bool(opts, "acl", false);
3975 share = qemu_opt_get(opts, "share");
3976 if (share) {
3977 if (strcmp(share, "ignore") == 0) {
3978 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
3979 } else if (strcmp(share, "allow-exclusive") == 0) {
3980 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3981 } else if (strcmp(share, "force-shared") == 0) {
3982 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3983 } else {
3984 error_setg(errp, "unknown vnc share= option");
3985 goto fail;
3987 } else {
3988 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3990 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3992 #ifdef CONFIG_VNC_JPEG
3993 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
3994 #endif
3995 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3996 /* adaptive updates are only used with tight encoding and
3997 * if lossy updates are enabled so we can disable all the
3998 * calculations otherwise */
3999 if (!vd->lossy) {
4000 vd->non_adaptive = true;
4003 if (acl) {
4004 if (strcmp(vd->id, "default") == 0) {
4005 vd->tlsaclname = g_strdup("vnc.x509dname");
4006 } else {
4007 vd->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vd->id);
4009 qemu_acl_init(vd->tlsaclname);
4011 #ifdef CONFIG_VNC_SASL
4012 if (acl && sasl) {
4013 char *aclname;
4015 if (strcmp(vd->id, "default") == 0) {
4016 aclname = g_strdup("vnc.username");
4017 } else {
4018 aclname = g_strdup_printf("vnc.%s.username", vd->id);
4020 vd->sasl.acl = qemu_acl_init(aclname);
4021 g_free(aclname);
4023 #endif
4025 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4026 vd->tlscreds, password,
4027 sasl, false, errp) < 0) {
4028 goto fail;
4030 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4032 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4033 vd->tlscreds, password,
4034 sasl, true, errp) < 0) {
4035 goto fail;
4037 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
4039 #ifdef CONFIG_VNC_SASL
4040 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
4041 error_setg(errp, "Failed to initialize SASL auth: %s",
4042 sasl_errstring(saslErr, NULL, NULL));
4043 goto fail;
4045 #endif
4046 vd->lock_key_sync = lock_key_sync;
4047 if (lock_key_sync) {
4048 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4050 vd->ledstate = 0;
4051 vd->key_delay_ms = key_delay_ms;
4053 device_id = qemu_opt_get(opts, "display");
4054 if (device_id) {
4055 int head = qemu_opt_get_number(opts, "head", 0);
4056 Error *err = NULL;
4058 con = qemu_console_lookup_by_device_name(device_id, head, &err);
4059 if (err) {
4060 error_propagate(errp, err);
4061 goto fail;
4063 } else {
4064 con = NULL;
4067 if (con != vd->dcl.con) {
4068 unregister_displaychangelistener(&vd->dcl);
4069 vd->dcl.con = con;
4070 register_displaychangelistener(&vd->dcl);
4073 if (saddr == NULL) {
4074 goto cleanup;
4077 if (reverse) {
4078 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4079 goto fail;
4081 } else {
4082 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4083 goto fail;
4087 if (qemu_opt_get(opts, "to")) {
4088 vnc_display_print_local_addr(vd);
4091 cleanup:
4092 vnc_free_addresses(&saddr, &nsaddr);
4093 vnc_free_addresses(&wsaddr, &nwsaddr);
4094 return;
4096 fail:
4097 vnc_display_close(vd);
4098 goto cleanup;
4101 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4103 VncDisplay *vd = vnc_display_find(id);
4104 QIOChannelSocket *sioc;
4106 if (!vd) {
4107 return;
4110 sioc = qio_channel_socket_new_fd(csock, NULL);
4111 if (sioc) {
4112 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4113 vnc_connect(vd, sioc, skipauth, false);
4114 object_unref(OBJECT(sioc));
4118 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4120 int i = 2;
4121 char *id;
4123 id = g_strdup("default");
4124 while (qemu_opts_find(olist, id)) {
4125 g_free(id);
4126 id = g_strdup_printf("vnc%d", i++);
4128 qemu_opts_set_id(opts, id);
4131 QemuOpts *vnc_parse(const char *str, Error **errp)
4133 QemuOptsList *olist = qemu_find_opts("vnc");
4134 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
4135 const char *id;
4137 if (!opts) {
4138 return NULL;
4141 id = qemu_opts_id(opts);
4142 if (!id) {
4143 /* auto-assign id if not present */
4144 vnc_auto_assign_id(olist, opts);
4146 return opts;
4149 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4151 Error *local_err = NULL;
4152 char *id = (char *)qemu_opts_id(opts);
4154 assert(id);
4155 vnc_display_init(id);
4156 vnc_display_open(id, &local_err);
4157 if (local_err != NULL) {
4158 error_reportf_err(local_err, "Failed to start VNC server: ");
4159 exit(1);
4161 return 0;
4164 static void vnc_register_config(void)
4166 qemu_add_opts(&qemu_vnc_opts);
4168 opts_init(vnc_register_config);