ui: fix VNC client throttling when audio capture is active
[qemu/ar7.git] / ui / vnc.c
blob9e03cc7c013d50f214a2b5c5a21620183f25bff2
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
1026 if (vs->output.offset < vs->throttle_output_offset) {
1027 return true;
1029 break;
1030 case VNC_STATE_UPDATE_FORCE:
1031 return true;
1033 return false;
1036 static int vnc_update_client(VncState *vs, int has_dirty)
1038 VncDisplay *vd = vs->vd;
1039 VncJob *job;
1040 int y;
1041 int height, width;
1042 int n = 0;
1044 if (vs->disconnecting) {
1045 vnc_disconnect_finish(vs);
1046 return 0;
1049 vs->has_dirty += has_dirty;
1050 if (!vnc_should_update(vs)) {
1051 return 0;
1054 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1055 return 0;
1059 * Send screen updates to the vnc client using the server
1060 * surface and server dirty map. guest surface updates
1061 * happening in parallel don't disturb us, the next pass will
1062 * send them to the client.
1064 job = vnc_job_new(vs);
1066 height = pixman_image_get_height(vd->server);
1067 width = pixman_image_get_width(vd->server);
1069 y = 0;
1070 for (;;) {
1071 int x, h;
1072 unsigned long x2;
1073 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1074 height * VNC_DIRTY_BPL(vs),
1075 y * VNC_DIRTY_BPL(vs));
1076 if (offset == height * VNC_DIRTY_BPL(vs)) {
1077 /* no more dirty bits */
1078 break;
1080 y = offset / VNC_DIRTY_BPL(vs);
1081 x = offset % VNC_DIRTY_BPL(vs);
1082 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1083 VNC_DIRTY_BPL(vs), x);
1084 bitmap_clear(vs->dirty[y], x, x2 - x);
1085 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1086 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1087 if (x2 > x) {
1088 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1089 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1091 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1092 y += h;
1093 if (y == height) {
1094 break;
1099 vnc_job_push(job);
1100 vs->update = VNC_STATE_UPDATE_NONE;
1101 vs->has_dirty = 0;
1102 return n;
1105 /* audio */
1106 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1108 VncState *vs = opaque;
1110 switch (cmd) {
1111 case AUD_CNOTIFY_DISABLE:
1112 vnc_lock_output(vs);
1113 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1114 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1115 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1116 vnc_unlock_output(vs);
1117 vnc_flush(vs);
1118 break;
1120 case AUD_CNOTIFY_ENABLE:
1121 vnc_lock_output(vs);
1122 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1123 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1124 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1125 vnc_unlock_output(vs);
1126 vnc_flush(vs);
1127 break;
1131 static void audio_capture_destroy(void *opaque)
1135 static void audio_capture(void *opaque, void *buf, int size)
1137 VncState *vs = opaque;
1139 vnc_lock_output(vs);
1140 if (vs->output.offset < vs->throttle_output_offset) {
1141 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1142 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1143 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1144 vnc_write_u32(vs, size);
1145 vnc_write(vs, buf, size);
1147 vnc_unlock_output(vs);
1148 vnc_flush(vs);
1151 static void audio_add(VncState *vs)
1153 struct audio_capture_ops ops;
1155 if (vs->audio_cap) {
1156 error_report("audio already running");
1157 return;
1160 ops.notify = audio_capture_notify;
1161 ops.destroy = audio_capture_destroy;
1162 ops.capture = audio_capture;
1164 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1165 if (!vs->audio_cap) {
1166 error_report("Failed to add audio capture");
1170 static void audio_del(VncState *vs)
1172 if (vs->audio_cap) {
1173 AUD_del_capture(vs->audio_cap, vs);
1174 vs->audio_cap = NULL;
1178 static void vnc_disconnect_start(VncState *vs)
1180 if (vs->disconnecting) {
1181 return;
1183 trace_vnc_client_disconnect_start(vs, vs->ioc);
1184 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1185 if (vs->ioc_tag) {
1186 g_source_remove(vs->ioc_tag);
1187 vs->ioc_tag = 0;
1189 qio_channel_close(vs->ioc, NULL);
1190 vs->disconnecting = TRUE;
1193 void vnc_disconnect_finish(VncState *vs)
1195 int i;
1197 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1199 vnc_jobs_join(vs); /* Wait encoding jobs */
1201 vnc_lock_output(vs);
1202 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1204 buffer_free(&vs->input);
1205 buffer_free(&vs->output);
1207 qapi_free_VncClientInfo(vs->info);
1209 vnc_zlib_clear(vs);
1210 vnc_tight_clear(vs);
1211 vnc_zrle_clear(vs);
1213 #ifdef CONFIG_VNC_SASL
1214 vnc_sasl_client_cleanup(vs);
1215 #endif /* CONFIG_VNC_SASL */
1216 audio_del(vs);
1217 vnc_release_modifiers(vs);
1219 if (vs->mouse_mode_notifier.notify != NULL) {
1220 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1222 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1223 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1224 /* last client gone */
1225 vnc_update_server_surface(vs->vd);
1228 vnc_unlock_output(vs);
1230 qemu_mutex_destroy(&vs->output_mutex);
1231 if (vs->bh != NULL) {
1232 qemu_bh_delete(vs->bh);
1234 buffer_free(&vs->jobs_buffer);
1236 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1237 g_free(vs->lossy_rect[i]);
1239 g_free(vs->lossy_rect);
1241 object_unref(OBJECT(vs->ioc));
1242 vs->ioc = NULL;
1243 object_unref(OBJECT(vs->sioc));
1244 vs->sioc = NULL;
1245 g_free(vs);
1248 ssize_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
1250 if (ret <= 0) {
1251 if (ret == 0) {
1252 trace_vnc_client_eof(vs, vs->ioc);
1253 vnc_disconnect_start(vs);
1254 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1255 trace_vnc_client_io_error(vs, vs->ioc,
1256 errp ? error_get_pretty(*errp) :
1257 "Unknown");
1258 vnc_disconnect_start(vs);
1261 if (errp) {
1262 error_free(*errp);
1263 *errp = NULL;
1265 return 0;
1267 return ret;
1271 void vnc_client_error(VncState *vs)
1273 VNC_DEBUG("Closing down client sock: protocol error\n");
1274 vnc_disconnect_start(vs);
1279 * Called to write a chunk of data to the client socket. The data may
1280 * be the raw data, or may have already been encoded by SASL.
1281 * The data will be written either straight onto the socket, or
1282 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1284 * NB, it is theoretically possible to have 2 layers of encryption,
1285 * both SASL, and this TLS layer. It is highly unlikely in practice
1286 * though, since SASL encryption will typically be a no-op if TLS
1287 * is active
1289 * Returns the number of bytes written, which may be less than
1290 * the requested 'datalen' if the socket would block. Returns
1291 * -1 on error, and disconnects the client socket.
1293 ssize_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1295 Error *err = NULL;
1296 ssize_t ret;
1297 ret = qio_channel_write(
1298 vs->ioc, (const char *)data, datalen, &err);
1299 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1300 return vnc_client_io_error(vs, ret, &err);
1305 * Called to write buffered data to the client socket, when not
1306 * using any SASL SSF encryption layers. Will write as much data
1307 * as possible without blocking. If all buffered data is written,
1308 * will switch the FD poll() handler back to read monitoring.
1310 * Returns the number of bytes written, which may be less than
1311 * the buffered output data if the socket would block. Returns
1312 * -1 on error, and disconnects the client socket.
1314 static ssize_t vnc_client_write_plain(VncState *vs)
1316 ssize_t ret;
1318 #ifdef CONFIG_VNC_SASL
1319 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1320 vs->output.buffer, vs->output.capacity, vs->output.offset,
1321 vs->sasl.waitWriteSSF);
1323 if (vs->sasl.conn &&
1324 vs->sasl.runSSF &&
1325 vs->sasl.waitWriteSSF) {
1326 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1327 if (ret)
1328 vs->sasl.waitWriteSSF -= ret;
1329 } else
1330 #endif /* CONFIG_VNC_SASL */
1331 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1332 if (!ret)
1333 return 0;
1335 buffer_advance(&vs->output, ret);
1337 if (vs->output.offset == 0) {
1338 if (vs->ioc_tag) {
1339 g_source_remove(vs->ioc_tag);
1341 vs->ioc_tag = qio_channel_add_watch(
1342 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1345 return ret;
1350 * First function called whenever there is data to be written to
1351 * the client socket. Will delegate actual work according to whether
1352 * SASL SSF layers are enabled (thus requiring encryption calls)
1354 static void vnc_client_write_locked(VncState *vs)
1356 #ifdef CONFIG_VNC_SASL
1357 if (vs->sasl.conn &&
1358 vs->sasl.runSSF &&
1359 !vs->sasl.waitWriteSSF) {
1360 vnc_client_write_sasl(vs);
1361 } else
1362 #endif /* CONFIG_VNC_SASL */
1364 vnc_client_write_plain(vs);
1368 static void vnc_client_write(VncState *vs)
1371 vnc_lock_output(vs);
1372 if (vs->output.offset) {
1373 vnc_client_write_locked(vs);
1374 } else if (vs->ioc != NULL) {
1375 if (vs->ioc_tag) {
1376 g_source_remove(vs->ioc_tag);
1378 vs->ioc_tag = qio_channel_add_watch(
1379 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1381 vnc_unlock_output(vs);
1384 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1386 vs->read_handler = func;
1387 vs->read_handler_expect = expecting;
1392 * Called to read a chunk of data from the client socket. The data may
1393 * be the raw data, or may need to be further decoded by SASL.
1394 * The data will be read either straight from to the socket, or
1395 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1397 * NB, it is theoretically possible to have 2 layers of encryption,
1398 * both SASL, and this TLS layer. It is highly unlikely in practice
1399 * though, since SASL encryption will typically be a no-op if TLS
1400 * is active
1402 * Returns the number of bytes read, which may be less than
1403 * the requested 'datalen' if the socket would block. Returns
1404 * -1 on error, and disconnects the client socket.
1406 ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1408 ssize_t ret;
1409 Error *err = NULL;
1410 ret = qio_channel_read(
1411 vs->ioc, (char *)data, datalen, &err);
1412 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1413 return vnc_client_io_error(vs, ret, &err);
1418 * Called to read data from the client socket to the input buffer,
1419 * when not using any SASL SSF encryption layers. Will read as much
1420 * data as possible without blocking.
1422 * Returns the number of bytes read. Returns -1 on error, and
1423 * disconnects the client socket.
1425 static ssize_t vnc_client_read_plain(VncState *vs)
1427 ssize_t ret;
1428 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1429 vs->input.buffer, vs->input.capacity, vs->input.offset);
1430 buffer_reserve(&vs->input, 4096);
1431 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1432 if (!ret)
1433 return 0;
1434 vs->input.offset += ret;
1435 return ret;
1438 static void vnc_jobs_bh(void *opaque)
1440 VncState *vs = opaque;
1442 vnc_jobs_consume_buffer(vs);
1446 * First function called whenever there is more data to be read from
1447 * the client socket. Will delegate actual work according to whether
1448 * SASL SSF layers are enabled (thus requiring decryption calls)
1449 * Returns 0 on success, -1 if client disconnected
1451 static int vnc_client_read(VncState *vs)
1453 ssize_t ret;
1455 #ifdef CONFIG_VNC_SASL
1456 if (vs->sasl.conn && vs->sasl.runSSF)
1457 ret = vnc_client_read_sasl(vs);
1458 else
1459 #endif /* CONFIG_VNC_SASL */
1460 ret = vnc_client_read_plain(vs);
1461 if (!ret) {
1462 if (vs->disconnecting) {
1463 vnc_disconnect_finish(vs);
1464 return -1;
1466 return 0;
1469 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1470 size_t len = vs->read_handler_expect;
1471 int ret;
1473 ret = vs->read_handler(vs, vs->input.buffer, len);
1474 if (vs->disconnecting) {
1475 vnc_disconnect_finish(vs);
1476 return -1;
1479 if (!ret) {
1480 buffer_advance(&vs->input, len);
1481 } else {
1482 vs->read_handler_expect = ret;
1485 return 0;
1488 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1489 GIOCondition condition, void *opaque)
1491 VncState *vs = opaque;
1492 if (condition & G_IO_IN) {
1493 if (vnc_client_read(vs) < 0) {
1494 return TRUE;
1497 if (condition & G_IO_OUT) {
1498 vnc_client_write(vs);
1500 return TRUE;
1504 void vnc_write(VncState *vs, const void *data, size_t len)
1506 buffer_reserve(&vs->output, len);
1508 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1509 if (vs->ioc_tag) {
1510 g_source_remove(vs->ioc_tag);
1512 vs->ioc_tag = qio_channel_add_watch(
1513 vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1516 buffer_append(&vs->output, data, len);
1519 void vnc_write_s32(VncState *vs, int32_t value)
1521 vnc_write_u32(vs, *(uint32_t *)&value);
1524 void vnc_write_u32(VncState *vs, uint32_t value)
1526 uint8_t buf[4];
1528 buf[0] = (value >> 24) & 0xFF;
1529 buf[1] = (value >> 16) & 0xFF;
1530 buf[2] = (value >> 8) & 0xFF;
1531 buf[3] = value & 0xFF;
1533 vnc_write(vs, buf, 4);
1536 void vnc_write_u16(VncState *vs, uint16_t value)
1538 uint8_t buf[2];
1540 buf[0] = (value >> 8) & 0xFF;
1541 buf[1] = value & 0xFF;
1543 vnc_write(vs, buf, 2);
1546 void vnc_write_u8(VncState *vs, uint8_t value)
1548 vnc_write(vs, (char *)&value, 1);
1551 void vnc_flush(VncState *vs)
1553 vnc_lock_output(vs);
1554 if (vs->ioc != NULL && vs->output.offset) {
1555 vnc_client_write_locked(vs);
1557 vnc_unlock_output(vs);
1560 static uint8_t read_u8(uint8_t *data, size_t offset)
1562 return data[offset];
1565 static uint16_t read_u16(uint8_t *data, size_t offset)
1567 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1570 static int32_t read_s32(uint8_t *data, size_t offset)
1572 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1573 (data[offset + 2] << 8) | data[offset + 3]);
1576 uint32_t read_u32(uint8_t *data, size_t offset)
1578 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1579 (data[offset + 2] << 8) | data[offset + 3]);
1582 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1586 static void check_pointer_type_change(Notifier *notifier, void *data)
1588 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1589 int absolute = qemu_input_is_absolute();
1591 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1592 vnc_lock_output(vs);
1593 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1594 vnc_write_u8(vs, 0);
1595 vnc_write_u16(vs, 1);
1596 vnc_framebuffer_update(vs, absolute, 0,
1597 pixman_image_get_width(vs->vd->server),
1598 pixman_image_get_height(vs->vd->server),
1599 VNC_ENCODING_POINTER_TYPE_CHANGE);
1600 vnc_unlock_output(vs);
1601 vnc_flush(vs);
1603 vs->absolute = absolute;
1606 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1608 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1609 [INPUT_BUTTON_LEFT] = 0x01,
1610 [INPUT_BUTTON_MIDDLE] = 0x02,
1611 [INPUT_BUTTON_RIGHT] = 0x04,
1612 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1613 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1615 QemuConsole *con = vs->vd->dcl.con;
1616 int width = pixman_image_get_width(vs->vd->server);
1617 int height = pixman_image_get_height(vs->vd->server);
1619 if (vs->last_bmask != button_mask) {
1620 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1621 vs->last_bmask = button_mask;
1624 if (vs->absolute) {
1625 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1626 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1627 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1628 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1629 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1630 } else {
1631 if (vs->last_x != -1) {
1632 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1633 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1635 vs->last_x = x;
1636 vs->last_y = y;
1638 qemu_input_event_sync();
1641 static void reset_keys(VncState *vs)
1643 int i;
1644 for(i = 0; i < 256; i++) {
1645 if (vs->modifiers_state[i]) {
1646 qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1647 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1648 vs->modifiers_state[i] = 0;
1653 static void press_key(VncState *vs, int keysym)
1655 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1656 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1657 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1658 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1659 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1662 static void vnc_led_state_change(VncState *vs)
1664 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1665 return;
1668 vnc_lock_output(vs);
1669 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1670 vnc_write_u8(vs, 0);
1671 vnc_write_u16(vs, 1);
1672 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1673 vnc_write_u8(vs, vs->vd->ledstate);
1674 vnc_unlock_output(vs);
1675 vnc_flush(vs);
1678 static void kbd_leds(void *opaque, int ledstate)
1680 VncDisplay *vd = opaque;
1681 VncState *client;
1683 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1684 (ledstate & QEMU_NUM_LOCK_LED),
1685 (ledstate & QEMU_SCROLL_LOCK_LED));
1687 if (ledstate == vd->ledstate) {
1688 return;
1691 vd->ledstate = ledstate;
1693 QTAILQ_FOREACH(client, &vd->clients, next) {
1694 vnc_led_state_change(client);
1698 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1700 /* QEMU console switch */
1701 switch(keycode) {
1702 case 0x2a: /* Left Shift */
1703 case 0x36: /* Right Shift */
1704 case 0x1d: /* Left CTRL */
1705 case 0x9d: /* Right CTRL */
1706 case 0x38: /* Left ALT */
1707 case 0xb8: /* Right ALT */
1708 if (down)
1709 vs->modifiers_state[keycode] = 1;
1710 else
1711 vs->modifiers_state[keycode] = 0;
1712 break;
1713 case 0x02 ... 0x0a: /* '1' to '9' keys */
1714 if (vs->vd->dcl.con == NULL &&
1715 down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1716 /* Reset the modifiers sent to the current console */
1717 reset_keys(vs);
1718 console_select(keycode - 0x02);
1719 return;
1721 break;
1722 case 0x3a: /* CapsLock */
1723 case 0x45: /* NumLock */
1724 if (down)
1725 vs->modifiers_state[keycode] ^= 1;
1726 break;
1729 /* Turn off the lock state sync logic if the client support the led
1730 state extension.
1732 if (down && vs->vd->lock_key_sync &&
1733 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1734 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1735 /* If the numlock state needs to change then simulate an additional
1736 keypress before sending this one. This will happen if the user
1737 toggles numlock away from the VNC window.
1739 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1740 if (!vs->modifiers_state[0x45]) {
1741 trace_vnc_key_sync_numlock(true);
1742 vs->modifiers_state[0x45] = 1;
1743 press_key(vs, 0xff7f);
1745 } else {
1746 if (vs->modifiers_state[0x45]) {
1747 trace_vnc_key_sync_numlock(false);
1748 vs->modifiers_state[0x45] = 0;
1749 press_key(vs, 0xff7f);
1754 if (down && vs->vd->lock_key_sync &&
1755 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1756 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1757 /* If the capslock state needs to change then simulate an additional
1758 keypress before sending this one. This will happen if the user
1759 toggles capslock away from the VNC window.
1761 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1762 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1763 int capslock = !!(vs->modifiers_state[0x3a]);
1764 if (capslock) {
1765 if (uppercase == shift) {
1766 trace_vnc_key_sync_capslock(false);
1767 vs->modifiers_state[0x3a] = 0;
1768 press_key(vs, 0xffe5);
1770 } else {
1771 if (uppercase != shift) {
1772 trace_vnc_key_sync_capslock(true);
1773 vs->modifiers_state[0x3a] = 1;
1774 press_key(vs, 0xffe5);
1779 if (qemu_console_is_graphic(NULL)) {
1780 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1781 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1782 } else {
1783 bool numlock = vs->modifiers_state[0x45];
1784 bool control = (vs->modifiers_state[0x1d] ||
1785 vs->modifiers_state[0x9d]);
1786 /* QEMU console emulation */
1787 if (down) {
1788 switch (keycode) {
1789 case 0x2a: /* Left Shift */
1790 case 0x36: /* Right Shift */
1791 case 0x1d: /* Left CTRL */
1792 case 0x9d: /* Right CTRL */
1793 case 0x38: /* Left ALT */
1794 case 0xb8: /* Right ALT */
1795 break;
1796 case 0xc8:
1797 kbd_put_keysym(QEMU_KEY_UP);
1798 break;
1799 case 0xd0:
1800 kbd_put_keysym(QEMU_KEY_DOWN);
1801 break;
1802 case 0xcb:
1803 kbd_put_keysym(QEMU_KEY_LEFT);
1804 break;
1805 case 0xcd:
1806 kbd_put_keysym(QEMU_KEY_RIGHT);
1807 break;
1808 case 0xd3:
1809 kbd_put_keysym(QEMU_KEY_DELETE);
1810 break;
1811 case 0xc7:
1812 kbd_put_keysym(QEMU_KEY_HOME);
1813 break;
1814 case 0xcf:
1815 kbd_put_keysym(QEMU_KEY_END);
1816 break;
1817 case 0xc9:
1818 kbd_put_keysym(QEMU_KEY_PAGEUP);
1819 break;
1820 case 0xd1:
1821 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1822 break;
1824 case 0x47:
1825 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1826 break;
1827 case 0x48:
1828 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1829 break;
1830 case 0x49:
1831 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1832 break;
1833 case 0x4b:
1834 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1835 break;
1836 case 0x4c:
1837 kbd_put_keysym('5');
1838 break;
1839 case 0x4d:
1840 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1841 break;
1842 case 0x4f:
1843 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1844 break;
1845 case 0x50:
1846 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1847 break;
1848 case 0x51:
1849 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1850 break;
1851 case 0x52:
1852 kbd_put_keysym('0');
1853 break;
1854 case 0x53:
1855 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1856 break;
1858 case 0xb5:
1859 kbd_put_keysym('/');
1860 break;
1861 case 0x37:
1862 kbd_put_keysym('*');
1863 break;
1864 case 0x4a:
1865 kbd_put_keysym('-');
1866 break;
1867 case 0x4e:
1868 kbd_put_keysym('+');
1869 break;
1870 case 0x9c:
1871 kbd_put_keysym('\n');
1872 break;
1874 default:
1875 if (control) {
1876 kbd_put_keysym(sym & 0x1f);
1877 } else {
1878 kbd_put_keysym(sym);
1880 break;
1886 static void vnc_release_modifiers(VncState *vs)
1888 static const int keycodes[] = {
1889 /* shift, control, alt keys, both left & right */
1890 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1892 int i, keycode;
1894 if (!qemu_console_is_graphic(NULL)) {
1895 return;
1897 for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1898 keycode = keycodes[i];
1899 if (!vs->modifiers_state[keycode]) {
1900 continue;
1902 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1903 qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
1907 static const char *code2name(int keycode)
1909 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
1912 static void key_event(VncState *vs, int down, uint32_t sym)
1914 int keycode;
1915 int lsym = sym;
1917 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1918 lsym = lsym - 'A' + 'a';
1921 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1922 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1923 do_key_event(vs, down, keycode, sym);
1926 static void ext_key_event(VncState *vs, int down,
1927 uint32_t sym, uint16_t keycode)
1929 /* if the user specifies a keyboard layout, always use it */
1930 if (keyboard_layout) {
1931 key_event(vs, down, sym);
1932 } else {
1933 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
1934 do_key_event(vs, down, keycode, sym);
1938 static void framebuffer_update_request(VncState *vs, int incremental,
1939 int x, int y, int w, int h)
1941 if (incremental) {
1942 if (vs->update != VNC_STATE_UPDATE_FORCE) {
1943 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
1945 } else {
1946 vs->update = VNC_STATE_UPDATE_FORCE;
1947 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
1951 static void send_ext_key_event_ack(VncState *vs)
1953 vnc_lock_output(vs);
1954 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1955 vnc_write_u8(vs, 0);
1956 vnc_write_u16(vs, 1);
1957 vnc_framebuffer_update(vs, 0, 0,
1958 pixman_image_get_width(vs->vd->server),
1959 pixman_image_get_height(vs->vd->server),
1960 VNC_ENCODING_EXT_KEY_EVENT);
1961 vnc_unlock_output(vs);
1962 vnc_flush(vs);
1965 static void send_ext_audio_ack(VncState *vs)
1967 vnc_lock_output(vs);
1968 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1969 vnc_write_u8(vs, 0);
1970 vnc_write_u16(vs, 1);
1971 vnc_framebuffer_update(vs, 0, 0,
1972 pixman_image_get_width(vs->vd->server),
1973 pixman_image_get_height(vs->vd->server),
1974 VNC_ENCODING_AUDIO);
1975 vnc_unlock_output(vs);
1976 vnc_flush(vs);
1979 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1981 int i;
1982 unsigned int enc = 0;
1984 vs->features = 0;
1985 vs->vnc_encoding = 0;
1986 vs->tight.compression = 9;
1987 vs->tight.quality = -1; /* Lossless by default */
1988 vs->absolute = -1;
1991 * Start from the end because the encodings are sent in order of preference.
1992 * This way the preferred encoding (first encoding defined in the array)
1993 * will be set at the end of the loop.
1995 for (i = n_encodings - 1; i >= 0; i--) {
1996 enc = encodings[i];
1997 switch (enc) {
1998 case VNC_ENCODING_RAW:
1999 vs->vnc_encoding = enc;
2000 break;
2001 case VNC_ENCODING_COPYRECT:
2002 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2003 break;
2004 case VNC_ENCODING_HEXTILE:
2005 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2006 vs->vnc_encoding = enc;
2007 break;
2008 case VNC_ENCODING_TIGHT:
2009 vs->features |= VNC_FEATURE_TIGHT_MASK;
2010 vs->vnc_encoding = enc;
2011 break;
2012 #ifdef CONFIG_VNC_PNG
2013 case VNC_ENCODING_TIGHT_PNG:
2014 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2015 vs->vnc_encoding = enc;
2016 break;
2017 #endif
2018 case VNC_ENCODING_ZLIB:
2019 vs->features |= VNC_FEATURE_ZLIB_MASK;
2020 vs->vnc_encoding = enc;
2021 break;
2022 case VNC_ENCODING_ZRLE:
2023 vs->features |= VNC_FEATURE_ZRLE_MASK;
2024 vs->vnc_encoding = enc;
2025 break;
2026 case VNC_ENCODING_ZYWRLE:
2027 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2028 vs->vnc_encoding = enc;
2029 break;
2030 case VNC_ENCODING_DESKTOPRESIZE:
2031 vs->features |= VNC_FEATURE_RESIZE_MASK;
2032 break;
2033 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2034 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2035 break;
2036 case VNC_ENCODING_RICH_CURSOR:
2037 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2038 if (vs->vd->cursor) {
2039 vnc_cursor_define(vs);
2041 break;
2042 case VNC_ENCODING_EXT_KEY_EVENT:
2043 send_ext_key_event_ack(vs);
2044 break;
2045 case VNC_ENCODING_AUDIO:
2046 send_ext_audio_ack(vs);
2047 break;
2048 case VNC_ENCODING_WMVi:
2049 vs->features |= VNC_FEATURE_WMVI_MASK;
2050 break;
2051 case VNC_ENCODING_LED_STATE:
2052 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2053 break;
2054 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2055 vs->tight.compression = (enc & 0x0F);
2056 break;
2057 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2058 if (vs->vd->lossy) {
2059 vs->tight.quality = (enc & 0x0F);
2061 break;
2062 default:
2063 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2064 break;
2067 vnc_desktop_resize(vs);
2068 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2069 vnc_led_state_change(vs);
2072 static void set_pixel_conversion(VncState *vs)
2074 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2076 if (fmt == VNC_SERVER_FB_FORMAT) {
2077 vs->write_pixels = vnc_write_pixels_copy;
2078 vnc_hextile_set_pixel_conversion(vs, 0);
2079 } else {
2080 vs->write_pixels = vnc_write_pixels_generic;
2081 vnc_hextile_set_pixel_conversion(vs, 1);
2085 static void send_color_map(VncState *vs)
2087 int i;
2089 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2090 vnc_write_u8(vs, 0); /* padding */
2091 vnc_write_u16(vs, 0); /* first color */
2092 vnc_write_u16(vs, 256); /* # of colors */
2094 for (i = 0; i < 256; i++) {
2095 PixelFormat *pf = &vs->client_pf;
2097 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2098 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2099 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2103 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2104 int big_endian_flag, int true_color_flag,
2105 int red_max, int green_max, int blue_max,
2106 int red_shift, int green_shift, int blue_shift)
2108 if (!true_color_flag) {
2109 /* Expose a reasonable default 256 color map */
2110 bits_per_pixel = 8;
2111 red_max = 7;
2112 green_max = 7;
2113 blue_max = 3;
2114 red_shift = 0;
2115 green_shift = 3;
2116 blue_shift = 6;
2119 switch (bits_per_pixel) {
2120 case 8:
2121 case 16:
2122 case 32:
2123 break;
2124 default:
2125 vnc_client_error(vs);
2126 return;
2129 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2130 vs->client_pf.rbits = ctpopl(red_max);
2131 vs->client_pf.rshift = red_shift;
2132 vs->client_pf.rmask = red_max << red_shift;
2133 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2134 vs->client_pf.gbits = ctpopl(green_max);
2135 vs->client_pf.gshift = green_shift;
2136 vs->client_pf.gmask = green_max << green_shift;
2137 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2138 vs->client_pf.bbits = ctpopl(blue_max);
2139 vs->client_pf.bshift = blue_shift;
2140 vs->client_pf.bmask = blue_max << blue_shift;
2141 vs->client_pf.bits_per_pixel = bits_per_pixel;
2142 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2143 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2144 vs->client_be = big_endian_flag;
2146 if (!true_color_flag) {
2147 send_color_map(vs);
2150 set_pixel_conversion(vs);
2152 graphic_hw_invalidate(vs->vd->dcl.con);
2153 graphic_hw_update(vs->vd->dcl.con);
2156 static void pixel_format_message (VncState *vs) {
2157 char pad[3] = { 0, 0, 0 };
2159 vs->client_pf = qemu_default_pixelformat(32);
2161 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2162 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2164 #ifdef HOST_WORDS_BIGENDIAN
2165 vnc_write_u8(vs, 1); /* big-endian-flag */
2166 #else
2167 vnc_write_u8(vs, 0); /* big-endian-flag */
2168 #endif
2169 vnc_write_u8(vs, 1); /* true-color-flag */
2170 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2171 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2172 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2173 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2174 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2175 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2176 vnc_write(vs, pad, 3); /* padding */
2178 vnc_hextile_set_pixel_conversion(vs, 0);
2179 vs->write_pixels = vnc_write_pixels_copy;
2182 static void vnc_colordepth(VncState *vs)
2184 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2185 /* Sending a WMVi message to notify the client*/
2186 vnc_lock_output(vs);
2187 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2188 vnc_write_u8(vs, 0);
2189 vnc_write_u16(vs, 1); /* number of rects */
2190 vnc_framebuffer_update(vs, 0, 0,
2191 pixman_image_get_width(vs->vd->server),
2192 pixman_image_get_height(vs->vd->server),
2193 VNC_ENCODING_WMVi);
2194 pixel_format_message(vs);
2195 vnc_unlock_output(vs);
2196 vnc_flush(vs);
2197 } else {
2198 set_pixel_conversion(vs);
2202 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2204 int i;
2205 uint16_t limit;
2206 VncDisplay *vd = vs->vd;
2208 if (data[0] > 3) {
2209 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2212 switch (data[0]) {
2213 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2214 if (len == 1)
2215 return 20;
2217 set_pixel_format(vs, read_u8(data, 4),
2218 read_u8(data, 6), read_u8(data, 7),
2219 read_u16(data, 8), read_u16(data, 10),
2220 read_u16(data, 12), read_u8(data, 14),
2221 read_u8(data, 15), read_u8(data, 16));
2222 break;
2223 case VNC_MSG_CLIENT_SET_ENCODINGS:
2224 if (len == 1)
2225 return 4;
2227 if (len == 4) {
2228 limit = read_u16(data, 2);
2229 if (limit > 0)
2230 return 4 + (limit * 4);
2231 } else
2232 limit = read_u16(data, 2);
2234 for (i = 0; i < limit; i++) {
2235 int32_t val = read_s32(data, 4 + (i * 4));
2236 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2239 set_encodings(vs, (int32_t *)(data + 4), limit);
2240 break;
2241 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2242 if (len == 1)
2243 return 10;
2245 framebuffer_update_request(vs,
2246 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2247 read_u16(data, 6), read_u16(data, 8));
2248 break;
2249 case VNC_MSG_CLIENT_KEY_EVENT:
2250 if (len == 1)
2251 return 8;
2253 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2254 break;
2255 case VNC_MSG_CLIENT_POINTER_EVENT:
2256 if (len == 1)
2257 return 6;
2259 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2260 break;
2261 case VNC_MSG_CLIENT_CUT_TEXT:
2262 if (len == 1) {
2263 return 8;
2265 if (len == 8) {
2266 uint32_t dlen = read_u32(data, 4);
2267 if (dlen > (1 << 20)) {
2268 error_report("vnc: client_cut_text msg payload has %u bytes"
2269 " which exceeds our limit of 1MB.", dlen);
2270 vnc_client_error(vs);
2271 break;
2273 if (dlen > 0) {
2274 return 8 + dlen;
2278 client_cut_text(vs, read_u32(data, 4), data + 8);
2279 break;
2280 case VNC_MSG_CLIENT_QEMU:
2281 if (len == 1)
2282 return 2;
2284 switch (read_u8(data, 1)) {
2285 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2286 if (len == 2)
2287 return 12;
2289 ext_key_event(vs, read_u16(data, 2),
2290 read_u32(data, 4), read_u32(data, 8));
2291 break;
2292 case VNC_MSG_CLIENT_QEMU_AUDIO:
2293 if (len == 2)
2294 return 4;
2296 switch (read_u16 (data, 2)) {
2297 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2298 audio_add(vs);
2299 break;
2300 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2301 audio_del(vs);
2302 break;
2303 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2304 if (len == 4)
2305 return 10;
2306 switch (read_u8(data, 4)) {
2307 case 0: vs->as.fmt = AUD_FMT_U8; break;
2308 case 1: vs->as.fmt = AUD_FMT_S8; break;
2309 case 2: vs->as.fmt = AUD_FMT_U16; break;
2310 case 3: vs->as.fmt = AUD_FMT_S16; break;
2311 case 4: vs->as.fmt = AUD_FMT_U32; break;
2312 case 5: vs->as.fmt = AUD_FMT_S32; break;
2313 default:
2314 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2315 vnc_client_error(vs);
2316 break;
2318 vs->as.nchannels = read_u8(data, 5);
2319 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2320 VNC_DEBUG("Invalid audio channel count %d\n",
2321 read_u8(data, 5));
2322 vnc_client_error(vs);
2323 break;
2325 vs->as.freq = read_u32(data, 6);
2326 break;
2327 default:
2328 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2329 vnc_client_error(vs);
2330 break;
2332 break;
2334 default:
2335 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2336 vnc_client_error(vs);
2337 break;
2339 break;
2340 default:
2341 VNC_DEBUG("Msg: %d\n", data[0]);
2342 vnc_client_error(vs);
2343 break;
2346 vnc_update_throttle_offset(vs);
2347 vnc_read_when(vs, protocol_client_msg, 1);
2348 return 0;
2351 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2353 char buf[1024];
2354 VncShareMode mode;
2355 int size;
2357 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2358 switch (vs->vd->share_policy) {
2359 case VNC_SHARE_POLICY_IGNORE:
2361 * Ignore the shared flag. Nothing to do here.
2363 * Doesn't conform to the rfb spec but is traditional qemu
2364 * behavior, thus left here as option for compatibility
2365 * reasons.
2367 break;
2368 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2370 * Policy: Allow clients ask for exclusive access.
2372 * Implementation: When a client asks for exclusive access,
2373 * disconnect all others. Shared connects are allowed as long
2374 * as no exclusive connection exists.
2376 * This is how the rfb spec suggests to handle the shared flag.
2378 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2379 VncState *client;
2380 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2381 if (vs == client) {
2382 continue;
2384 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2385 client->share_mode != VNC_SHARE_MODE_SHARED) {
2386 continue;
2388 vnc_disconnect_start(client);
2391 if (mode == VNC_SHARE_MODE_SHARED) {
2392 if (vs->vd->num_exclusive > 0) {
2393 vnc_disconnect_start(vs);
2394 return 0;
2397 break;
2398 case VNC_SHARE_POLICY_FORCE_SHARED:
2400 * Policy: Shared connects only.
2401 * Implementation: Disallow clients asking for exclusive access.
2403 * Useful for shared desktop sessions where you don't want
2404 * someone forgetting to say -shared when running the vnc
2405 * client disconnect everybody else.
2407 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2408 vnc_disconnect_start(vs);
2409 return 0;
2411 break;
2413 vnc_set_share_mode(vs, mode);
2415 if (vs->vd->num_shared > vs->vd->connections_limit) {
2416 vnc_disconnect_start(vs);
2417 return 0;
2420 vs->client_width = pixman_image_get_width(vs->vd->server);
2421 vs->client_height = pixman_image_get_height(vs->vd->server);
2422 vnc_write_u16(vs, vs->client_width);
2423 vnc_write_u16(vs, vs->client_height);
2425 pixel_format_message(vs);
2427 if (qemu_name) {
2428 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2429 if (size > sizeof(buf)) {
2430 size = sizeof(buf);
2432 } else {
2433 size = snprintf(buf, sizeof(buf), "QEMU");
2436 vnc_write_u32(vs, size);
2437 vnc_write(vs, buf, size);
2438 vnc_flush(vs);
2440 vnc_client_cache_auth(vs);
2441 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2443 vnc_read_when(vs, protocol_client_msg, 1);
2445 return 0;
2448 void start_client_init(VncState *vs)
2450 vnc_read_when(vs, protocol_client_init, 1);
2453 static void make_challenge(VncState *vs)
2455 int i;
2457 srand(time(NULL)+getpid()+getpid()*987654+rand());
2459 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2460 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2463 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2465 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2466 size_t i, pwlen;
2467 unsigned char key[8];
2468 time_t now = time(NULL);
2469 QCryptoCipher *cipher = NULL;
2470 Error *err = NULL;
2472 if (!vs->vd->password) {
2473 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2474 goto reject;
2476 if (vs->vd->expires < now) {
2477 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2478 goto reject;
2481 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2483 /* Calculate the expected challenge response */
2484 pwlen = strlen(vs->vd->password);
2485 for (i=0; i<sizeof(key); i++)
2486 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2488 cipher = qcrypto_cipher_new(
2489 QCRYPTO_CIPHER_ALG_DES_RFB,
2490 QCRYPTO_CIPHER_MODE_ECB,
2491 key, G_N_ELEMENTS(key),
2492 &err);
2493 if (!cipher) {
2494 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2495 error_get_pretty(err));
2496 error_free(err);
2497 goto reject;
2500 if (qcrypto_cipher_encrypt(cipher,
2501 vs->challenge,
2502 response,
2503 VNC_AUTH_CHALLENGE_SIZE,
2504 &err) < 0) {
2505 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2506 error_get_pretty(err));
2507 error_free(err);
2508 goto reject;
2511 /* Compare expected vs actual challenge response */
2512 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2513 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2514 goto reject;
2515 } else {
2516 trace_vnc_auth_pass(vs, vs->auth);
2517 vnc_write_u32(vs, 0); /* Accept auth */
2518 vnc_flush(vs);
2520 start_client_init(vs);
2523 qcrypto_cipher_free(cipher);
2524 return 0;
2526 reject:
2527 vnc_write_u32(vs, 1); /* Reject auth */
2528 if (vs->minor >= 8) {
2529 static const char err[] = "Authentication failed";
2530 vnc_write_u32(vs, sizeof(err));
2531 vnc_write(vs, err, sizeof(err));
2533 vnc_flush(vs);
2534 vnc_client_error(vs);
2535 qcrypto_cipher_free(cipher);
2536 return 0;
2539 void start_auth_vnc(VncState *vs)
2541 make_challenge(vs);
2542 /* Send client a 'random' challenge */
2543 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2544 vnc_flush(vs);
2546 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2550 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2552 /* We only advertise 1 auth scheme at a time, so client
2553 * must pick the one we sent. Verify this */
2554 if (data[0] != vs->auth) { /* Reject auth */
2555 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2556 vnc_write_u32(vs, 1);
2557 if (vs->minor >= 8) {
2558 static const char err[] = "Authentication failed";
2559 vnc_write_u32(vs, sizeof(err));
2560 vnc_write(vs, err, sizeof(err));
2562 vnc_client_error(vs);
2563 } else { /* Accept requested auth */
2564 trace_vnc_auth_start(vs, vs->auth);
2565 switch (vs->auth) {
2566 case VNC_AUTH_NONE:
2567 if (vs->minor >= 8) {
2568 vnc_write_u32(vs, 0); /* Accept auth completion */
2569 vnc_flush(vs);
2571 trace_vnc_auth_pass(vs, vs->auth);
2572 start_client_init(vs);
2573 break;
2575 case VNC_AUTH_VNC:
2576 start_auth_vnc(vs);
2577 break;
2579 case VNC_AUTH_VENCRYPT:
2580 start_auth_vencrypt(vs);
2581 break;
2583 #ifdef CONFIG_VNC_SASL
2584 case VNC_AUTH_SASL:
2585 start_auth_sasl(vs);
2586 break;
2587 #endif /* CONFIG_VNC_SASL */
2589 default: /* Should not be possible, but just in case */
2590 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2591 vnc_write_u8(vs, 1);
2592 if (vs->minor >= 8) {
2593 static const char err[] = "Authentication failed";
2594 vnc_write_u32(vs, sizeof(err));
2595 vnc_write(vs, err, sizeof(err));
2597 vnc_client_error(vs);
2600 return 0;
2603 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2605 char local[13];
2607 memcpy(local, version, 12);
2608 local[12] = 0;
2610 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2611 VNC_DEBUG("Malformed protocol version %s\n", local);
2612 vnc_client_error(vs);
2613 return 0;
2615 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2616 if (vs->major != 3 ||
2617 (vs->minor != 3 &&
2618 vs->minor != 4 &&
2619 vs->minor != 5 &&
2620 vs->minor != 7 &&
2621 vs->minor != 8)) {
2622 VNC_DEBUG("Unsupported client version\n");
2623 vnc_write_u32(vs, VNC_AUTH_INVALID);
2624 vnc_flush(vs);
2625 vnc_client_error(vs);
2626 return 0;
2628 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2629 * as equivalent to v3.3 by servers
2631 if (vs->minor == 4 || vs->minor == 5)
2632 vs->minor = 3;
2634 if (vs->minor == 3) {
2635 trace_vnc_auth_start(vs, vs->auth);
2636 if (vs->auth == VNC_AUTH_NONE) {
2637 vnc_write_u32(vs, vs->auth);
2638 vnc_flush(vs);
2639 trace_vnc_auth_pass(vs, vs->auth);
2640 start_client_init(vs);
2641 } else if (vs->auth == VNC_AUTH_VNC) {
2642 VNC_DEBUG("Tell client VNC auth\n");
2643 vnc_write_u32(vs, vs->auth);
2644 vnc_flush(vs);
2645 start_auth_vnc(vs);
2646 } else {
2647 trace_vnc_auth_fail(vs, vs->auth,
2648 "Unsupported auth method for v3.3", "");
2649 vnc_write_u32(vs, VNC_AUTH_INVALID);
2650 vnc_flush(vs);
2651 vnc_client_error(vs);
2653 } else {
2654 vnc_write_u8(vs, 1); /* num auth */
2655 vnc_write_u8(vs, vs->auth);
2656 vnc_read_when(vs, protocol_client_auth, 1);
2657 vnc_flush(vs);
2660 return 0;
2663 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2665 struct VncSurface *vs = &vd->guest;
2667 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2670 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2672 int i, j;
2674 w = (x + w) / VNC_STAT_RECT;
2675 h = (y + h) / VNC_STAT_RECT;
2676 x /= VNC_STAT_RECT;
2677 y /= VNC_STAT_RECT;
2679 for (j = y; j <= h; j++) {
2680 for (i = x; i <= w; i++) {
2681 vs->lossy_rect[j][i] = 1;
2686 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2688 VncState *vs;
2689 int sty = y / VNC_STAT_RECT;
2690 int stx = x / VNC_STAT_RECT;
2691 int has_dirty = 0;
2693 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2694 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2696 QTAILQ_FOREACH(vs, &vd->clients, next) {
2697 int j;
2699 /* kernel send buffers are full -> refresh later */
2700 if (vs->output.offset) {
2701 continue;
2704 if (!vs->lossy_rect[sty][stx]) {
2705 continue;
2708 vs->lossy_rect[sty][stx] = 0;
2709 for (j = 0; j < VNC_STAT_RECT; ++j) {
2710 bitmap_set(vs->dirty[y + j],
2711 x / VNC_DIRTY_PIXELS_PER_BIT,
2712 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2714 has_dirty++;
2717 return has_dirty;
2720 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2722 int width = MIN(pixman_image_get_width(vd->guest.fb),
2723 pixman_image_get_width(vd->server));
2724 int height = MIN(pixman_image_get_height(vd->guest.fb),
2725 pixman_image_get_height(vd->server));
2726 int x, y;
2727 struct timeval res;
2728 int has_dirty = 0;
2730 for (y = 0; y < height; y += VNC_STAT_RECT) {
2731 for (x = 0; x < width; x += VNC_STAT_RECT) {
2732 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2734 rect->updated = false;
2738 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2740 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2741 return has_dirty;
2743 vd->guest.last_freq_check = *tv;
2745 for (y = 0; y < height; y += VNC_STAT_RECT) {
2746 for (x = 0; x < width; x += VNC_STAT_RECT) {
2747 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2748 int count = ARRAY_SIZE(rect->times);
2749 struct timeval min, max;
2751 if (!timerisset(&rect->times[count - 1])) {
2752 continue ;
2755 max = rect->times[(rect->idx + count - 1) % count];
2756 qemu_timersub(tv, &max, &res);
2758 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2759 rect->freq = 0;
2760 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2761 memset(rect->times, 0, sizeof (rect->times));
2762 continue ;
2765 min = rect->times[rect->idx];
2766 max = rect->times[(rect->idx + count - 1) % count];
2767 qemu_timersub(&max, &min, &res);
2769 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2770 rect->freq /= count;
2771 rect->freq = 1. / rect->freq;
2774 return has_dirty;
2777 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2779 int i, j;
2780 double total = 0;
2781 int num = 0;
2783 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2784 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2786 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2787 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2788 total += vnc_stat_rect(vs->vd, i, j)->freq;
2789 num++;
2793 if (num) {
2794 return total / num;
2795 } else {
2796 return 0;
2800 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2802 VncRectStat *rect;
2804 rect = vnc_stat_rect(vd, x, y);
2805 if (rect->updated) {
2806 return ;
2808 rect->times[rect->idx] = *tv;
2809 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2810 rect->updated = true;
2813 static int vnc_refresh_server_surface(VncDisplay *vd)
2815 int width = MIN(pixman_image_get_width(vd->guest.fb),
2816 pixman_image_get_width(vd->server));
2817 int height = MIN(pixman_image_get_height(vd->guest.fb),
2818 pixman_image_get_height(vd->server));
2819 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2820 uint8_t *guest_row0 = NULL, *server_row0;
2821 VncState *vs;
2822 int has_dirty = 0;
2823 pixman_image_t *tmpbuf = NULL;
2825 struct timeval tv = { 0, 0 };
2827 if (!vd->non_adaptive) {
2828 gettimeofday(&tv, NULL);
2829 has_dirty = vnc_update_stats(vd, &tv);
2833 * Walk through the guest dirty map.
2834 * Check and copy modified bits from guest to server surface.
2835 * Update server dirty map.
2837 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2838 server_stride = guest_stride = guest_ll =
2839 pixman_image_get_stride(vd->server);
2840 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2841 server_stride);
2842 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2843 int width = pixman_image_get_width(vd->server);
2844 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2845 } else {
2846 int guest_bpp =
2847 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2848 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2849 guest_stride = pixman_image_get_stride(vd->guest.fb);
2850 guest_ll = pixman_image_get_width(vd->guest.fb) * (DIV_ROUND_UP(guest_bpp, 8));
2852 line_bytes = MIN(server_stride, guest_ll);
2854 for (;;) {
2855 int x;
2856 uint8_t *guest_ptr, *server_ptr;
2857 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2858 height * VNC_DIRTY_BPL(&vd->guest),
2859 y * VNC_DIRTY_BPL(&vd->guest));
2860 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2861 /* no more dirty bits */
2862 break;
2864 y = offset / VNC_DIRTY_BPL(&vd->guest);
2865 x = offset % VNC_DIRTY_BPL(&vd->guest);
2867 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2869 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2870 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2871 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2872 } else {
2873 guest_ptr = guest_row0 + y * guest_stride;
2875 guest_ptr += x * cmp_bytes;
2877 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2878 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2879 int _cmp_bytes = cmp_bytes;
2880 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2881 continue;
2883 if ((x + 1) * cmp_bytes > line_bytes) {
2884 _cmp_bytes = line_bytes - x * cmp_bytes;
2886 assert(_cmp_bytes >= 0);
2887 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2888 continue;
2890 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2891 if (!vd->non_adaptive) {
2892 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2893 y, &tv);
2895 QTAILQ_FOREACH(vs, &vd->clients, next) {
2896 set_bit(x, vs->dirty[y]);
2898 has_dirty++;
2901 y++;
2903 qemu_pixman_image_unref(tmpbuf);
2904 return has_dirty;
2907 static void vnc_refresh(DisplayChangeListener *dcl)
2909 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2910 VncState *vs, *vn;
2911 int has_dirty, rects = 0;
2913 if (QTAILQ_EMPTY(&vd->clients)) {
2914 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2915 return;
2918 graphic_hw_update(vd->dcl.con);
2920 if (vnc_trylock_display(vd)) {
2921 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2922 return;
2925 has_dirty = vnc_refresh_server_surface(vd);
2926 vnc_unlock_display(vd);
2928 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2929 rects += vnc_update_client(vs, has_dirty);
2930 /* vs might be free()ed here */
2933 if (has_dirty && rects) {
2934 vd->dcl.update_interval /= 2;
2935 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
2936 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
2938 } else {
2939 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
2940 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
2941 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
2946 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
2947 bool skipauth, bool websocket)
2949 VncState *vs = g_new0(VncState, 1);
2950 bool first_client = QTAILQ_EMPTY(&vd->clients);
2951 int i;
2953 trace_vnc_client_connect(vs, sioc);
2954 vs->sioc = sioc;
2955 object_ref(OBJECT(vs->sioc));
2956 vs->ioc = QIO_CHANNEL(sioc);
2957 object_ref(OBJECT(vs->ioc));
2958 vs->vd = vd;
2960 buffer_init(&vs->input, "vnc-input/%p", sioc);
2961 buffer_init(&vs->output, "vnc-output/%p", sioc);
2962 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
2964 buffer_init(&vs->tight.tight, "vnc-tight/%p", sioc);
2965 buffer_init(&vs->tight.zlib, "vnc-tight-zlib/%p", sioc);
2966 buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
2967 #ifdef CONFIG_VNC_JPEG
2968 buffer_init(&vs->tight.jpeg, "vnc-tight-jpeg/%p", sioc);
2969 #endif
2970 #ifdef CONFIG_VNC_PNG
2971 buffer_init(&vs->tight.png, "vnc-tight-png/%p", sioc);
2972 #endif
2973 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
2974 buffer_init(&vs->zrle.zrle, "vnc-zrle/%p", sioc);
2975 buffer_init(&vs->zrle.fb, "vnc-zrle-fb/%p", sioc);
2976 buffer_init(&vs->zrle.zlib, "vnc-zrle-zlib/%p", sioc);
2978 if (skipauth) {
2979 vs->auth = VNC_AUTH_NONE;
2980 vs->subauth = VNC_AUTH_INVALID;
2981 } else {
2982 if (websocket) {
2983 vs->auth = vd->ws_auth;
2984 vs->subauth = VNC_AUTH_INVALID;
2985 } else {
2986 vs->auth = vd->auth;
2987 vs->subauth = vd->subauth;
2990 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
2991 sioc, websocket, vs->auth, vs->subauth);
2993 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
2994 for (i = 0; i < VNC_STAT_ROWS; ++i) {
2995 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
2998 VNC_DEBUG("New client on socket %p\n", vs->sioc);
2999 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3000 qio_channel_set_blocking(vs->ioc, false, NULL);
3001 if (vs->ioc_tag) {
3002 g_source_remove(vs->ioc_tag);
3004 if (websocket) {
3005 vs->websocket = 1;
3006 if (vd->tlscreds) {
3007 vs->ioc_tag = qio_channel_add_watch(
3008 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
3009 } else {
3010 vs->ioc_tag = qio_channel_add_watch(
3011 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
3013 } else {
3014 vs->ioc_tag = qio_channel_add_watch(
3015 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
3018 vnc_client_cache_addr(vs);
3019 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3020 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3022 vs->last_x = -1;
3023 vs->last_y = -1;
3025 vs->as.freq = 44100;
3026 vs->as.nchannels = 2;
3027 vs->as.fmt = AUD_FMT_S16;
3028 vs->as.endianness = 0;
3030 qemu_mutex_init(&vs->output_mutex);
3031 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3033 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3034 if (first_client) {
3035 vnc_update_server_surface(vd);
3038 graphic_hw_update(vd->dcl.con);
3040 if (!vs->websocket) {
3041 vnc_start_protocol(vs);
3044 if (vd->num_connecting > vd->connections_limit) {
3045 QTAILQ_FOREACH(vs, &vd->clients, next) {
3046 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3047 vnc_disconnect_start(vs);
3048 return;
3054 void vnc_start_protocol(VncState *vs)
3056 vnc_write(vs, "RFB 003.008\n", 12);
3057 vnc_flush(vs);
3058 vnc_read_when(vs, protocol_version, 12);
3060 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3061 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3064 static gboolean vnc_listen_io(QIOChannel *ioc,
3065 GIOCondition condition,
3066 void *opaque)
3068 VncDisplay *vd = opaque;
3069 QIOChannelSocket *sioc = NULL;
3070 Error *err = NULL;
3071 bool isWebsock = false;
3072 size_t i;
3074 for (i = 0; i < vd->nlwebsock; i++) {
3075 if (ioc == QIO_CHANNEL(vd->lwebsock[i])) {
3076 isWebsock = true;
3077 break;
3081 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), &err);
3082 if (sioc != NULL) {
3083 qio_channel_set_name(QIO_CHANNEL(sioc),
3084 isWebsock ? "vnc-ws-server" : "vnc-server");
3085 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
3086 vnc_connect(vd, sioc, false, isWebsock);
3087 object_unref(OBJECT(sioc));
3088 } else {
3089 /* client probably closed connection before we got there */
3090 error_free(err);
3093 return TRUE;
3096 static const DisplayChangeListenerOps dcl_ops = {
3097 .dpy_name = "vnc",
3098 .dpy_refresh = vnc_refresh,
3099 .dpy_gfx_update = vnc_dpy_update,
3100 .dpy_gfx_switch = vnc_dpy_switch,
3101 .dpy_gfx_check_format = qemu_pixman_check_format,
3102 .dpy_mouse_set = vnc_mouse_set,
3103 .dpy_cursor_define = vnc_dpy_cursor_define,
3106 void vnc_display_init(const char *id)
3108 VncDisplay *vd;
3110 if (vnc_display_find(id) != NULL) {
3111 return;
3113 vd = g_malloc0(sizeof(*vd));
3115 vd->id = strdup(id);
3116 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3118 QTAILQ_INIT(&vd->clients);
3119 vd->expires = TIME_MAX;
3121 if (keyboard_layout) {
3122 trace_vnc_key_map_init(keyboard_layout);
3123 vd->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
3124 } else {
3125 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
3128 if (!vd->kbd_layout) {
3129 exit(1);
3132 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3133 vd->connections_limit = 32;
3135 qemu_mutex_init(&vd->mutex);
3136 vnc_start_worker_thread();
3138 vd->dcl.ops = &dcl_ops;
3139 register_displaychangelistener(&vd->dcl);
3143 static void vnc_display_close(VncDisplay *vd)
3145 size_t i;
3146 if (!vd) {
3147 return;
3149 vd->is_unix = false;
3150 for (i = 0; i < vd->nlsock; i++) {
3151 if (vd->lsock_tag[i]) {
3152 g_source_remove(vd->lsock_tag[i]);
3154 object_unref(OBJECT(vd->lsock[i]));
3156 g_free(vd->lsock);
3157 g_free(vd->lsock_tag);
3158 vd->lsock = NULL;
3159 vd->lsock_tag = NULL;
3160 vd->nlsock = 0;
3162 for (i = 0; i < vd->nlwebsock; i++) {
3163 if (vd->lwebsock_tag[i]) {
3164 g_source_remove(vd->lwebsock_tag[i]);
3166 object_unref(OBJECT(vd->lwebsock[i]));
3168 g_free(vd->lwebsock);
3169 g_free(vd->lwebsock_tag);
3170 vd->lwebsock = NULL;
3171 vd->lwebsock_tag = NULL;
3172 vd->nlwebsock = 0;
3174 vd->auth = VNC_AUTH_INVALID;
3175 vd->subauth = VNC_AUTH_INVALID;
3176 if (vd->tlscreds) {
3177 object_unparent(OBJECT(vd->tlscreds));
3178 vd->tlscreds = NULL;
3180 g_free(vd->tlsaclname);
3181 vd->tlsaclname = NULL;
3182 if (vd->lock_key_sync) {
3183 qemu_remove_led_event_handler(vd->led);
3184 vd->led = NULL;
3188 int vnc_display_password(const char *id, const char *password)
3190 VncDisplay *vd = vnc_display_find(id);
3192 if (!vd) {
3193 return -EINVAL;
3195 if (vd->auth == VNC_AUTH_NONE) {
3196 error_printf_unless_qmp("If you want use passwords please enable "
3197 "password auth using '-vnc ${dpy},password'.\n");
3198 return -EINVAL;
3201 g_free(vd->password);
3202 vd->password = g_strdup(password);
3204 return 0;
3207 int vnc_display_pw_expire(const char *id, time_t expires)
3209 VncDisplay *vd = vnc_display_find(id);
3211 if (!vd) {
3212 return -EINVAL;
3215 vd->expires = expires;
3216 return 0;
3219 static void vnc_display_print_local_addr(VncDisplay *vd)
3221 SocketAddress *addr;
3222 Error *err = NULL;
3224 if (!vd->nlsock) {
3225 return;
3228 addr = qio_channel_socket_get_local_address(vd->lsock[0], &err);
3229 if (!addr) {
3230 return;
3233 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3234 qapi_free_SocketAddress(addr);
3235 return;
3237 error_printf_unless_qmp("VNC server running on %s:%s\n",
3238 addr->u.inet.host,
3239 addr->u.inet.port);
3240 qapi_free_SocketAddress(addr);
3243 static QemuOptsList qemu_vnc_opts = {
3244 .name = "vnc",
3245 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3246 .implied_opt_name = "vnc",
3247 .desc = {
3249 .name = "vnc",
3250 .type = QEMU_OPT_STRING,
3252 .name = "websocket",
3253 .type = QEMU_OPT_STRING,
3255 .name = "tls-creds",
3256 .type = QEMU_OPT_STRING,
3258 /* Deprecated in favour of tls-creds */
3259 .name = "x509",
3260 .type = QEMU_OPT_STRING,
3262 .name = "share",
3263 .type = QEMU_OPT_STRING,
3265 .name = "display",
3266 .type = QEMU_OPT_STRING,
3268 .name = "head",
3269 .type = QEMU_OPT_NUMBER,
3271 .name = "connections",
3272 .type = QEMU_OPT_NUMBER,
3274 .name = "to",
3275 .type = QEMU_OPT_NUMBER,
3277 .name = "ipv4",
3278 .type = QEMU_OPT_BOOL,
3280 .name = "ipv6",
3281 .type = QEMU_OPT_BOOL,
3283 .name = "password",
3284 .type = QEMU_OPT_BOOL,
3286 .name = "reverse",
3287 .type = QEMU_OPT_BOOL,
3289 .name = "lock-key-sync",
3290 .type = QEMU_OPT_BOOL,
3292 .name = "key-delay-ms",
3293 .type = QEMU_OPT_NUMBER,
3295 .name = "sasl",
3296 .type = QEMU_OPT_BOOL,
3298 /* Deprecated in favour of tls-creds */
3299 .name = "tls",
3300 .type = QEMU_OPT_BOOL,
3302 /* Deprecated in favour of tls-creds */
3303 .name = "x509verify",
3304 .type = QEMU_OPT_STRING,
3306 .name = "acl",
3307 .type = QEMU_OPT_BOOL,
3309 .name = "lossy",
3310 .type = QEMU_OPT_BOOL,
3312 .name = "non-adaptive",
3313 .type = QEMU_OPT_BOOL,
3315 { /* end of list */ }
3320 static int
3321 vnc_display_setup_auth(int *auth,
3322 int *subauth,
3323 QCryptoTLSCreds *tlscreds,
3324 bool password,
3325 bool sasl,
3326 bool websocket,
3327 Error **errp)
3330 * We have a choice of 3 authentication options
3332 * 1. none
3333 * 2. vnc
3334 * 3. sasl
3336 * The channel can be run in 2 modes
3338 * 1. clear
3339 * 2. tls
3341 * And TLS can use 2 types of credentials
3343 * 1. anon
3344 * 2. x509
3346 * We thus have 9 possible logical combinations
3348 * 1. clear + none
3349 * 2. clear + vnc
3350 * 3. clear + sasl
3351 * 4. tls + anon + none
3352 * 5. tls + anon + vnc
3353 * 6. tls + anon + sasl
3354 * 7. tls + x509 + none
3355 * 8. tls + x509 + vnc
3356 * 9. tls + x509 + sasl
3358 * These need to be mapped into the VNC auth schemes
3359 * in an appropriate manner. In regular VNC, all the
3360 * TLS options get mapped into VNC_AUTH_VENCRYPT
3361 * sub-auth types.
3363 * In websockets, the https:// protocol already provides
3364 * TLS support, so there is no need to make use of the
3365 * VeNCrypt extension. Furthermore, websockets browser
3366 * clients could not use VeNCrypt even if they wanted to,
3367 * as they cannot control when the TLS handshake takes
3368 * place. Thus there is no option but to rely on https://,
3369 * meaning combinations 4->6 and 7->9 will be mapped to
3370 * VNC auth schemes in the same way as combos 1->3.
3372 * Regardless of fact that we have a different mapping to
3373 * VNC auth mechs for plain VNC vs websockets VNC, the end
3374 * result has the same security characteristics.
3376 if (websocket || !tlscreds) {
3377 if (password) {
3378 VNC_DEBUG("Initializing VNC server with password auth\n");
3379 *auth = VNC_AUTH_VNC;
3380 } else if (sasl) {
3381 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3382 *auth = VNC_AUTH_SASL;
3383 } else {
3384 VNC_DEBUG("Initializing VNC server with no auth\n");
3385 *auth = VNC_AUTH_NONE;
3387 *subauth = VNC_AUTH_INVALID;
3388 } else {
3389 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3390 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3391 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3392 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3394 if (!is_x509 && !is_anon) {
3395 error_setg(errp,
3396 "Unsupported TLS cred type %s",
3397 object_get_typename(OBJECT(tlscreds)));
3398 return -1;
3400 *auth = VNC_AUTH_VENCRYPT;
3401 if (password) {
3402 if (is_x509) {
3403 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3404 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3405 } else {
3406 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3407 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3410 } else if (sasl) {
3411 if (is_x509) {
3412 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3413 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3414 } else {
3415 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3416 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3418 } else {
3419 if (is_x509) {
3420 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3421 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3422 } else {
3423 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3424 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3428 return 0;
3433 * Handle back compat with old CLI syntax by creating some
3434 * suitable QCryptoTLSCreds objects
3436 static QCryptoTLSCreds *
3437 vnc_display_create_creds(bool x509,
3438 bool x509verify,
3439 const char *dir,
3440 const char *id,
3441 Error **errp)
3443 gchar *credsid = g_strdup_printf("tlsvnc%s", id);
3444 Object *parent = object_get_objects_root();
3445 Object *creds;
3446 Error *err = NULL;
3448 if (x509) {
3449 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
3450 parent,
3451 credsid,
3452 &err,
3453 "endpoint", "server",
3454 "dir", dir,
3455 "verify-peer", x509verify ? "yes" : "no",
3456 NULL);
3457 } else {
3458 creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
3459 parent,
3460 credsid,
3461 &err,
3462 "endpoint", "server",
3463 NULL);
3466 g_free(credsid);
3468 if (err) {
3469 error_propagate(errp, err);
3470 return NULL;
3473 return QCRYPTO_TLS_CREDS(creds);
3477 static int vnc_display_get_address(const char *addrstr,
3478 bool websocket,
3479 bool reverse,
3480 int displaynum,
3481 int to,
3482 bool has_ipv4,
3483 bool has_ipv6,
3484 bool ipv4,
3485 bool ipv6,
3486 SocketAddress **retaddr,
3487 Error **errp)
3489 int ret = -1;
3490 SocketAddress *addr = NULL;
3492 addr = g_new0(SocketAddress, 1);
3494 if (strncmp(addrstr, "unix:", 5) == 0) {
3495 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3496 addr->u.q_unix.path = g_strdup(addrstr + 5);
3498 if (websocket) {
3499 error_setg(errp, "UNIX sockets not supported with websock");
3500 goto cleanup;
3503 if (to) {
3504 error_setg(errp, "Port range not support with UNIX socket");
3505 goto cleanup;
3507 ret = 0;
3508 } else {
3509 const char *port;
3510 size_t hostlen;
3511 unsigned long long baseport = 0;
3512 InetSocketAddress *inet;
3514 port = strrchr(addrstr, ':');
3515 if (!port) {
3516 if (websocket) {
3517 hostlen = 0;
3518 port = addrstr;
3519 } else {
3520 error_setg(errp, "no vnc port specified");
3521 goto cleanup;
3523 } else {
3524 hostlen = port - addrstr;
3525 port++;
3526 if (*port == '\0') {
3527 error_setg(errp, "vnc port cannot be empty");
3528 goto cleanup;
3532 addr->type = SOCKET_ADDRESS_TYPE_INET;
3533 inet = &addr->u.inet;
3534 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3535 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3536 } else {
3537 inet->host = g_strndup(addrstr, hostlen);
3539 /* plain VNC port is just an offset, for websocket
3540 * port is absolute */
3541 if (websocket) {
3542 if (g_str_equal(addrstr, "") ||
3543 g_str_equal(addrstr, "on")) {
3544 if (displaynum == -1) {
3545 error_setg(errp, "explicit websocket port is required");
3546 goto cleanup;
3548 inet->port = g_strdup_printf(
3549 "%d", displaynum + 5700);
3550 if (to) {
3551 inet->has_to = true;
3552 inet->to = to + 5700;
3554 } else {
3555 inet->port = g_strdup(port);
3557 } else {
3558 int offset = reverse ? 0 : 5900;
3559 if (parse_uint_full(port, &baseport, 10) < 0) {
3560 error_setg(errp, "can't convert to a number: %s", port);
3561 goto cleanup;
3563 if (baseport > 65535 ||
3564 baseport + offset > 65535) {
3565 error_setg(errp, "port %s out of range", port);
3566 goto cleanup;
3568 inet->port = g_strdup_printf(
3569 "%d", (int)baseport + offset);
3571 if (to) {
3572 inet->has_to = true;
3573 inet->to = to + offset;
3577 inet->ipv4 = ipv4;
3578 inet->has_ipv4 = has_ipv4;
3579 inet->ipv6 = ipv6;
3580 inet->has_ipv6 = has_ipv6;
3582 ret = baseport;
3585 *retaddr = addr;
3587 cleanup:
3588 if (ret < 0) {
3589 qapi_free_SocketAddress(addr);
3591 return ret;
3594 static void vnc_free_addresses(SocketAddress ***retsaddr,
3595 size_t *retnsaddr)
3597 size_t i;
3599 for (i = 0; i < *retnsaddr; i++) {
3600 qapi_free_SocketAddress((*retsaddr)[i]);
3602 g_free(*retsaddr);
3604 *retsaddr = NULL;
3605 *retnsaddr = 0;
3608 static int vnc_display_get_addresses(QemuOpts *opts,
3609 bool reverse,
3610 SocketAddress ***retsaddr,
3611 size_t *retnsaddr,
3612 SocketAddress ***retwsaddr,
3613 size_t *retnwsaddr,
3614 Error **errp)
3616 SocketAddress *saddr = NULL;
3617 SocketAddress *wsaddr = NULL;
3618 QemuOptsIter addriter;
3619 const char *addr;
3620 int to = qemu_opt_get_number(opts, "to", 0);
3621 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3622 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3623 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3624 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3625 int displaynum = -1;
3626 int ret = -1;
3628 *retsaddr = NULL;
3629 *retnsaddr = 0;
3630 *retwsaddr = NULL;
3631 *retnwsaddr = 0;
3633 addr = qemu_opt_get(opts, "vnc");
3634 if (addr == NULL || g_str_equal(addr, "none")) {
3635 ret = 0;
3636 goto cleanup;
3638 if (qemu_opt_get(opts, "websocket") &&
3639 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3640 error_setg(errp,
3641 "SHA1 hash support is required for websockets");
3642 goto cleanup;
3645 qemu_opt_iter_init(&addriter, opts, "vnc");
3646 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3647 int rv;
3648 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3649 has_ipv4, has_ipv6,
3650 ipv4, ipv6,
3651 &saddr, errp);
3652 if (rv < 0) {
3653 goto cleanup;
3655 /* Historical compat - first listen address can be used
3656 * to set the default websocket port
3658 if (displaynum == -1) {
3659 displaynum = rv;
3661 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3662 (*retsaddr)[(*retnsaddr)++] = saddr;
3665 /* If we had multiple primary displays, we don't do defaults
3666 * for websocket, and require explicit config instead. */
3667 if (*retnsaddr > 1) {
3668 displaynum = -1;
3671 qemu_opt_iter_init(&addriter, opts, "websocket");
3672 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3673 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3674 has_ipv4, has_ipv6,
3675 ipv4, ipv6,
3676 &wsaddr, errp) < 0) {
3677 goto cleanup;
3680 /* Historical compat - if only a single listen address was
3681 * provided, then this is used to set the default listen
3682 * address for websocket too
3684 if (*retnsaddr == 1 &&
3685 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3686 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3687 g_str_equal(wsaddr->u.inet.host, "") &&
3688 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3689 g_free(wsaddr->u.inet.host);
3690 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3693 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3694 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3697 ret = 0;
3698 cleanup:
3699 if (ret < 0) {
3700 vnc_free_addresses(retsaddr, retnsaddr);
3701 vnc_free_addresses(retwsaddr, retnwsaddr);
3703 return ret;
3706 static int vnc_display_connect(VncDisplay *vd,
3707 SocketAddress **saddr,
3708 size_t nsaddr,
3709 SocketAddress **wsaddr,
3710 size_t nwsaddr,
3711 Error **errp)
3713 /* connect to viewer */
3714 QIOChannelSocket *sioc = NULL;
3715 if (nwsaddr != 0) {
3716 error_setg(errp, "Cannot use websockets in reverse mode");
3717 return -1;
3719 if (nsaddr != 1) {
3720 error_setg(errp, "Expected a single address in reverse mode");
3721 return -1;
3723 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3724 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3725 sioc = qio_channel_socket_new();
3726 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3727 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3728 return -1;
3730 vnc_connect(vd, sioc, false, false);
3731 object_unref(OBJECT(sioc));
3732 return 0;
3736 static int vnc_display_listen_addr(VncDisplay *vd,
3737 SocketAddress *addr,
3738 const char *name,
3739 QIOChannelSocket ***lsock,
3740 guint **lsock_tag,
3741 size_t *nlsock,
3742 Error **errp)
3744 QIODNSResolver *resolver = qio_dns_resolver_get_instance();
3745 SocketAddress **rawaddrs = NULL;
3746 size_t nrawaddrs = 0;
3747 Error *listenerr = NULL;
3748 bool listening = false;
3749 size_t i;
3751 if (qio_dns_resolver_lookup_sync(resolver, addr, &nrawaddrs,
3752 &rawaddrs, errp) < 0) {
3753 return -1;
3756 for (i = 0; i < nrawaddrs; i++) {
3757 QIOChannelSocket *sioc = qio_channel_socket_new();
3759 qio_channel_set_name(QIO_CHANNEL(sioc), name);
3760 if (qio_channel_socket_listen_sync(
3761 sioc, rawaddrs[i], listenerr == NULL ? &listenerr : NULL) < 0) {
3762 object_unref(OBJECT(sioc));
3763 continue;
3765 listening = true;
3766 (*nlsock)++;
3767 *lsock = g_renew(QIOChannelSocket *, *lsock, *nlsock);
3768 *lsock_tag = g_renew(guint, *lsock_tag, *nlsock);
3770 (*lsock)[*nlsock - 1] = sioc;
3771 (*lsock_tag)[*nlsock - 1] = 0;
3774 for (i = 0; i < nrawaddrs; i++) {
3775 qapi_free_SocketAddress(rawaddrs[i]);
3777 g_free(rawaddrs);
3779 if (listenerr) {
3780 if (!listening) {
3781 error_propagate(errp, listenerr);
3782 return -1;
3783 } else {
3784 error_free(listenerr);
3788 for (i = 0; i < *nlsock; i++) {
3789 (*lsock_tag)[i] = qio_channel_add_watch(
3790 QIO_CHANNEL((*lsock)[i]),
3791 G_IO_IN, vnc_listen_io, vd, NULL);
3794 return 0;
3798 static int vnc_display_listen(VncDisplay *vd,
3799 SocketAddress **saddr,
3800 size_t nsaddr,
3801 SocketAddress **wsaddr,
3802 size_t nwsaddr,
3803 Error **errp)
3805 size_t i;
3807 for (i = 0; i < nsaddr; i++) {
3808 if (vnc_display_listen_addr(vd, saddr[i],
3809 "vnc-listen",
3810 &vd->lsock,
3811 &vd->lsock_tag,
3812 &vd->nlsock,
3813 errp) < 0) {
3814 return -1;
3817 for (i = 0; i < nwsaddr; i++) {
3818 if (vnc_display_listen_addr(vd, wsaddr[i],
3819 "vnc-ws-listen",
3820 &vd->lwebsock,
3821 &vd->lwebsock_tag,
3822 &vd->nlwebsock,
3823 errp) < 0) {
3824 return -1;
3828 return 0;
3832 void vnc_display_open(const char *id, Error **errp)
3834 VncDisplay *vd = vnc_display_find(id);
3835 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3836 SocketAddress **saddr = NULL, **wsaddr = NULL;
3837 size_t nsaddr, nwsaddr;
3838 const char *share, *device_id;
3839 QemuConsole *con;
3840 bool password = false;
3841 bool reverse = false;
3842 const char *credid;
3843 bool sasl = false;
3844 #ifdef CONFIG_VNC_SASL
3845 int saslErr;
3846 #endif
3847 int acl = 0;
3848 int lock_key_sync = 1;
3849 int key_delay_ms;
3851 if (!vd) {
3852 error_setg(errp, "VNC display not active");
3853 return;
3855 vnc_display_close(vd);
3857 if (!opts) {
3858 return;
3861 reverse = qemu_opt_get_bool(opts, "reverse", false);
3862 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3863 &wsaddr, &nwsaddr, errp) < 0) {
3864 goto fail;
3867 password = qemu_opt_get_bool(opts, "password", false);
3868 if (password) {
3869 if (fips_get_state()) {
3870 error_setg(errp,
3871 "VNC password auth disabled due to FIPS mode, "
3872 "consider using the VeNCrypt or SASL authentication "
3873 "methods as an alternative");
3874 goto fail;
3876 if (!qcrypto_cipher_supports(
3877 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3878 error_setg(errp,
3879 "Cipher backend does not support DES RFB algorithm");
3880 goto fail;
3884 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3885 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3886 sasl = qemu_opt_get_bool(opts, "sasl", false);
3887 #ifndef CONFIG_VNC_SASL
3888 if (sasl) {
3889 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3890 goto fail;
3892 #endif /* CONFIG_VNC_SASL */
3893 credid = qemu_opt_get(opts, "tls-creds");
3894 if (credid) {
3895 Object *creds;
3896 if (qemu_opt_get(opts, "tls") ||
3897 qemu_opt_get(opts, "x509") ||
3898 qemu_opt_get(opts, "x509verify")) {
3899 error_setg(errp,
3900 "'tls-creds' parameter is mutually exclusive with "
3901 "'tls', 'x509' and 'x509verify' parameters");
3902 goto fail;
3905 creds = object_resolve_path_component(
3906 object_get_objects_root(), credid);
3907 if (!creds) {
3908 error_setg(errp, "No TLS credentials with id '%s'",
3909 credid);
3910 goto fail;
3912 vd->tlscreds = (QCryptoTLSCreds *)
3913 object_dynamic_cast(creds,
3914 TYPE_QCRYPTO_TLS_CREDS);
3915 if (!vd->tlscreds) {
3916 error_setg(errp, "Object with id '%s' is not TLS credentials",
3917 credid);
3918 goto fail;
3920 object_ref(OBJECT(vd->tlscreds));
3922 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3923 error_setg(errp,
3924 "Expecting TLS credentials with a server endpoint");
3925 goto fail;
3927 } else {
3928 const char *path;
3929 bool tls = false, x509 = false, x509verify = false;
3930 tls = qemu_opt_get_bool(opts, "tls", false);
3931 if (tls) {
3932 path = qemu_opt_get(opts, "x509");
3934 if (path) {
3935 x509 = true;
3936 } else {
3937 path = qemu_opt_get(opts, "x509verify");
3938 if (path) {
3939 x509 = true;
3940 x509verify = true;
3943 vd->tlscreds = vnc_display_create_creds(x509,
3944 x509verify,
3945 path,
3946 vd->id,
3947 errp);
3948 if (!vd->tlscreds) {
3949 goto fail;
3953 acl = qemu_opt_get_bool(opts, "acl", false);
3955 share = qemu_opt_get(opts, "share");
3956 if (share) {
3957 if (strcmp(share, "ignore") == 0) {
3958 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
3959 } else if (strcmp(share, "allow-exclusive") == 0) {
3960 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3961 } else if (strcmp(share, "force-shared") == 0) {
3962 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3963 } else {
3964 error_setg(errp, "unknown vnc share= option");
3965 goto fail;
3967 } else {
3968 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3970 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3972 #ifdef CONFIG_VNC_JPEG
3973 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
3974 #endif
3975 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3976 /* adaptive updates are only used with tight encoding and
3977 * if lossy updates are enabled so we can disable all the
3978 * calculations otherwise */
3979 if (!vd->lossy) {
3980 vd->non_adaptive = true;
3983 if (acl) {
3984 if (strcmp(vd->id, "default") == 0) {
3985 vd->tlsaclname = g_strdup("vnc.x509dname");
3986 } else {
3987 vd->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vd->id);
3989 qemu_acl_init(vd->tlsaclname);
3991 #ifdef CONFIG_VNC_SASL
3992 if (acl && sasl) {
3993 char *aclname;
3995 if (strcmp(vd->id, "default") == 0) {
3996 aclname = g_strdup("vnc.username");
3997 } else {
3998 aclname = g_strdup_printf("vnc.%s.username", vd->id);
4000 vd->sasl.acl = qemu_acl_init(aclname);
4001 g_free(aclname);
4003 #endif
4005 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4006 vd->tlscreds, password,
4007 sasl, false, errp) < 0) {
4008 goto fail;
4010 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4012 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4013 vd->tlscreds, password,
4014 sasl, true, errp) < 0) {
4015 goto fail;
4017 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
4019 #ifdef CONFIG_VNC_SASL
4020 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
4021 error_setg(errp, "Failed to initialize SASL auth: %s",
4022 sasl_errstring(saslErr, NULL, NULL));
4023 goto fail;
4025 #endif
4026 vd->lock_key_sync = lock_key_sync;
4027 if (lock_key_sync) {
4028 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4030 vd->ledstate = 0;
4031 vd->key_delay_ms = key_delay_ms;
4033 device_id = qemu_opt_get(opts, "display");
4034 if (device_id) {
4035 int head = qemu_opt_get_number(opts, "head", 0);
4036 Error *err = NULL;
4038 con = qemu_console_lookup_by_device_name(device_id, head, &err);
4039 if (err) {
4040 error_propagate(errp, err);
4041 goto fail;
4043 } else {
4044 con = NULL;
4047 if (con != vd->dcl.con) {
4048 unregister_displaychangelistener(&vd->dcl);
4049 vd->dcl.con = con;
4050 register_displaychangelistener(&vd->dcl);
4053 if (saddr == NULL) {
4054 goto cleanup;
4057 if (reverse) {
4058 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4059 goto fail;
4061 } else {
4062 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4063 goto fail;
4067 if (qemu_opt_get(opts, "to")) {
4068 vnc_display_print_local_addr(vd);
4071 cleanup:
4072 vnc_free_addresses(&saddr, &nsaddr);
4073 vnc_free_addresses(&wsaddr, &nwsaddr);
4074 return;
4076 fail:
4077 vnc_display_close(vd);
4078 goto cleanup;
4081 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4083 VncDisplay *vd = vnc_display_find(id);
4084 QIOChannelSocket *sioc;
4086 if (!vd) {
4087 return;
4090 sioc = qio_channel_socket_new_fd(csock, NULL);
4091 if (sioc) {
4092 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4093 vnc_connect(vd, sioc, skipauth, false);
4094 object_unref(OBJECT(sioc));
4098 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4100 int i = 2;
4101 char *id;
4103 id = g_strdup("default");
4104 while (qemu_opts_find(olist, id)) {
4105 g_free(id);
4106 id = g_strdup_printf("vnc%d", i++);
4108 qemu_opts_set_id(opts, id);
4111 QemuOpts *vnc_parse(const char *str, Error **errp)
4113 QemuOptsList *olist = qemu_find_opts("vnc");
4114 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
4115 const char *id;
4117 if (!opts) {
4118 return NULL;
4121 id = qemu_opts_id(opts);
4122 if (!id) {
4123 /* auto-assign id if not present */
4124 vnc_auto_assign_id(olist, opts);
4126 return opts;
4129 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4131 Error *local_err = NULL;
4132 char *id = (char *)qemu_opts_id(opts);
4134 assert(id);
4135 vnc_display_init(id);
4136 vnc_display_open(id, &local_err);
4137 if (local_err != NULL) {
4138 error_reportf_err(local_err, "Failed to start VNC server: ");
4139 exit(1);
4141 return 0;
4144 static void vnc_register_config(void)
4146 qemu_add_opts(&qemu_vnc_opts);
4148 opts_init(vnc_register_config);