vfio/pci: Fix RTL8168 NIC quirks
[qemu/ar7.git] / ui / vnc.c
blob1483958c454f0006ef447326b039a7a8a6cec5c7
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 "vnc.h"
28 #include "vnc-jobs.h"
29 #include "trace.h"
30 #include "hw/qdev.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 "qemu/osdep.h"
41 #include "ui/input.h"
42 #include "qapi-event.h"
43 #include "crypto/hash.h"
45 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
46 #define VNC_REFRESH_INTERVAL_INC 50
47 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
48 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
49 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
51 #include "vnc_keysym.h"
52 #include "crypto/cipher.h"
54 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
55 QTAILQ_HEAD_INITIALIZER(vnc_displays);
57 static int vnc_cursor_define(VncState *vs);
58 static void vnc_release_modifiers(VncState *vs);
60 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
62 #ifdef _VNC_DEBUG
63 static const char *mn[] = {
64 [0] = "undefined",
65 [VNC_SHARE_MODE_CONNECTING] = "connecting",
66 [VNC_SHARE_MODE_SHARED] = "shared",
67 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
68 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
70 fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
71 vs->csock, mn[vs->share_mode], mn[mode]);
72 #endif
74 switch (vs->share_mode) {
75 case VNC_SHARE_MODE_CONNECTING:
76 vs->vd->num_connecting--;
77 break;
78 case VNC_SHARE_MODE_SHARED:
79 vs->vd->num_shared--;
80 break;
81 case VNC_SHARE_MODE_EXCLUSIVE:
82 vs->vd->num_exclusive--;
83 break;
84 default:
85 break;
88 vs->share_mode = mode;
90 switch (vs->share_mode) {
91 case VNC_SHARE_MODE_CONNECTING:
92 vs->vd->num_connecting++;
93 break;
94 case VNC_SHARE_MODE_SHARED:
95 vs->vd->num_shared++;
96 break;
97 case VNC_SHARE_MODE_EXCLUSIVE:
98 vs->vd->num_exclusive++;
99 break;
100 default:
101 break;
105 static char *addr_to_string(const char *format,
106 struct sockaddr_storage *sa,
107 socklen_t salen) {
108 char *addr;
109 char host[NI_MAXHOST];
110 char serv[NI_MAXSERV];
111 int err;
112 size_t addrlen;
114 if ((err = getnameinfo((struct sockaddr *)sa, salen,
115 host, sizeof(host),
116 serv, sizeof(serv),
117 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
118 VNC_DEBUG("Cannot resolve address %d: %s\n",
119 err, gai_strerror(err));
120 return NULL;
123 /* Enough for the existing format + the 2 vars we're
124 * substituting in. */
125 addrlen = strlen(format) + strlen(host) + strlen(serv);
126 addr = g_malloc(addrlen + 1);
127 snprintf(addr, addrlen, format, host, serv);
128 addr[addrlen] = '\0';
130 return addr;
134 char *vnc_socket_local_addr(const char *format, int fd) {
135 struct sockaddr_storage sa;
136 socklen_t salen;
138 salen = sizeof(sa);
139 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
140 return NULL;
142 return addr_to_string(format, &sa, salen);
145 char *vnc_socket_remote_addr(const char *format, int fd) {
146 struct sockaddr_storage sa;
147 socklen_t salen;
149 salen = sizeof(sa);
150 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
151 return NULL;
153 return addr_to_string(format, &sa, salen);
156 static VncBasicInfo *vnc_basic_info_get(struct sockaddr_storage *sa,
157 socklen_t salen)
159 VncBasicInfo *info;
160 char host[NI_MAXHOST];
161 char serv[NI_MAXSERV];
162 int err;
164 if ((err = getnameinfo((struct sockaddr *)sa, salen,
165 host, sizeof(host),
166 serv, sizeof(serv),
167 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
168 VNC_DEBUG("Cannot resolve address %d: %s\n",
169 err, gai_strerror(err));
170 return NULL;
173 info = g_malloc0(sizeof(VncBasicInfo));
174 info->host = g_strdup(host);
175 info->service = g_strdup(serv);
176 info->family = inet_netfamily(sa->ss_family);
177 return info;
180 static VncBasicInfo *vnc_basic_info_get_from_server_addr(int fd)
182 struct sockaddr_storage sa;
183 socklen_t salen;
185 salen = sizeof(sa);
186 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
187 return NULL;
190 return vnc_basic_info_get(&sa, salen);
193 static VncBasicInfo *vnc_basic_info_get_from_remote_addr(int fd)
195 struct sockaddr_storage sa;
196 socklen_t salen;
198 salen = sizeof(sa);
199 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
200 return NULL;
203 return vnc_basic_info_get(&sa, salen);
206 static const char *vnc_auth_name(VncDisplay *vd) {
207 switch (vd->auth) {
208 case VNC_AUTH_INVALID:
209 return "invalid";
210 case VNC_AUTH_NONE:
211 return "none";
212 case VNC_AUTH_VNC:
213 return "vnc";
214 case VNC_AUTH_RA2:
215 return "ra2";
216 case VNC_AUTH_RA2NE:
217 return "ra2ne";
218 case VNC_AUTH_TIGHT:
219 return "tight";
220 case VNC_AUTH_ULTRA:
221 return "ultra";
222 case VNC_AUTH_TLS:
223 return "tls";
224 case VNC_AUTH_VENCRYPT:
225 #ifdef CONFIG_VNC_TLS
226 switch (vd->subauth) {
227 case VNC_AUTH_VENCRYPT_PLAIN:
228 return "vencrypt+plain";
229 case VNC_AUTH_VENCRYPT_TLSNONE:
230 return "vencrypt+tls+none";
231 case VNC_AUTH_VENCRYPT_TLSVNC:
232 return "vencrypt+tls+vnc";
233 case VNC_AUTH_VENCRYPT_TLSPLAIN:
234 return "vencrypt+tls+plain";
235 case VNC_AUTH_VENCRYPT_X509NONE:
236 return "vencrypt+x509+none";
237 case VNC_AUTH_VENCRYPT_X509VNC:
238 return "vencrypt+x509+vnc";
239 case VNC_AUTH_VENCRYPT_X509PLAIN:
240 return "vencrypt+x509+plain";
241 case VNC_AUTH_VENCRYPT_TLSSASL:
242 return "vencrypt+tls+sasl";
243 case VNC_AUTH_VENCRYPT_X509SASL:
244 return "vencrypt+x509+sasl";
245 default:
246 return "vencrypt";
248 #else
249 return "vencrypt";
250 #endif
251 case VNC_AUTH_SASL:
252 return "sasl";
254 return "unknown";
257 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
259 VncServerInfo *info;
260 VncBasicInfo *bi = vnc_basic_info_get_from_server_addr(vd->lsock);
261 if (!bi) {
262 return NULL;
265 info = g_malloc(sizeof(*info));
266 info->base = bi;
267 info->has_auth = true;
268 info->auth = g_strdup(vnc_auth_name(vd));
269 return info;
272 static void vnc_client_cache_auth(VncState *client)
274 if (!client->info) {
275 return;
278 #ifdef CONFIG_VNC_TLS
279 if (client->tls.session &&
280 client->tls.dname) {
281 client->info->has_x509_dname = true;
282 client->info->x509_dname = g_strdup(client->tls.dname);
284 #endif
285 #ifdef CONFIG_VNC_SASL
286 if (client->sasl.conn &&
287 client->sasl.username) {
288 client->info->has_sasl_username = true;
289 client->info->sasl_username = g_strdup(client->sasl.username);
291 #endif
294 static void vnc_client_cache_addr(VncState *client)
296 VncBasicInfo *bi = vnc_basic_info_get_from_remote_addr(client->csock);
298 if (bi) {
299 client->info = g_malloc0(sizeof(*client->info));
300 client->info->base = bi;
304 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
306 VncServerInfo *si;
308 if (!vs->info) {
309 return;
311 g_assert(vs->info->base);
313 si = vnc_server_info_get(vs->vd);
314 if (!si) {
315 return;
318 switch (event) {
319 case QAPI_EVENT_VNC_CONNECTED:
320 qapi_event_send_vnc_connected(si, vs->info->base, &error_abort);
321 break;
322 case QAPI_EVENT_VNC_INITIALIZED:
323 qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
324 break;
325 case QAPI_EVENT_VNC_DISCONNECTED:
326 qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
327 break;
328 default:
329 break;
332 qapi_free_VncServerInfo(si);
335 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
337 struct sockaddr_storage sa;
338 socklen_t salen = sizeof(sa);
339 char host[NI_MAXHOST];
340 char serv[NI_MAXSERV];
341 VncClientInfo *info;
343 if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
344 return NULL;
347 if (getnameinfo((struct sockaddr *)&sa, salen,
348 host, sizeof(host),
349 serv, sizeof(serv),
350 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
351 return NULL;
354 info = g_malloc0(sizeof(*info));
355 info->base = g_malloc0(sizeof(*info->base));
356 info->base->host = g_strdup(host);
357 info->base->service = g_strdup(serv);
358 info->base->family = inet_netfamily(sa.ss_family);
359 info->base->websocket = client->websocket;
361 #ifdef CONFIG_VNC_TLS
362 if (client->tls.session && client->tls.dname) {
363 info->has_x509_dname = true;
364 info->x509_dname = g_strdup(client->tls.dname);
366 #endif
367 #ifdef CONFIG_VNC_SASL
368 if (client->sasl.conn && client->sasl.username) {
369 info->has_sasl_username = true;
370 info->sasl_username = g_strdup(client->sasl.username);
372 #endif
374 return info;
377 static VncDisplay *vnc_display_find(const char *id)
379 VncDisplay *vd;
381 if (id == NULL) {
382 return QTAILQ_FIRST(&vnc_displays);
384 QTAILQ_FOREACH(vd, &vnc_displays, next) {
385 if (strcmp(id, vd->id) == 0) {
386 return vd;
389 return NULL;
392 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
394 VncClientInfoList *cinfo, *prev = NULL;
395 VncState *client;
397 QTAILQ_FOREACH(client, &vd->clients, next) {
398 cinfo = g_new0(VncClientInfoList, 1);
399 cinfo->value = qmp_query_vnc_client(client);
400 cinfo->next = prev;
401 prev = cinfo;
403 return prev;
406 VncInfo *qmp_query_vnc(Error **errp)
408 VncInfo *info = g_malloc0(sizeof(*info));
409 VncDisplay *vd = vnc_display_find(NULL);
411 if (vd == NULL || !vd->enabled) {
412 info->enabled = false;
413 } else {
414 struct sockaddr_storage sa;
415 socklen_t salen = sizeof(sa);
416 char host[NI_MAXHOST];
417 char serv[NI_MAXSERV];
419 info->enabled = true;
421 /* for compatibility with the original command */
422 info->has_clients = true;
423 info->clients = qmp_query_client_list(vd);
425 if (vd->lsock == -1) {
426 return info;
429 if (getsockname(vd->lsock, (struct sockaddr *)&sa,
430 &salen) == -1) {
431 error_setg(errp, QERR_UNDEFINED_ERROR);
432 goto out_error;
435 if (getnameinfo((struct sockaddr *)&sa, salen,
436 host, sizeof(host),
437 serv, sizeof(serv),
438 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
439 error_setg(errp, QERR_UNDEFINED_ERROR);
440 goto out_error;
443 info->has_host = true;
444 info->host = g_strdup(host);
446 info->has_service = true;
447 info->service = g_strdup(serv);
449 info->has_family = true;
450 info->family = inet_netfamily(sa.ss_family);
452 info->has_auth = true;
453 info->auth = g_strdup(vnc_auth_name(vd));
456 return info;
458 out_error:
459 qapi_free_VncInfo(info);
460 return NULL;
463 static VncBasicInfoList *qmp_query_server_entry(int socket,
464 bool websocket,
465 VncBasicInfoList *prev)
467 VncBasicInfoList *list;
468 VncBasicInfo *info;
469 struct sockaddr_storage sa;
470 socklen_t salen = sizeof(sa);
471 char host[NI_MAXHOST];
472 char serv[NI_MAXSERV];
474 if (getsockname(socket, (struct sockaddr *)&sa, &salen) < 0 ||
475 getnameinfo((struct sockaddr *)&sa, salen,
476 host, sizeof(host), serv, sizeof(serv),
477 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
478 return prev;
481 info = g_new0(VncBasicInfo, 1);
482 info->host = g_strdup(host);
483 info->service = g_strdup(serv);
484 info->family = inet_netfamily(sa.ss_family);
485 info->websocket = websocket;
487 list = g_new0(VncBasicInfoList, 1);
488 list->value = info;
489 list->next = prev;
490 return list;
493 static void qmp_query_auth(VncDisplay *vd, VncInfo2 *info)
495 switch (vd->auth) {
496 case VNC_AUTH_VNC:
497 info->auth = VNC_PRIMARY_AUTH_VNC;
498 break;
499 case VNC_AUTH_RA2:
500 info->auth = VNC_PRIMARY_AUTH_RA2;
501 break;
502 case VNC_AUTH_RA2NE:
503 info->auth = VNC_PRIMARY_AUTH_RA2NE;
504 break;
505 case VNC_AUTH_TIGHT:
506 info->auth = VNC_PRIMARY_AUTH_TIGHT;
507 break;
508 case VNC_AUTH_ULTRA:
509 info->auth = VNC_PRIMARY_AUTH_ULTRA;
510 break;
511 case VNC_AUTH_TLS:
512 info->auth = VNC_PRIMARY_AUTH_TLS;
513 break;
514 case VNC_AUTH_VENCRYPT:
515 info->auth = VNC_PRIMARY_AUTH_VENCRYPT;
516 #ifdef CONFIG_VNC_TLS
517 info->has_vencrypt = true;
518 switch (vd->subauth) {
519 case VNC_AUTH_VENCRYPT_PLAIN:
520 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
521 break;
522 case VNC_AUTH_VENCRYPT_TLSNONE:
523 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
524 break;
525 case VNC_AUTH_VENCRYPT_TLSVNC:
526 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
527 break;
528 case VNC_AUTH_VENCRYPT_TLSPLAIN:
529 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
530 break;
531 case VNC_AUTH_VENCRYPT_X509NONE:
532 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
533 break;
534 case VNC_AUTH_VENCRYPT_X509VNC:
535 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
536 break;
537 case VNC_AUTH_VENCRYPT_X509PLAIN:
538 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
539 break;
540 case VNC_AUTH_VENCRYPT_TLSSASL:
541 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
542 break;
543 case VNC_AUTH_VENCRYPT_X509SASL:
544 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
545 break;
546 default:
547 info->has_vencrypt = false;
548 break;
550 #endif
551 break;
552 case VNC_AUTH_SASL:
553 info->auth = VNC_PRIMARY_AUTH_SASL;
554 break;
555 case VNC_AUTH_NONE:
556 default:
557 info->auth = VNC_PRIMARY_AUTH_NONE;
558 break;
562 VncInfo2List *qmp_query_vnc_servers(Error **errp)
564 VncInfo2List *item, *prev = NULL;
565 VncInfo2 *info;
566 VncDisplay *vd;
567 DeviceState *dev;
569 QTAILQ_FOREACH(vd, &vnc_displays, next) {
570 info = g_new0(VncInfo2, 1);
571 info->id = g_strdup(vd->id);
572 info->clients = qmp_query_client_list(vd);
573 qmp_query_auth(vd, info);
574 if (vd->dcl.con) {
575 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
576 "device", NULL));
577 info->has_display = true;
578 info->display = g_strdup(dev->id);
580 if (vd->lsock != -1) {
581 info->server = qmp_query_server_entry(vd->lsock, false,
582 info->server);
584 if (vd->lwebsock != -1) {
585 info->server = qmp_query_server_entry(vd->lwebsock, true,
586 info->server);
589 item = g_new0(VncInfo2List, 1);
590 item->value = info;
591 item->next = prev;
592 prev = item;
594 return prev;
597 /* TODO
598 1) Get the queue working for IO.
599 2) there is some weirdness when using the -S option (the screen is grey
600 and not totally invalidated
601 3) resolutions > 1024
604 static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
605 static void vnc_disconnect_start(VncState *vs);
607 static void vnc_colordepth(VncState *vs);
608 static void framebuffer_update_request(VncState *vs, int incremental,
609 int x_position, int y_position,
610 int w, int h);
611 static void vnc_refresh(DisplayChangeListener *dcl);
612 static int vnc_refresh_server_surface(VncDisplay *vd);
614 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
615 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
616 int width, int height,
617 int x, int y, int w, int h) {
618 /* this is needed this to ensure we updated all affected
619 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
620 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
621 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
623 x = MIN(x, width);
624 y = MIN(y, height);
625 w = MIN(x + w, width) - x;
626 h = MIN(y + h, height);
628 for (; y < h; y++) {
629 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
630 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
634 static void vnc_dpy_update(DisplayChangeListener *dcl,
635 int x, int y, int w, int h)
637 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
638 struct VncSurface *s = &vd->guest;
639 int width = pixman_image_get_width(vd->server);
640 int height = pixman_image_get_height(vd->server);
642 vnc_set_area_dirty(s->dirty, width, height, x, y, w, h);
645 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
646 int32_t encoding)
648 vnc_write_u16(vs, x);
649 vnc_write_u16(vs, y);
650 vnc_write_u16(vs, w);
651 vnc_write_u16(vs, h);
653 vnc_write_s32(vs, encoding);
656 void buffer_reserve(Buffer *buffer, size_t len)
658 if ((buffer->capacity - buffer->offset) < len) {
659 buffer->capacity += (len + 1024);
660 buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
664 static int buffer_empty(Buffer *buffer)
666 return buffer->offset == 0;
669 uint8_t *buffer_end(Buffer *buffer)
671 return buffer->buffer + buffer->offset;
674 void buffer_reset(Buffer *buffer)
676 buffer->offset = 0;
679 void buffer_free(Buffer *buffer)
681 g_free(buffer->buffer);
682 buffer->offset = 0;
683 buffer->capacity = 0;
684 buffer->buffer = NULL;
687 void buffer_append(Buffer *buffer, const void *data, size_t len)
689 memcpy(buffer->buffer + buffer->offset, data, len);
690 buffer->offset += len;
693 void buffer_advance(Buffer *buf, size_t len)
695 memmove(buf->buffer, buf->buffer + len,
696 (buf->offset - len));
697 buf->offset -= len;
700 static void vnc_desktop_resize(VncState *vs)
702 if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
703 return;
705 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
706 vs->client_height == pixman_image_get_height(vs->vd->server)) {
707 return;
709 vs->client_width = pixman_image_get_width(vs->vd->server);
710 vs->client_height = pixman_image_get_height(vs->vd->server);
711 vnc_lock_output(vs);
712 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
713 vnc_write_u8(vs, 0);
714 vnc_write_u16(vs, 1); /* number of rects */
715 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
716 VNC_ENCODING_DESKTOPRESIZE);
717 vnc_unlock_output(vs);
718 vnc_flush(vs);
721 static void vnc_abort_display_jobs(VncDisplay *vd)
723 VncState *vs;
725 QTAILQ_FOREACH(vs, &vd->clients, next) {
726 vnc_lock_output(vs);
727 vs->abort = true;
728 vnc_unlock_output(vs);
730 QTAILQ_FOREACH(vs, &vd->clients, next) {
731 vnc_jobs_join(vs);
733 QTAILQ_FOREACH(vs, &vd->clients, next) {
734 vnc_lock_output(vs);
735 vs->abort = false;
736 vnc_unlock_output(vs);
740 int vnc_server_fb_stride(VncDisplay *vd)
742 return pixman_image_get_stride(vd->server);
745 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
747 uint8_t *ptr;
749 ptr = (uint8_t *)pixman_image_get_data(vd->server);
750 ptr += y * vnc_server_fb_stride(vd);
751 ptr += x * VNC_SERVER_FB_BYTES;
752 return ptr;
755 static void vnc_dpy_switch(DisplayChangeListener *dcl,
756 DisplaySurface *surface)
758 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
759 VncState *vs;
760 int width, height;
762 vnc_abort_display_jobs(vd);
764 /* server surface */
765 qemu_pixman_image_unref(vd->server);
766 vd->ds = surface;
767 width = MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
768 VNC_DIRTY_PIXELS_PER_BIT));
769 height = MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
770 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
771 width, height, NULL, 0);
773 /* guest surface */
774 #if 0 /* FIXME */
775 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
776 console_color_init(ds);
777 #endif
778 qemu_pixman_image_unref(vd->guest.fb);
779 vd->guest.fb = pixman_image_ref(surface->image);
780 vd->guest.format = surface->format;
781 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
782 vnc_set_area_dirty(vd->guest.dirty, width, height, 0, 0,
783 width, height);
785 QTAILQ_FOREACH(vs, &vd->clients, next) {
786 vnc_colordepth(vs);
787 vnc_desktop_resize(vs);
788 if (vs->vd->cursor) {
789 vnc_cursor_define(vs);
791 memset(vs->dirty, 0x00, sizeof(vs->dirty));
792 vnc_set_area_dirty(vs->dirty, width, height, 0, 0,
793 width, height);
797 /* fastest code */
798 static void vnc_write_pixels_copy(VncState *vs,
799 void *pixels, int size)
801 vnc_write(vs, pixels, size);
804 /* slowest but generic code. */
805 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
807 uint8_t r, g, b;
809 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
810 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
811 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
812 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
813 #else
814 # error need some bits here if you change VNC_SERVER_FB_FORMAT
815 #endif
816 v = (r << vs->client_pf.rshift) |
817 (g << vs->client_pf.gshift) |
818 (b << vs->client_pf.bshift);
819 switch (vs->client_pf.bytes_per_pixel) {
820 case 1:
821 buf[0] = v;
822 break;
823 case 2:
824 if (vs->client_be) {
825 buf[0] = v >> 8;
826 buf[1] = v;
827 } else {
828 buf[1] = v >> 8;
829 buf[0] = v;
831 break;
832 default:
833 case 4:
834 if (vs->client_be) {
835 buf[0] = v >> 24;
836 buf[1] = v >> 16;
837 buf[2] = v >> 8;
838 buf[3] = v;
839 } else {
840 buf[3] = v >> 24;
841 buf[2] = v >> 16;
842 buf[1] = v >> 8;
843 buf[0] = v;
845 break;
849 static void vnc_write_pixels_generic(VncState *vs,
850 void *pixels1, int size)
852 uint8_t buf[4];
854 if (VNC_SERVER_FB_BYTES == 4) {
855 uint32_t *pixels = pixels1;
856 int n, i;
857 n = size >> 2;
858 for (i = 0; i < n; i++) {
859 vnc_convert_pixel(vs, buf, pixels[i]);
860 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
865 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
867 int i;
868 uint8_t *row;
869 VncDisplay *vd = vs->vd;
871 row = vnc_server_fb_ptr(vd, x, y);
872 for (i = 0; i < h; i++) {
873 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
874 row += vnc_server_fb_stride(vd);
876 return 1;
879 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
881 int n = 0;
883 switch(vs->vnc_encoding) {
884 case VNC_ENCODING_ZLIB:
885 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
886 break;
887 case VNC_ENCODING_HEXTILE:
888 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
889 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
890 break;
891 case VNC_ENCODING_TIGHT:
892 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
893 break;
894 case VNC_ENCODING_TIGHT_PNG:
895 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
896 break;
897 case VNC_ENCODING_ZRLE:
898 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
899 break;
900 case VNC_ENCODING_ZYWRLE:
901 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
902 break;
903 default:
904 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
905 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
906 break;
908 return n;
911 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
913 /* send bitblit op to the vnc client */
914 vnc_lock_output(vs);
915 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
916 vnc_write_u8(vs, 0);
917 vnc_write_u16(vs, 1); /* number of rects */
918 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
919 vnc_write_u16(vs, src_x);
920 vnc_write_u16(vs, src_y);
921 vnc_unlock_output(vs);
922 vnc_flush(vs);
925 static void vnc_dpy_copy(DisplayChangeListener *dcl,
926 int src_x, int src_y,
927 int dst_x, int dst_y, int w, int h)
929 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
930 VncState *vs, *vn;
931 uint8_t *src_row;
932 uint8_t *dst_row;
933 int i, x, y, pitch, inc, w_lim, s;
934 int cmp_bytes;
936 vnc_refresh_server_surface(vd);
937 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
938 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
939 vs->force_update = 1;
940 vnc_update_client(vs, 1, true);
941 /* vs might be free()ed here */
945 /* do bitblit op on the local surface too */
946 pitch = vnc_server_fb_stride(vd);
947 src_row = vnc_server_fb_ptr(vd, src_x, src_y);
948 dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
949 y = dst_y;
950 inc = 1;
951 if (dst_y > src_y) {
952 /* copy backwards */
953 src_row += pitch * (h-1);
954 dst_row += pitch * (h-1);
955 pitch = -pitch;
956 y = dst_y + h - 1;
957 inc = -1;
959 w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
960 if (w_lim < 0) {
961 w_lim = w;
962 } else {
963 w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
965 for (i = 0; i < h; i++) {
966 for (x = 0; x <= w_lim;
967 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
968 if (x == w_lim) {
969 if ((s = w - w_lim) == 0)
970 break;
971 } else if (!x) {
972 s = (VNC_DIRTY_PIXELS_PER_BIT -
973 (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
974 s = MIN(s, w_lim);
975 } else {
976 s = VNC_DIRTY_PIXELS_PER_BIT;
978 cmp_bytes = s * VNC_SERVER_FB_BYTES;
979 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
980 continue;
981 memmove(dst_row, src_row, cmp_bytes);
982 QTAILQ_FOREACH(vs, &vd->clients, next) {
983 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
984 set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
985 vs->dirty[y]);
989 src_row += pitch - w * VNC_SERVER_FB_BYTES;
990 dst_row += pitch - w * VNC_SERVER_FB_BYTES;
991 y += inc;
994 QTAILQ_FOREACH(vs, &vd->clients, next) {
995 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
996 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
1001 static void vnc_mouse_set(DisplayChangeListener *dcl,
1002 int x, int y, int visible)
1004 /* can we ask the client(s) to move the pointer ??? */
1007 static int vnc_cursor_define(VncState *vs)
1009 QEMUCursor *c = vs->vd->cursor;
1010 int isize;
1012 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
1013 vnc_lock_output(vs);
1014 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1015 vnc_write_u8(vs, 0); /* padding */
1016 vnc_write_u16(vs, 1); /* # of rects */
1017 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
1018 VNC_ENCODING_RICH_CURSOR);
1019 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
1020 vnc_write_pixels_generic(vs, c->data, isize);
1021 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
1022 vnc_unlock_output(vs);
1023 return 0;
1025 return -1;
1028 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
1029 QEMUCursor *c)
1031 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
1032 VncState *vs;
1034 cursor_put(vd->cursor);
1035 g_free(vd->cursor_mask);
1037 vd->cursor = c;
1038 cursor_get(vd->cursor);
1039 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
1040 vd->cursor_mask = g_malloc0(vd->cursor_msize);
1041 cursor_get_mono_mask(c, 0, vd->cursor_mask);
1043 QTAILQ_FOREACH(vs, &vd->clients, next) {
1044 vnc_cursor_define(vs);
1048 static int find_and_clear_dirty_height(VncState *vs,
1049 int y, int last_x, int x, int height)
1051 int h;
1053 for (h = 1; h < (height - y); h++) {
1054 if (!test_bit(last_x, vs->dirty[y + h])) {
1055 break;
1057 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1060 return h;
1063 static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
1065 vs->has_dirty += has_dirty;
1066 if (vs->need_update && vs->csock != -1) {
1067 VncDisplay *vd = vs->vd;
1068 VncJob *job;
1069 int y;
1070 int height, width;
1071 int n = 0;
1073 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
1074 /* kernel send buffers are full -> drop frames to throttle */
1075 return 0;
1077 if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)
1078 return 0;
1081 * Send screen updates to the vnc client using the server
1082 * surface and server dirty map. guest surface updates
1083 * happening in parallel don't disturb us, the next pass will
1084 * send them to the client.
1086 job = vnc_job_new(vs);
1088 height = pixman_image_get_height(vd->server);
1089 width = pixman_image_get_width(vd->server);
1091 y = 0;
1092 for (;;) {
1093 int x, h;
1094 unsigned long x2;
1095 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1096 height * VNC_DIRTY_BPL(vs),
1097 y * VNC_DIRTY_BPL(vs));
1098 if (offset == height * VNC_DIRTY_BPL(vs)) {
1099 /* no more dirty bits */
1100 break;
1102 y = offset / VNC_DIRTY_BPL(vs);
1103 x = offset % VNC_DIRTY_BPL(vs);
1104 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1105 VNC_DIRTY_BPL(vs), x);
1106 bitmap_clear(vs->dirty[y], x, x2 - x);
1107 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1108 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1109 if (x2 > x) {
1110 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1111 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1113 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1114 y += h;
1115 if (y == height) {
1116 break;
1121 vnc_job_push(job);
1122 if (sync) {
1123 vnc_jobs_join(vs);
1125 vs->force_update = 0;
1126 vs->has_dirty = 0;
1127 return n;
1130 if (vs->csock == -1) {
1131 vnc_disconnect_finish(vs);
1132 } else if (sync) {
1133 vnc_jobs_join(vs);
1136 return 0;
1139 /* audio */
1140 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1142 VncState *vs = opaque;
1144 switch (cmd) {
1145 case AUD_CNOTIFY_DISABLE:
1146 vnc_lock_output(vs);
1147 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1148 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1149 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1150 vnc_unlock_output(vs);
1151 vnc_flush(vs);
1152 break;
1154 case AUD_CNOTIFY_ENABLE:
1155 vnc_lock_output(vs);
1156 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1157 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1158 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1159 vnc_unlock_output(vs);
1160 vnc_flush(vs);
1161 break;
1165 static void audio_capture_destroy(void *opaque)
1169 static void audio_capture(void *opaque, void *buf, int size)
1171 VncState *vs = opaque;
1173 vnc_lock_output(vs);
1174 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1175 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1176 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1177 vnc_write_u32(vs, size);
1178 vnc_write(vs, buf, size);
1179 vnc_unlock_output(vs);
1180 vnc_flush(vs);
1183 static void audio_add(VncState *vs)
1185 struct audio_capture_ops ops;
1187 if (vs->audio_cap) {
1188 error_report("audio already running");
1189 return;
1192 ops.notify = audio_capture_notify;
1193 ops.destroy = audio_capture_destroy;
1194 ops.capture = audio_capture;
1196 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1197 if (!vs->audio_cap) {
1198 error_report("Failed to add audio capture");
1202 static void audio_del(VncState *vs)
1204 if (vs->audio_cap) {
1205 AUD_del_capture(vs->audio_cap, vs);
1206 vs->audio_cap = NULL;
1210 static void vnc_disconnect_start(VncState *vs)
1212 if (vs->csock == -1)
1213 return;
1214 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1215 qemu_set_fd_handler(vs->csock, NULL, NULL, NULL);
1216 closesocket(vs->csock);
1217 vs->csock = -1;
1220 void vnc_disconnect_finish(VncState *vs)
1222 int i;
1224 vnc_jobs_join(vs); /* Wait encoding jobs */
1226 vnc_lock_output(vs);
1227 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1229 buffer_free(&vs->input);
1230 buffer_free(&vs->output);
1231 buffer_free(&vs->ws_input);
1232 buffer_free(&vs->ws_output);
1234 qapi_free_VncClientInfo(vs->info);
1236 vnc_zlib_clear(vs);
1237 vnc_tight_clear(vs);
1238 vnc_zrle_clear(vs);
1240 #ifdef CONFIG_VNC_TLS
1241 vnc_tls_client_cleanup(vs);
1242 #endif /* CONFIG_VNC_TLS */
1243 #ifdef CONFIG_VNC_SASL
1244 vnc_sasl_client_cleanup(vs);
1245 #endif /* CONFIG_VNC_SASL */
1246 audio_del(vs);
1247 vnc_release_modifiers(vs);
1249 if (vs->initialized) {
1250 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1251 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1254 if (vs->vd->lock_key_sync)
1255 qemu_remove_led_event_handler(vs->led);
1256 vnc_unlock_output(vs);
1258 qemu_mutex_destroy(&vs->output_mutex);
1259 if (vs->bh != NULL) {
1260 qemu_bh_delete(vs->bh);
1262 buffer_free(&vs->jobs_buffer);
1264 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1265 g_free(vs->lossy_rect[i]);
1267 g_free(vs->lossy_rect);
1268 g_free(vs);
1271 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1273 if (ret == 0 || ret == -1) {
1274 if (ret == -1) {
1275 switch (last_errno) {
1276 case EINTR:
1277 case EAGAIN:
1278 #ifdef _WIN32
1279 case WSAEWOULDBLOCK:
1280 #endif
1281 return 0;
1282 default:
1283 break;
1287 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1288 ret, ret < 0 ? last_errno : 0);
1289 vnc_disconnect_start(vs);
1291 return 0;
1293 return ret;
1297 void vnc_client_error(VncState *vs)
1299 VNC_DEBUG("Closing down client sock: protocol error\n");
1300 vnc_disconnect_start(vs);
1303 #ifdef CONFIG_VNC_TLS
1304 static long vnc_client_write_tls(gnutls_session_t *session,
1305 const uint8_t *data,
1306 size_t datalen)
1308 long ret = gnutls_write(*session, data, datalen);
1309 if (ret < 0) {
1310 if (ret == GNUTLS_E_AGAIN) {
1311 errno = EAGAIN;
1312 } else {
1313 errno = EIO;
1315 ret = -1;
1317 return ret;
1319 #endif /* CONFIG_VNC_TLS */
1322 * Called to write a chunk of data to the client socket. The data may
1323 * be the raw data, or may have already been encoded by SASL.
1324 * The data will be written either straight onto the socket, or
1325 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1327 * NB, it is theoretically possible to have 2 layers of encryption,
1328 * both SASL, and this TLS layer. It is highly unlikely in practice
1329 * though, since SASL encryption will typically be a no-op if TLS
1330 * is active
1332 * Returns the number of bytes written, which may be less than
1333 * the requested 'datalen' if the socket would block. Returns
1334 * -1 on error, and disconnects the client socket.
1336 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1338 long ret;
1339 #ifdef CONFIG_VNC_TLS
1340 if (vs->tls.session) {
1341 ret = vnc_client_write_tls(&vs->tls.session, data, datalen);
1342 } else {
1343 #endif /* CONFIG_VNC_TLS */
1344 ret = send(vs->csock, (const void *)data, datalen, 0);
1345 #ifdef CONFIG_VNC_TLS
1347 #endif /* CONFIG_VNC_TLS */
1348 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1349 return vnc_client_io_error(vs, ret, socket_error());
1354 * Called to write buffered data to the client socket, when not
1355 * using any SASL SSF encryption layers. Will write as much data
1356 * as possible without blocking. If all buffered data is written,
1357 * will switch the FD poll() handler back to read monitoring.
1359 * Returns the number of bytes written, which may be less than
1360 * the buffered output data if the socket would block. Returns
1361 * -1 on error, and disconnects the client socket.
1363 static long vnc_client_write_plain(VncState *vs)
1365 long ret;
1367 #ifdef CONFIG_VNC_SASL
1368 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1369 vs->output.buffer, vs->output.capacity, vs->output.offset,
1370 vs->sasl.waitWriteSSF);
1372 if (vs->sasl.conn &&
1373 vs->sasl.runSSF &&
1374 vs->sasl.waitWriteSSF) {
1375 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1376 if (ret)
1377 vs->sasl.waitWriteSSF -= ret;
1378 } else
1379 #endif /* CONFIG_VNC_SASL */
1380 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1381 if (!ret)
1382 return 0;
1384 buffer_advance(&vs->output, ret);
1386 if (vs->output.offset == 0) {
1387 qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
1390 return ret;
1395 * First function called whenever there is data to be written to
1396 * the client socket. Will delegate actual work according to whether
1397 * SASL SSF layers are enabled (thus requiring encryption calls)
1399 static void vnc_client_write_locked(void *opaque)
1401 VncState *vs = opaque;
1403 #ifdef CONFIG_VNC_SASL
1404 if (vs->sasl.conn &&
1405 vs->sasl.runSSF &&
1406 !vs->sasl.waitWriteSSF) {
1407 vnc_client_write_sasl(vs);
1408 } else
1409 #endif /* CONFIG_VNC_SASL */
1411 if (vs->encode_ws) {
1412 vnc_client_write_ws(vs);
1413 } else {
1414 vnc_client_write_plain(vs);
1419 void vnc_client_write(void *opaque)
1421 VncState *vs = opaque;
1423 vnc_lock_output(vs);
1424 if (vs->output.offset || vs->ws_output.offset) {
1425 vnc_client_write_locked(opaque);
1426 } else if (vs->csock != -1) {
1427 qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
1429 vnc_unlock_output(vs);
1432 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1434 vs->read_handler = func;
1435 vs->read_handler_expect = expecting;
1438 #ifdef CONFIG_VNC_TLS
1439 static long vnc_client_read_tls(gnutls_session_t *session, uint8_t *data,
1440 size_t datalen)
1442 long ret = gnutls_read(*session, data, datalen);
1443 if (ret < 0) {
1444 if (ret == GNUTLS_E_AGAIN) {
1445 errno = EAGAIN;
1446 } else {
1447 errno = EIO;
1449 ret = -1;
1451 return ret;
1453 #endif /* CONFIG_VNC_TLS */
1456 * Called to read a chunk of data from the client socket. The data may
1457 * be the raw data, or may need to be further decoded by SASL.
1458 * The data will be read either straight from to the socket, or
1459 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1461 * NB, it is theoretically possible to have 2 layers of encryption,
1462 * both SASL, and this TLS layer. It is highly unlikely in practice
1463 * though, since SASL encryption will typically be a no-op if TLS
1464 * is active
1466 * Returns the number of bytes read, which may be less than
1467 * the requested 'datalen' if the socket would block. Returns
1468 * -1 on error, and disconnects the client socket.
1470 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1472 long ret;
1473 #ifdef CONFIG_VNC_TLS
1474 if (vs->tls.session) {
1475 ret = vnc_client_read_tls(&vs->tls.session, data, datalen);
1476 } else {
1477 #endif /* CONFIG_VNC_TLS */
1478 ret = qemu_recv(vs->csock, data, datalen, 0);
1479 #ifdef CONFIG_VNC_TLS
1481 #endif /* CONFIG_VNC_TLS */
1482 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1483 return vnc_client_io_error(vs, ret, socket_error());
1488 * Called to read data from the client socket to the input buffer,
1489 * when not using any SASL SSF encryption layers. Will read as much
1490 * data as possible without blocking.
1492 * Returns the number of bytes read. Returns -1 on error, and
1493 * disconnects the client socket.
1495 static long vnc_client_read_plain(VncState *vs)
1497 int ret;
1498 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1499 vs->input.buffer, vs->input.capacity, vs->input.offset);
1500 buffer_reserve(&vs->input, 4096);
1501 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1502 if (!ret)
1503 return 0;
1504 vs->input.offset += ret;
1505 return ret;
1508 static void vnc_jobs_bh(void *opaque)
1510 VncState *vs = opaque;
1512 vnc_jobs_consume_buffer(vs);
1516 * First function called whenever there is more data to be read from
1517 * the client socket. Will delegate actual work according to whether
1518 * SASL SSF layers are enabled (thus requiring decryption calls)
1520 void vnc_client_read(void *opaque)
1522 VncState *vs = opaque;
1523 long ret;
1525 #ifdef CONFIG_VNC_SASL
1526 if (vs->sasl.conn && vs->sasl.runSSF)
1527 ret = vnc_client_read_sasl(vs);
1528 else
1529 #endif /* CONFIG_VNC_SASL */
1530 if (vs->encode_ws) {
1531 ret = vnc_client_read_ws(vs);
1532 if (ret == -1) {
1533 vnc_disconnect_start(vs);
1534 return;
1535 } else if (ret == -2) {
1536 vnc_client_error(vs);
1537 return;
1539 } else {
1540 ret = vnc_client_read_plain(vs);
1542 if (!ret) {
1543 if (vs->csock == -1)
1544 vnc_disconnect_finish(vs);
1545 return;
1548 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1549 size_t len = vs->read_handler_expect;
1550 int ret;
1552 ret = vs->read_handler(vs, vs->input.buffer, len);
1553 if (vs->csock == -1) {
1554 vnc_disconnect_finish(vs);
1555 return;
1558 if (!ret) {
1559 buffer_advance(&vs->input, len);
1560 } else {
1561 vs->read_handler_expect = ret;
1566 void vnc_write(VncState *vs, const void *data, size_t len)
1568 buffer_reserve(&vs->output, len);
1570 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1571 qemu_set_fd_handler(vs->csock, vnc_client_read, vnc_client_write, vs);
1574 buffer_append(&vs->output, data, len);
1577 void vnc_write_s32(VncState *vs, int32_t value)
1579 vnc_write_u32(vs, *(uint32_t *)&value);
1582 void vnc_write_u32(VncState *vs, uint32_t value)
1584 uint8_t buf[4];
1586 buf[0] = (value >> 24) & 0xFF;
1587 buf[1] = (value >> 16) & 0xFF;
1588 buf[2] = (value >> 8) & 0xFF;
1589 buf[3] = value & 0xFF;
1591 vnc_write(vs, buf, 4);
1594 void vnc_write_u16(VncState *vs, uint16_t value)
1596 uint8_t buf[2];
1598 buf[0] = (value >> 8) & 0xFF;
1599 buf[1] = value & 0xFF;
1601 vnc_write(vs, buf, 2);
1604 void vnc_write_u8(VncState *vs, uint8_t value)
1606 vnc_write(vs, (char *)&value, 1);
1609 void vnc_flush(VncState *vs)
1611 vnc_lock_output(vs);
1612 if (vs->csock != -1 && (vs->output.offset ||
1613 vs->ws_output.offset)) {
1614 vnc_client_write_locked(vs);
1616 vnc_unlock_output(vs);
1619 static uint8_t read_u8(uint8_t *data, size_t offset)
1621 return data[offset];
1624 static uint16_t read_u16(uint8_t *data, size_t offset)
1626 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1629 static int32_t read_s32(uint8_t *data, size_t offset)
1631 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1632 (data[offset + 2] << 8) | data[offset + 3]);
1635 uint32_t read_u32(uint8_t *data, size_t offset)
1637 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1638 (data[offset + 2] << 8) | data[offset + 3]);
1641 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1645 static void check_pointer_type_change(Notifier *notifier, void *data)
1647 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1648 int absolute = qemu_input_is_absolute();
1650 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1651 vnc_lock_output(vs);
1652 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1653 vnc_write_u8(vs, 0);
1654 vnc_write_u16(vs, 1);
1655 vnc_framebuffer_update(vs, absolute, 0,
1656 pixman_image_get_width(vs->vd->server),
1657 pixman_image_get_height(vs->vd->server),
1658 VNC_ENCODING_POINTER_TYPE_CHANGE);
1659 vnc_unlock_output(vs);
1660 vnc_flush(vs);
1662 vs->absolute = absolute;
1665 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1667 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1668 [INPUT_BUTTON_LEFT] = 0x01,
1669 [INPUT_BUTTON_MIDDLE] = 0x02,
1670 [INPUT_BUTTON_RIGHT] = 0x04,
1671 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1672 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1674 QemuConsole *con = vs->vd->dcl.con;
1675 int width = pixman_image_get_width(vs->vd->server);
1676 int height = pixman_image_get_height(vs->vd->server);
1678 if (vs->last_bmask != button_mask) {
1679 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1680 vs->last_bmask = button_mask;
1683 if (vs->absolute) {
1684 qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
1685 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
1686 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1687 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1688 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1689 } else {
1690 if (vs->last_x != -1) {
1691 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1692 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1694 vs->last_x = x;
1695 vs->last_y = y;
1697 qemu_input_event_sync();
1700 static void reset_keys(VncState *vs)
1702 int i;
1703 for(i = 0; i < 256; i++) {
1704 if (vs->modifiers_state[i]) {
1705 qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1706 vs->modifiers_state[i] = 0;
1711 static void press_key(VncState *vs, int keysym)
1713 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1714 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1715 qemu_input_event_send_key_delay(0);
1716 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1717 qemu_input_event_send_key_delay(0);
1720 static int current_led_state(VncState *vs)
1722 int ledstate = 0;
1724 if (vs->modifiers_state[0x46]) {
1725 ledstate |= QEMU_SCROLL_LOCK_LED;
1727 if (vs->modifiers_state[0x45]) {
1728 ledstate |= QEMU_NUM_LOCK_LED;
1730 if (vs->modifiers_state[0x3a]) {
1731 ledstate |= QEMU_CAPS_LOCK_LED;
1734 return ledstate;
1737 static void vnc_led_state_change(VncState *vs)
1739 int ledstate = 0;
1741 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1742 return;
1745 ledstate = current_led_state(vs);
1746 vnc_lock_output(vs);
1747 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1748 vnc_write_u8(vs, 0);
1749 vnc_write_u16(vs, 1);
1750 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1751 vnc_write_u8(vs, ledstate);
1752 vnc_unlock_output(vs);
1753 vnc_flush(vs);
1756 static void kbd_leds(void *opaque, int ledstate)
1758 VncState *vs = opaque;
1759 int caps, num, scr;
1760 bool has_changed = (ledstate != current_led_state(vs));
1762 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1763 (ledstate & QEMU_NUM_LOCK_LED),
1764 (ledstate & QEMU_SCROLL_LOCK_LED));
1766 caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1767 num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
1768 scr = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
1770 if (vs->modifiers_state[0x3a] != caps) {
1771 vs->modifiers_state[0x3a] = caps;
1773 if (vs->modifiers_state[0x45] != num) {
1774 vs->modifiers_state[0x45] = num;
1776 if (vs->modifiers_state[0x46] != scr) {
1777 vs->modifiers_state[0x46] = scr;
1780 /* Sending the current led state message to the client */
1781 if (has_changed) {
1782 vnc_led_state_change(vs);
1786 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1788 /* QEMU console switch */
1789 switch(keycode) {
1790 case 0x2a: /* Left Shift */
1791 case 0x36: /* Right Shift */
1792 case 0x1d: /* Left CTRL */
1793 case 0x9d: /* Right CTRL */
1794 case 0x38: /* Left ALT */
1795 case 0xb8: /* Right ALT */
1796 if (down)
1797 vs->modifiers_state[keycode] = 1;
1798 else
1799 vs->modifiers_state[keycode] = 0;
1800 break;
1801 case 0x02 ... 0x0a: /* '1' to '9' keys */
1802 if (vs->vd->dcl.con == NULL &&
1803 down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1804 /* Reset the modifiers sent to the current console */
1805 reset_keys(vs);
1806 console_select(keycode - 0x02);
1807 return;
1809 break;
1810 case 0x3a: /* CapsLock */
1811 case 0x45: /* NumLock */
1812 if (down)
1813 vs->modifiers_state[keycode] ^= 1;
1814 break;
1817 /* Turn off the lock state sync logic if the client support the led
1818 state extension.
1820 if (down && vs->vd->lock_key_sync &&
1821 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1822 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1823 /* If the numlock state needs to change then simulate an additional
1824 keypress before sending this one. This will happen if the user
1825 toggles numlock away from the VNC window.
1827 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1828 if (!vs->modifiers_state[0x45]) {
1829 trace_vnc_key_sync_numlock(true);
1830 vs->modifiers_state[0x45] = 1;
1831 press_key(vs, 0xff7f);
1833 } else {
1834 if (vs->modifiers_state[0x45]) {
1835 trace_vnc_key_sync_numlock(false);
1836 vs->modifiers_state[0x45] = 0;
1837 press_key(vs, 0xff7f);
1842 if (down && vs->vd->lock_key_sync &&
1843 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1844 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1845 /* If the capslock state needs to change then simulate an additional
1846 keypress before sending this one. This will happen if the user
1847 toggles capslock away from the VNC window.
1849 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1850 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1851 int capslock = !!(vs->modifiers_state[0x3a]);
1852 if (capslock) {
1853 if (uppercase == shift) {
1854 trace_vnc_key_sync_capslock(false);
1855 vs->modifiers_state[0x3a] = 0;
1856 press_key(vs, 0xffe5);
1858 } else {
1859 if (uppercase != shift) {
1860 trace_vnc_key_sync_capslock(true);
1861 vs->modifiers_state[0x3a] = 1;
1862 press_key(vs, 0xffe5);
1867 if (qemu_console_is_graphic(NULL)) {
1868 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1869 } else {
1870 bool numlock = vs->modifiers_state[0x45];
1871 bool control = (vs->modifiers_state[0x1d] ||
1872 vs->modifiers_state[0x9d]);
1873 /* QEMU console emulation */
1874 if (down) {
1875 switch (keycode) {
1876 case 0x2a: /* Left Shift */
1877 case 0x36: /* Right Shift */
1878 case 0x1d: /* Left CTRL */
1879 case 0x9d: /* Right CTRL */
1880 case 0x38: /* Left ALT */
1881 case 0xb8: /* Right ALT */
1882 break;
1883 case 0xc8:
1884 kbd_put_keysym(QEMU_KEY_UP);
1885 break;
1886 case 0xd0:
1887 kbd_put_keysym(QEMU_KEY_DOWN);
1888 break;
1889 case 0xcb:
1890 kbd_put_keysym(QEMU_KEY_LEFT);
1891 break;
1892 case 0xcd:
1893 kbd_put_keysym(QEMU_KEY_RIGHT);
1894 break;
1895 case 0xd3:
1896 kbd_put_keysym(QEMU_KEY_DELETE);
1897 break;
1898 case 0xc7:
1899 kbd_put_keysym(QEMU_KEY_HOME);
1900 break;
1901 case 0xcf:
1902 kbd_put_keysym(QEMU_KEY_END);
1903 break;
1904 case 0xc9:
1905 kbd_put_keysym(QEMU_KEY_PAGEUP);
1906 break;
1907 case 0xd1:
1908 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1909 break;
1911 case 0x47:
1912 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1913 break;
1914 case 0x48:
1915 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1916 break;
1917 case 0x49:
1918 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1919 break;
1920 case 0x4b:
1921 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1922 break;
1923 case 0x4c:
1924 kbd_put_keysym('5');
1925 break;
1926 case 0x4d:
1927 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1928 break;
1929 case 0x4f:
1930 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1931 break;
1932 case 0x50:
1933 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1934 break;
1935 case 0x51:
1936 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1937 break;
1938 case 0x52:
1939 kbd_put_keysym('0');
1940 break;
1941 case 0x53:
1942 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1943 break;
1945 case 0xb5:
1946 kbd_put_keysym('/');
1947 break;
1948 case 0x37:
1949 kbd_put_keysym('*');
1950 break;
1951 case 0x4a:
1952 kbd_put_keysym('-');
1953 break;
1954 case 0x4e:
1955 kbd_put_keysym('+');
1956 break;
1957 case 0x9c:
1958 kbd_put_keysym('\n');
1959 break;
1961 default:
1962 if (control) {
1963 kbd_put_keysym(sym & 0x1f);
1964 } else {
1965 kbd_put_keysym(sym);
1967 break;
1973 static void vnc_release_modifiers(VncState *vs)
1975 static const int keycodes[] = {
1976 /* shift, control, alt keys, both left & right */
1977 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1979 int i, keycode;
1981 if (!qemu_console_is_graphic(NULL)) {
1982 return;
1984 for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1985 keycode = keycodes[i];
1986 if (!vs->modifiers_state[keycode]) {
1987 continue;
1989 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1993 static const char *code2name(int keycode)
1995 return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
1998 static void key_event(VncState *vs, int down, uint32_t sym)
2000 int keycode;
2001 int lsym = sym;
2003 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
2004 lsym = lsym - 'A' + 'a';
2007 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
2008 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
2009 do_key_event(vs, down, keycode, sym);
2012 static void ext_key_event(VncState *vs, int down,
2013 uint32_t sym, uint16_t keycode)
2015 /* if the user specifies a keyboard layout, always use it */
2016 if (keyboard_layout) {
2017 key_event(vs, down, sym);
2018 } else {
2019 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2020 do_key_event(vs, down, keycode, sym);
2024 static void framebuffer_update_request(VncState *vs, int incremental,
2025 int x, int y, int w, int h)
2027 int width = pixman_image_get_width(vs->vd->server);
2028 int height = pixman_image_get_height(vs->vd->server);
2030 vs->need_update = 1;
2032 if (incremental) {
2033 return;
2036 vs->force_update = 1;
2037 vnc_set_area_dirty(vs->dirty, width, height, x, y, w, h);
2040 static void send_ext_key_event_ack(VncState *vs)
2042 vnc_lock_output(vs);
2043 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2044 vnc_write_u8(vs, 0);
2045 vnc_write_u16(vs, 1);
2046 vnc_framebuffer_update(vs, 0, 0,
2047 pixman_image_get_width(vs->vd->server),
2048 pixman_image_get_height(vs->vd->server),
2049 VNC_ENCODING_EXT_KEY_EVENT);
2050 vnc_unlock_output(vs);
2051 vnc_flush(vs);
2054 static void send_ext_audio_ack(VncState *vs)
2056 vnc_lock_output(vs);
2057 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2058 vnc_write_u8(vs, 0);
2059 vnc_write_u16(vs, 1);
2060 vnc_framebuffer_update(vs, 0, 0,
2061 pixman_image_get_width(vs->vd->server),
2062 pixman_image_get_height(vs->vd->server),
2063 VNC_ENCODING_AUDIO);
2064 vnc_unlock_output(vs);
2065 vnc_flush(vs);
2068 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2070 int i;
2071 unsigned int enc = 0;
2073 vs->features = 0;
2074 vs->vnc_encoding = 0;
2075 vs->tight.compression = 9;
2076 vs->tight.quality = -1; /* Lossless by default */
2077 vs->absolute = -1;
2080 * Start from the end because the encodings are sent in order of preference.
2081 * This way the preferred encoding (first encoding defined in the array)
2082 * will be set at the end of the loop.
2084 for (i = n_encodings - 1; i >= 0; i--) {
2085 enc = encodings[i];
2086 switch (enc) {
2087 case VNC_ENCODING_RAW:
2088 vs->vnc_encoding = enc;
2089 break;
2090 case VNC_ENCODING_COPYRECT:
2091 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2092 break;
2093 case VNC_ENCODING_HEXTILE:
2094 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2095 vs->vnc_encoding = enc;
2096 break;
2097 case VNC_ENCODING_TIGHT:
2098 vs->features |= VNC_FEATURE_TIGHT_MASK;
2099 vs->vnc_encoding = enc;
2100 break;
2101 #ifdef CONFIG_VNC_PNG
2102 case VNC_ENCODING_TIGHT_PNG:
2103 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2104 vs->vnc_encoding = enc;
2105 break;
2106 #endif
2107 case VNC_ENCODING_ZLIB:
2108 vs->features |= VNC_FEATURE_ZLIB_MASK;
2109 vs->vnc_encoding = enc;
2110 break;
2111 case VNC_ENCODING_ZRLE:
2112 vs->features |= VNC_FEATURE_ZRLE_MASK;
2113 vs->vnc_encoding = enc;
2114 break;
2115 case VNC_ENCODING_ZYWRLE:
2116 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2117 vs->vnc_encoding = enc;
2118 break;
2119 case VNC_ENCODING_DESKTOPRESIZE:
2120 vs->features |= VNC_FEATURE_RESIZE_MASK;
2121 break;
2122 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2123 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2124 break;
2125 case VNC_ENCODING_RICH_CURSOR:
2126 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2127 break;
2128 case VNC_ENCODING_EXT_KEY_EVENT:
2129 send_ext_key_event_ack(vs);
2130 break;
2131 case VNC_ENCODING_AUDIO:
2132 send_ext_audio_ack(vs);
2133 break;
2134 case VNC_ENCODING_WMVi:
2135 vs->features |= VNC_FEATURE_WMVI_MASK;
2136 break;
2137 case VNC_ENCODING_LED_STATE:
2138 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2139 break;
2140 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2141 vs->tight.compression = (enc & 0x0F);
2142 break;
2143 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2144 if (vs->vd->lossy) {
2145 vs->tight.quality = (enc & 0x0F);
2147 break;
2148 default:
2149 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2150 break;
2153 vnc_desktop_resize(vs);
2154 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2155 vnc_led_state_change(vs);
2158 static void set_pixel_conversion(VncState *vs)
2160 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2162 if (fmt == VNC_SERVER_FB_FORMAT) {
2163 vs->write_pixels = vnc_write_pixels_copy;
2164 vnc_hextile_set_pixel_conversion(vs, 0);
2165 } else {
2166 vs->write_pixels = vnc_write_pixels_generic;
2167 vnc_hextile_set_pixel_conversion(vs, 1);
2171 static void set_pixel_format(VncState *vs,
2172 int bits_per_pixel, int depth,
2173 int big_endian_flag, int true_color_flag,
2174 int red_max, int green_max, int blue_max,
2175 int red_shift, int green_shift, int blue_shift)
2177 if (!true_color_flag) {
2178 vnc_client_error(vs);
2179 return;
2182 switch (bits_per_pixel) {
2183 case 8:
2184 case 16:
2185 case 32:
2186 break;
2187 default:
2188 vnc_client_error(vs);
2189 return;
2192 vs->client_pf.rmax = red_max;
2193 vs->client_pf.rbits = hweight_long(red_max);
2194 vs->client_pf.rshift = red_shift;
2195 vs->client_pf.rmask = red_max << red_shift;
2196 vs->client_pf.gmax = green_max;
2197 vs->client_pf.gbits = hweight_long(green_max);
2198 vs->client_pf.gshift = green_shift;
2199 vs->client_pf.gmask = green_max << green_shift;
2200 vs->client_pf.bmax = blue_max;
2201 vs->client_pf.bbits = hweight_long(blue_max);
2202 vs->client_pf.bshift = blue_shift;
2203 vs->client_pf.bmask = blue_max << blue_shift;
2204 vs->client_pf.bits_per_pixel = bits_per_pixel;
2205 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2206 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2207 vs->client_be = big_endian_flag;
2209 set_pixel_conversion(vs);
2211 graphic_hw_invalidate(vs->vd->dcl.con);
2212 graphic_hw_update(vs->vd->dcl.con);
2215 static void pixel_format_message (VncState *vs) {
2216 char pad[3] = { 0, 0, 0 };
2218 vs->client_pf = qemu_default_pixelformat(32);
2220 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2221 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2223 #ifdef HOST_WORDS_BIGENDIAN
2224 vnc_write_u8(vs, 1); /* big-endian-flag */
2225 #else
2226 vnc_write_u8(vs, 0); /* big-endian-flag */
2227 #endif
2228 vnc_write_u8(vs, 1); /* true-color-flag */
2229 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2230 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2231 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2232 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2233 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2234 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2235 vnc_write(vs, pad, 3); /* padding */
2237 vnc_hextile_set_pixel_conversion(vs, 0);
2238 vs->write_pixels = vnc_write_pixels_copy;
2241 static void vnc_colordepth(VncState *vs)
2243 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2244 /* Sending a WMVi message to notify the client*/
2245 vnc_lock_output(vs);
2246 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2247 vnc_write_u8(vs, 0);
2248 vnc_write_u16(vs, 1); /* number of rects */
2249 vnc_framebuffer_update(vs, 0, 0,
2250 pixman_image_get_width(vs->vd->server),
2251 pixman_image_get_height(vs->vd->server),
2252 VNC_ENCODING_WMVi);
2253 pixel_format_message(vs);
2254 vnc_unlock_output(vs);
2255 vnc_flush(vs);
2256 } else {
2257 set_pixel_conversion(vs);
2261 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2263 int i;
2264 uint16_t limit;
2265 VncDisplay *vd = vs->vd;
2267 if (data[0] > 3) {
2268 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2271 switch (data[0]) {
2272 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2273 if (len == 1)
2274 return 20;
2276 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
2277 read_u8(data, 6), read_u8(data, 7),
2278 read_u16(data, 8), read_u16(data, 10),
2279 read_u16(data, 12), read_u8(data, 14),
2280 read_u8(data, 15), read_u8(data, 16));
2281 break;
2282 case VNC_MSG_CLIENT_SET_ENCODINGS:
2283 if (len == 1)
2284 return 4;
2286 if (len == 4) {
2287 limit = read_u16(data, 2);
2288 if (limit > 0)
2289 return 4 + (limit * 4);
2290 } else
2291 limit = read_u16(data, 2);
2293 for (i = 0; i < limit; i++) {
2294 int32_t val = read_s32(data, 4 + (i * 4));
2295 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2298 set_encodings(vs, (int32_t *)(data + 4), limit);
2299 break;
2300 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2301 if (len == 1)
2302 return 10;
2304 framebuffer_update_request(vs,
2305 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2306 read_u16(data, 6), read_u16(data, 8));
2307 break;
2308 case VNC_MSG_CLIENT_KEY_EVENT:
2309 if (len == 1)
2310 return 8;
2312 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2313 break;
2314 case VNC_MSG_CLIENT_POINTER_EVENT:
2315 if (len == 1)
2316 return 6;
2318 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2319 break;
2320 case VNC_MSG_CLIENT_CUT_TEXT:
2321 if (len == 1) {
2322 return 8;
2324 if (len == 8) {
2325 uint32_t dlen = read_u32(data, 4);
2326 if (dlen > (1 << 20)) {
2327 error_report("vnc: client_cut_text msg payload has %u bytes"
2328 " which exceeds our limit of 1MB.", dlen);
2329 vnc_client_error(vs);
2330 break;
2332 if (dlen > 0) {
2333 return 8 + dlen;
2337 client_cut_text(vs, read_u32(data, 4), data + 8);
2338 break;
2339 case VNC_MSG_CLIENT_QEMU:
2340 if (len == 1)
2341 return 2;
2343 switch (read_u8(data, 1)) {
2344 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2345 if (len == 2)
2346 return 12;
2348 ext_key_event(vs, read_u16(data, 2),
2349 read_u32(data, 4), read_u32(data, 8));
2350 break;
2351 case VNC_MSG_CLIENT_QEMU_AUDIO:
2352 if (len == 2)
2353 return 4;
2355 switch (read_u16 (data, 2)) {
2356 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2357 audio_add(vs);
2358 break;
2359 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2360 audio_del(vs);
2361 break;
2362 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2363 if (len == 4)
2364 return 10;
2365 switch (read_u8(data, 4)) {
2366 case 0: vs->as.fmt = AUD_FMT_U8; break;
2367 case 1: vs->as.fmt = AUD_FMT_S8; break;
2368 case 2: vs->as.fmt = AUD_FMT_U16; break;
2369 case 3: vs->as.fmt = AUD_FMT_S16; break;
2370 case 4: vs->as.fmt = AUD_FMT_U32; break;
2371 case 5: vs->as.fmt = AUD_FMT_S32; break;
2372 default:
2373 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2374 vnc_client_error(vs);
2375 break;
2377 vs->as.nchannels = read_u8(data, 5);
2378 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2379 VNC_DEBUG("Invalid audio channel coount %d\n",
2380 read_u8(data, 5));
2381 vnc_client_error(vs);
2382 break;
2384 vs->as.freq = read_u32(data, 6);
2385 break;
2386 default:
2387 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2388 vnc_client_error(vs);
2389 break;
2391 break;
2393 default:
2394 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2395 vnc_client_error(vs);
2396 break;
2398 break;
2399 default:
2400 VNC_DEBUG("Msg: %d\n", data[0]);
2401 vnc_client_error(vs);
2402 break;
2405 vnc_read_when(vs, protocol_client_msg, 1);
2406 return 0;
2409 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2411 char buf[1024];
2412 VncShareMode mode;
2413 int size;
2415 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2416 switch (vs->vd->share_policy) {
2417 case VNC_SHARE_POLICY_IGNORE:
2419 * Ignore the shared flag. Nothing to do here.
2421 * Doesn't conform to the rfb spec but is traditional qemu
2422 * behavior, thus left here as option for compatibility
2423 * reasons.
2425 break;
2426 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2428 * Policy: Allow clients ask for exclusive access.
2430 * Implementation: When a client asks for exclusive access,
2431 * disconnect all others. Shared connects are allowed as long
2432 * as no exclusive connection exists.
2434 * This is how the rfb spec suggests to handle the shared flag.
2436 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2437 VncState *client;
2438 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2439 if (vs == client) {
2440 continue;
2442 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2443 client->share_mode != VNC_SHARE_MODE_SHARED) {
2444 continue;
2446 vnc_disconnect_start(client);
2449 if (mode == VNC_SHARE_MODE_SHARED) {
2450 if (vs->vd->num_exclusive > 0) {
2451 vnc_disconnect_start(vs);
2452 return 0;
2455 break;
2456 case VNC_SHARE_POLICY_FORCE_SHARED:
2458 * Policy: Shared connects only.
2459 * Implementation: Disallow clients asking for exclusive access.
2461 * Useful for shared desktop sessions where you don't want
2462 * someone forgetting to say -shared when running the vnc
2463 * client disconnect everybody else.
2465 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2466 vnc_disconnect_start(vs);
2467 return 0;
2469 break;
2471 vnc_set_share_mode(vs, mode);
2473 if (vs->vd->num_shared > vs->vd->connections_limit) {
2474 vnc_disconnect_start(vs);
2475 return 0;
2478 vs->client_width = pixman_image_get_width(vs->vd->server);
2479 vs->client_height = pixman_image_get_height(vs->vd->server);
2480 vnc_write_u16(vs, vs->client_width);
2481 vnc_write_u16(vs, vs->client_height);
2483 pixel_format_message(vs);
2485 if (qemu_name)
2486 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2487 else
2488 size = snprintf(buf, sizeof(buf), "QEMU");
2490 vnc_write_u32(vs, size);
2491 vnc_write(vs, buf, size);
2492 vnc_flush(vs);
2494 vnc_client_cache_auth(vs);
2495 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2497 vnc_read_when(vs, protocol_client_msg, 1);
2499 return 0;
2502 void start_client_init(VncState *vs)
2504 vnc_read_when(vs, protocol_client_init, 1);
2507 static void make_challenge(VncState *vs)
2509 int i;
2511 srand(time(NULL)+getpid()+getpid()*987654+rand());
2513 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2514 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2517 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2519 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2520 size_t i, pwlen;
2521 unsigned char key[8];
2522 time_t now = time(NULL);
2523 QCryptoCipher *cipher;
2524 Error *err = NULL;
2526 if (!vs->vd->password) {
2527 VNC_DEBUG("No password configured on server");
2528 goto reject;
2530 if (vs->vd->expires < now) {
2531 VNC_DEBUG("Password is expired");
2532 goto reject;
2535 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2537 /* Calculate the expected challenge response */
2538 pwlen = strlen(vs->vd->password);
2539 for (i=0; i<sizeof(key); i++)
2540 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2542 cipher = qcrypto_cipher_new(
2543 QCRYPTO_CIPHER_ALG_DES_RFB,
2544 QCRYPTO_CIPHER_MODE_ECB,
2545 key, G_N_ELEMENTS(key),
2546 &err);
2547 if (!cipher) {
2548 VNC_DEBUG("Cannot initialize cipher %s",
2549 error_get_pretty(err));
2550 error_free(err);
2551 goto reject;
2554 if (qcrypto_cipher_encrypt(cipher,
2555 vs->challenge,
2556 response,
2557 VNC_AUTH_CHALLENGE_SIZE,
2558 &err) < 0) {
2559 VNC_DEBUG("Cannot encrypt challenge %s",
2560 error_get_pretty(err));
2561 error_free(err);
2562 goto reject;
2565 /* Compare expected vs actual challenge response */
2566 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2567 VNC_DEBUG("Client challenge response did not match\n");
2568 goto reject;
2569 } else {
2570 VNC_DEBUG("Accepting VNC challenge response\n");
2571 vnc_write_u32(vs, 0); /* Accept auth */
2572 vnc_flush(vs);
2574 start_client_init(vs);
2576 return 0;
2578 reject:
2579 vnc_write_u32(vs, 1); /* Reject auth */
2580 if (vs->minor >= 8) {
2581 static const char err[] = "Authentication failed";
2582 vnc_write_u32(vs, sizeof(err));
2583 vnc_write(vs, err, sizeof(err));
2585 vnc_flush(vs);
2586 vnc_client_error(vs);
2587 return 0;
2590 void start_auth_vnc(VncState *vs)
2592 make_challenge(vs);
2593 /* Send client a 'random' challenge */
2594 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2595 vnc_flush(vs);
2597 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2601 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2603 /* We only advertise 1 auth scheme at a time, so client
2604 * must pick the one we sent. Verify this */
2605 if (data[0] != vs->auth) { /* Reject auth */
2606 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2607 vnc_write_u32(vs, 1);
2608 if (vs->minor >= 8) {
2609 static const char err[] = "Authentication failed";
2610 vnc_write_u32(vs, sizeof(err));
2611 vnc_write(vs, err, sizeof(err));
2613 vnc_client_error(vs);
2614 } else { /* Accept requested auth */
2615 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2616 switch (vs->auth) {
2617 case VNC_AUTH_NONE:
2618 VNC_DEBUG("Accept auth none\n");
2619 if (vs->minor >= 8) {
2620 vnc_write_u32(vs, 0); /* Accept auth completion */
2621 vnc_flush(vs);
2623 start_client_init(vs);
2624 break;
2626 case VNC_AUTH_VNC:
2627 VNC_DEBUG("Start VNC auth\n");
2628 start_auth_vnc(vs);
2629 break;
2631 #ifdef CONFIG_VNC_TLS
2632 case VNC_AUTH_VENCRYPT:
2633 VNC_DEBUG("Accept VeNCrypt auth\n");
2634 start_auth_vencrypt(vs);
2635 break;
2636 #endif /* CONFIG_VNC_TLS */
2638 #ifdef CONFIG_VNC_SASL
2639 case VNC_AUTH_SASL:
2640 VNC_DEBUG("Accept SASL auth\n");
2641 start_auth_sasl(vs);
2642 break;
2643 #endif /* CONFIG_VNC_SASL */
2645 default: /* Should not be possible, but just in case */
2646 VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2647 vnc_write_u8(vs, 1);
2648 if (vs->minor >= 8) {
2649 static const char err[] = "Authentication failed";
2650 vnc_write_u32(vs, sizeof(err));
2651 vnc_write(vs, err, sizeof(err));
2653 vnc_client_error(vs);
2656 return 0;
2659 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2661 char local[13];
2663 memcpy(local, version, 12);
2664 local[12] = 0;
2666 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2667 VNC_DEBUG("Malformed protocol version %s\n", local);
2668 vnc_client_error(vs);
2669 return 0;
2671 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2672 if (vs->major != 3 ||
2673 (vs->minor != 3 &&
2674 vs->minor != 4 &&
2675 vs->minor != 5 &&
2676 vs->minor != 7 &&
2677 vs->minor != 8)) {
2678 VNC_DEBUG("Unsupported client version\n");
2679 vnc_write_u32(vs, VNC_AUTH_INVALID);
2680 vnc_flush(vs);
2681 vnc_client_error(vs);
2682 return 0;
2684 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2685 * as equivalent to v3.3 by servers
2687 if (vs->minor == 4 || vs->minor == 5)
2688 vs->minor = 3;
2690 if (vs->minor == 3) {
2691 if (vs->auth == VNC_AUTH_NONE) {
2692 VNC_DEBUG("Tell client auth none\n");
2693 vnc_write_u32(vs, vs->auth);
2694 vnc_flush(vs);
2695 start_client_init(vs);
2696 } else if (vs->auth == VNC_AUTH_VNC) {
2697 VNC_DEBUG("Tell client VNC auth\n");
2698 vnc_write_u32(vs, vs->auth);
2699 vnc_flush(vs);
2700 start_auth_vnc(vs);
2701 } else {
2702 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2703 vnc_write_u32(vs, VNC_AUTH_INVALID);
2704 vnc_flush(vs);
2705 vnc_client_error(vs);
2707 } else {
2708 VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2709 vnc_write_u8(vs, 1); /* num auth */
2710 vnc_write_u8(vs, vs->auth);
2711 vnc_read_when(vs, protocol_client_auth, 1);
2712 vnc_flush(vs);
2715 return 0;
2718 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2720 struct VncSurface *vs = &vd->guest;
2722 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2725 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2727 int i, j;
2729 w = (x + w) / VNC_STAT_RECT;
2730 h = (y + h) / VNC_STAT_RECT;
2731 x /= VNC_STAT_RECT;
2732 y /= VNC_STAT_RECT;
2734 for (j = y; j <= h; j++) {
2735 for (i = x; i <= w; i++) {
2736 vs->lossy_rect[j][i] = 1;
2741 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2743 VncState *vs;
2744 int sty = y / VNC_STAT_RECT;
2745 int stx = x / VNC_STAT_RECT;
2746 int has_dirty = 0;
2748 y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2749 x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2751 QTAILQ_FOREACH(vs, &vd->clients, next) {
2752 int j;
2754 /* kernel send buffers are full -> refresh later */
2755 if (vs->output.offset) {
2756 continue;
2759 if (!vs->lossy_rect[sty][stx]) {
2760 continue;
2763 vs->lossy_rect[sty][stx] = 0;
2764 for (j = 0; j < VNC_STAT_RECT; ++j) {
2765 bitmap_set(vs->dirty[y + j],
2766 x / VNC_DIRTY_PIXELS_PER_BIT,
2767 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2769 has_dirty++;
2772 return has_dirty;
2775 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2777 int width = pixman_image_get_width(vd->guest.fb);
2778 int height = pixman_image_get_height(vd->guest.fb);
2779 int x, y;
2780 struct timeval res;
2781 int has_dirty = 0;
2783 for (y = 0; y < height; y += VNC_STAT_RECT) {
2784 for (x = 0; x < width; x += VNC_STAT_RECT) {
2785 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2787 rect->updated = false;
2791 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2793 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2794 return has_dirty;
2796 vd->guest.last_freq_check = *tv;
2798 for (y = 0; y < height; y += VNC_STAT_RECT) {
2799 for (x = 0; x < width; x += VNC_STAT_RECT) {
2800 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2801 int count = ARRAY_SIZE(rect->times);
2802 struct timeval min, max;
2804 if (!timerisset(&rect->times[count - 1])) {
2805 continue ;
2808 max = rect->times[(rect->idx + count - 1) % count];
2809 qemu_timersub(tv, &max, &res);
2811 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2812 rect->freq = 0;
2813 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2814 memset(rect->times, 0, sizeof (rect->times));
2815 continue ;
2818 min = rect->times[rect->idx];
2819 max = rect->times[(rect->idx + count - 1) % count];
2820 qemu_timersub(&max, &min, &res);
2822 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2823 rect->freq /= count;
2824 rect->freq = 1. / rect->freq;
2827 return has_dirty;
2830 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2832 int i, j;
2833 double total = 0;
2834 int num = 0;
2836 x = (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2837 y = (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2839 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2840 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2841 total += vnc_stat_rect(vs->vd, i, j)->freq;
2842 num++;
2846 if (num) {
2847 return total / num;
2848 } else {
2849 return 0;
2853 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2855 VncRectStat *rect;
2857 rect = vnc_stat_rect(vd, x, y);
2858 if (rect->updated) {
2859 return ;
2861 rect->times[rect->idx] = *tv;
2862 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2863 rect->updated = true;
2866 static int vnc_refresh_server_surface(VncDisplay *vd)
2868 int width = MIN(pixman_image_get_width(vd->guest.fb),
2869 pixman_image_get_width(vd->server));
2870 int height = MIN(pixman_image_get_height(vd->guest.fb),
2871 pixman_image_get_height(vd->server));
2872 int cmp_bytes, server_stride, min_stride, guest_stride, y = 0;
2873 uint8_t *guest_row0 = NULL, *server_row0;
2874 VncState *vs;
2875 int has_dirty = 0;
2876 pixman_image_t *tmpbuf = NULL;
2878 struct timeval tv = { 0, 0 };
2880 if (!vd->non_adaptive) {
2881 gettimeofday(&tv, NULL);
2882 has_dirty = vnc_update_stats(vd, &tv);
2886 * Walk through the guest dirty map.
2887 * Check and copy modified bits from guest to server surface.
2888 * Update server dirty map.
2890 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2891 server_stride = guest_stride = pixman_image_get_stride(vd->server);
2892 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2893 server_stride);
2894 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2895 int width = pixman_image_get_width(vd->server);
2896 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2897 } else {
2898 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2899 guest_stride = pixman_image_get_stride(vd->guest.fb);
2901 min_stride = MIN(server_stride, guest_stride);
2903 for (;;) {
2904 int x;
2905 uint8_t *guest_ptr, *server_ptr;
2906 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2907 height * VNC_DIRTY_BPL(&vd->guest),
2908 y * VNC_DIRTY_BPL(&vd->guest));
2909 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2910 /* no more dirty bits */
2911 break;
2913 y = offset / VNC_DIRTY_BPL(&vd->guest);
2914 x = offset % VNC_DIRTY_BPL(&vd->guest);
2916 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2918 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2919 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2920 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2921 } else {
2922 guest_ptr = guest_row0 + y * guest_stride;
2924 guest_ptr += x * cmp_bytes;
2926 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2927 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2928 int _cmp_bytes = cmp_bytes;
2929 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2930 continue;
2932 if ((x + 1) * cmp_bytes > min_stride) {
2933 _cmp_bytes = min_stride - x * cmp_bytes;
2935 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2936 continue;
2938 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2939 if (!vd->non_adaptive) {
2940 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2941 y, &tv);
2943 QTAILQ_FOREACH(vs, &vd->clients, next) {
2944 set_bit(x, vs->dirty[y]);
2946 has_dirty++;
2949 y++;
2951 qemu_pixman_image_unref(tmpbuf);
2952 return has_dirty;
2955 static void vnc_refresh(DisplayChangeListener *dcl)
2957 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2958 VncState *vs, *vn;
2959 int has_dirty, rects = 0;
2961 if (QTAILQ_EMPTY(&vd->clients)) {
2962 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2963 return;
2966 graphic_hw_update(vd->dcl.con);
2968 if (vnc_trylock_display(vd)) {
2969 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2970 return;
2973 has_dirty = vnc_refresh_server_surface(vd);
2974 vnc_unlock_display(vd);
2976 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2977 rects += vnc_update_client(vs, has_dirty, false);
2978 /* vs might be free()ed here */
2981 if (has_dirty && rects) {
2982 vd->dcl.update_interval /= 2;
2983 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
2984 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
2986 } else {
2987 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
2988 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
2989 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
2994 static void vnc_connect(VncDisplay *vd, int csock,
2995 bool skipauth, bool websocket)
2997 VncState *vs = g_malloc0(sizeof(VncState));
2998 int i;
3000 vs->csock = csock;
3001 vs->vd = vd;
3003 if (skipauth) {
3004 vs->auth = VNC_AUTH_NONE;
3005 vs->subauth = VNC_AUTH_INVALID;
3006 } else {
3007 if (websocket) {
3008 vs->auth = vd->ws_auth;
3009 vs->subauth = VNC_AUTH_INVALID;
3010 } else {
3011 vs->auth = vd->auth;
3012 vs->subauth = vd->subauth;
3015 VNC_DEBUG("Client sock=%d ws=%d auth=%d subauth=%d\n",
3016 csock, websocket, vs->auth, vs->subauth);
3018 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3019 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3020 vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
3023 VNC_DEBUG("New client on socket %d\n", csock);
3024 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3025 qemu_set_nonblock(vs->csock);
3026 if (websocket) {
3027 vs->websocket = 1;
3028 #ifdef CONFIG_VNC_TLS
3029 if (vd->ws_tls) {
3030 qemu_set_fd_handler(vs->csock, vncws_tls_handshake_io, NULL, vs);
3031 } else
3032 #endif /* CONFIG_VNC_TLS */
3034 qemu_set_fd_handler(vs->csock, vncws_handshake_read, NULL, vs);
3036 } else
3038 qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
3041 vnc_client_cache_addr(vs);
3042 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3043 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3045 if (!vs->websocket) {
3046 vnc_init_state(vs);
3049 if (vd->num_connecting > vd->connections_limit) {
3050 QTAILQ_FOREACH(vs, &vd->clients, next) {
3051 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3052 vnc_disconnect_start(vs);
3053 return;
3059 void vnc_init_state(VncState *vs)
3061 vs->initialized = true;
3062 VncDisplay *vd = vs->vd;
3064 vs->last_x = -1;
3065 vs->last_y = -1;
3067 vs->as.freq = 44100;
3068 vs->as.nchannels = 2;
3069 vs->as.fmt = AUD_FMT_S16;
3070 vs->as.endianness = 0;
3072 qemu_mutex_init(&vs->output_mutex);
3073 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3075 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3077 graphic_hw_update(vd->dcl.con);
3079 vnc_write(vs, "RFB 003.008\n", 12);
3080 vnc_flush(vs);
3081 vnc_read_when(vs, protocol_version, 12);
3082 reset_keys(vs);
3083 if (vs->vd->lock_key_sync)
3084 vs->led = qemu_add_led_event_handler(kbd_leds, vs);
3086 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3087 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3089 /* vs might be free()ed here */
3092 static void vnc_listen_read(void *opaque, bool websocket)
3094 VncDisplay *vs = opaque;
3095 struct sockaddr_in addr;
3096 socklen_t addrlen = sizeof(addr);
3097 int csock;
3099 /* Catch-up */
3100 graphic_hw_update(vs->dcl.con);
3101 if (websocket) {
3102 csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
3103 } else {
3104 csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
3107 if (csock != -1) {
3108 socket_set_nodelay(csock);
3109 vnc_connect(vs, csock, false, websocket);
3113 static void vnc_listen_regular_read(void *opaque)
3115 vnc_listen_read(opaque, false);
3118 static void vnc_listen_websocket_read(void *opaque)
3120 vnc_listen_read(opaque, true);
3123 static const DisplayChangeListenerOps dcl_ops = {
3124 .dpy_name = "vnc",
3125 .dpy_refresh = vnc_refresh,
3126 .dpy_gfx_copy = vnc_dpy_copy,
3127 .dpy_gfx_update = vnc_dpy_update,
3128 .dpy_gfx_switch = vnc_dpy_switch,
3129 .dpy_gfx_check_format = qemu_pixman_check_format,
3130 .dpy_mouse_set = vnc_mouse_set,
3131 .dpy_cursor_define = vnc_dpy_cursor_define,
3134 void vnc_display_init(const char *id)
3136 VncDisplay *vs;
3138 if (vnc_display_find(id) != NULL) {
3139 return;
3141 vs = g_malloc0(sizeof(*vs));
3143 vs->id = strdup(id);
3144 QTAILQ_INSERT_TAIL(&vnc_displays, vs, next);
3146 vs->lsock = -1;
3147 vs->lwebsock = -1;
3149 QTAILQ_INIT(&vs->clients);
3150 vs->expires = TIME_MAX;
3152 if (keyboard_layout) {
3153 trace_vnc_key_map_init(keyboard_layout);
3154 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
3155 } else {
3156 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
3159 if (!vs->kbd_layout)
3160 exit(1);
3162 qemu_mutex_init(&vs->mutex);
3163 vnc_start_worker_thread();
3165 vs->dcl.ops = &dcl_ops;
3166 register_displaychangelistener(&vs->dcl);
3170 static void vnc_display_close(VncDisplay *vs)
3172 if (!vs)
3173 return;
3174 vs->enabled = false;
3175 vs->is_unix = false;
3176 if (vs->lsock != -1) {
3177 qemu_set_fd_handler(vs->lsock, NULL, NULL, NULL);
3178 close(vs->lsock);
3179 vs->lsock = -1;
3181 vs->ws_enabled = false;
3182 if (vs->lwebsock != -1) {
3183 qemu_set_fd_handler(vs->lwebsock, NULL, NULL, NULL);
3184 close(vs->lwebsock);
3185 vs->lwebsock = -1;
3187 vs->auth = VNC_AUTH_INVALID;
3188 vs->subauth = VNC_AUTH_INVALID;
3189 #ifdef CONFIG_VNC_TLS
3190 vs->tls.x509verify = 0;
3191 #endif
3194 int vnc_display_password(const char *id, const char *password)
3196 VncDisplay *vs = vnc_display_find(id);
3198 if (!vs) {
3199 return -EINVAL;
3201 if (vs->auth == VNC_AUTH_NONE) {
3202 error_printf_unless_qmp("If you want use passwords please enable "
3203 "password auth using '-vnc ${dpy},password'.");
3204 return -EINVAL;
3207 g_free(vs->password);
3208 vs->password = g_strdup(password);
3210 return 0;
3213 int vnc_display_pw_expire(const char *id, time_t expires)
3215 VncDisplay *vs = vnc_display_find(id);
3217 if (!vs) {
3218 return -EINVAL;
3221 vs->expires = expires;
3222 return 0;
3225 char *vnc_display_local_addr(const char *id)
3227 VncDisplay *vs = vnc_display_find(id);
3229 assert(vs);
3230 return vnc_socket_local_addr("%s:%s", vs->lsock);
3233 static QemuOptsList qemu_vnc_opts = {
3234 .name = "vnc",
3235 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3236 .implied_opt_name = "vnc",
3237 .desc = {
3239 .name = "vnc",
3240 .type = QEMU_OPT_STRING,
3242 .name = "websocket",
3243 .type = QEMU_OPT_STRING,
3245 .name = "x509",
3246 .type = QEMU_OPT_STRING,
3248 .name = "share",
3249 .type = QEMU_OPT_STRING,
3251 .name = "display",
3252 .type = QEMU_OPT_STRING,
3254 .name = "head",
3255 .type = QEMU_OPT_NUMBER,
3257 .name = "connections",
3258 .type = QEMU_OPT_NUMBER,
3260 .name = "to",
3261 .type = QEMU_OPT_NUMBER,
3263 .name = "ipv4",
3264 .type = QEMU_OPT_BOOL,
3266 .name = "ipv6",
3267 .type = QEMU_OPT_BOOL,
3269 .name = "password",
3270 .type = QEMU_OPT_BOOL,
3272 .name = "reverse",
3273 .type = QEMU_OPT_BOOL,
3275 .name = "lock-key-sync",
3276 .type = QEMU_OPT_BOOL,
3278 .name = "sasl",
3279 .type = QEMU_OPT_BOOL,
3281 .name = "tls",
3282 .type = QEMU_OPT_BOOL,
3284 .name = "x509verify",
3285 .type = QEMU_OPT_STRING,
3287 .name = "acl",
3288 .type = QEMU_OPT_BOOL,
3290 .name = "lossy",
3291 .type = QEMU_OPT_BOOL,
3293 .name = "non-adaptive",
3294 .type = QEMU_OPT_BOOL,
3296 { /* end of list */ }
3301 static void
3302 vnc_display_setup_auth(VncDisplay *vs,
3303 bool password,
3304 bool sasl,
3305 bool tls,
3306 bool x509,
3307 bool websocket)
3310 * We have a choice of 3 authentication options
3312 * 1. none
3313 * 2. vnc
3314 * 3. sasl
3316 * The channel can be run in 2 modes
3318 * 1. clear
3319 * 2. tls
3321 * And TLS can use 2 types of credentials
3323 * 1. anon
3324 * 2. x509
3326 * We thus have 9 possible logical combinations
3328 * 1. clear + none
3329 * 2. clear + vnc
3330 * 3. clear + sasl
3331 * 4. tls + anon + none
3332 * 5. tls + anon + vnc
3333 * 6. tls + anon + sasl
3334 * 7. tls + x509 + none
3335 * 8. tls + x509 + vnc
3336 * 9. tls + x509 + sasl
3338 * These need to be mapped into the VNC auth schemes
3339 * in an appropriate manner. In regular VNC, all the
3340 * TLS options get mapped into VNC_AUTH_VENCRYPT
3341 * sub-auth types.
3343 * In websockets, the https:// protocol already provides
3344 * TLS support, so there is no need to make use of the
3345 * VeNCrypt extension. Furthermore, websockets browser
3346 * clients could not use VeNCrypt even if they wanted to,
3347 * as they cannot control when the TLS handshake takes
3348 * place. Thus there is no option but to rely on https://,
3349 * meaning combinations 4->6 and 7->9 will be mapped to
3350 * VNC auth schemes in the same way as combos 1->3.
3352 * Regardless of fact that we have a different mapping to
3353 * VNC auth mechs for plain VNC vs websockets VNC, the end
3354 * result has the same security characteristics.
3356 if (password) {
3357 if (tls) {
3358 vs->auth = VNC_AUTH_VENCRYPT;
3359 if (websocket) {
3360 vs->ws_tls = true;
3362 if (x509) {
3363 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3364 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
3365 } else {
3366 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3367 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3369 } else {
3370 VNC_DEBUG("Initializing VNC server with password auth\n");
3371 vs->auth = VNC_AUTH_VNC;
3372 vs->subauth = VNC_AUTH_INVALID;
3374 if (websocket) {
3375 vs->ws_auth = VNC_AUTH_VNC;
3376 } else {
3377 vs->ws_auth = VNC_AUTH_INVALID;
3379 } else if (sasl) {
3380 if (tls) {
3381 vs->auth = VNC_AUTH_VENCRYPT;
3382 if (websocket) {
3383 vs->ws_tls = true;
3385 if (x509) {
3386 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3387 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3388 } else {
3389 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3390 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3392 } else {
3393 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3394 vs->auth = VNC_AUTH_SASL;
3395 vs->subauth = VNC_AUTH_INVALID;
3397 if (websocket) {
3398 vs->ws_auth = VNC_AUTH_SASL;
3399 } else {
3400 vs->ws_auth = VNC_AUTH_INVALID;
3402 } else {
3403 if (tls) {
3404 vs->auth = VNC_AUTH_VENCRYPT;
3405 if (websocket) {
3406 vs->ws_tls = true;
3408 if (x509) {
3409 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3410 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3411 } else {
3412 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3413 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3415 } else {
3416 VNC_DEBUG("Initializing VNC server with no auth\n");
3417 vs->auth = VNC_AUTH_NONE;
3418 vs->subauth = VNC_AUTH_INVALID;
3420 if (websocket) {
3421 vs->ws_auth = VNC_AUTH_NONE;
3422 } else {
3423 vs->ws_auth = VNC_AUTH_INVALID;
3428 void vnc_display_open(const char *id, Error **errp)
3430 VncDisplay *vs = vnc_display_find(id);
3431 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3432 QemuOpts *sopts, *wsopts;
3433 const char *share, *device_id;
3434 QemuConsole *con;
3435 bool password = false;
3436 bool reverse = false;
3437 const char *vnc;
3438 const char *has_to;
3439 char *h;
3440 bool has_ipv4 = false;
3441 bool has_ipv6 = false;
3442 const char *websocket;
3443 bool tls = false, x509 = false;
3444 #ifdef CONFIG_VNC_TLS
3445 const char *path;
3446 #endif
3447 bool sasl = false;
3448 #ifdef CONFIG_VNC_SASL
3449 int saslErr;
3450 #endif
3451 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3452 int acl = 0;
3453 #endif
3454 int lock_key_sync = 1;
3456 if (!vs) {
3457 error_setg(errp, "VNC display not active");
3458 return;
3460 vnc_display_close(vs);
3462 if (!opts) {
3463 return;
3465 vnc = qemu_opt_get(opts, "vnc");
3466 if (!vnc || strcmp(vnc, "none") == 0) {
3467 return;
3470 sopts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
3471 wsopts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
3473 h = strrchr(vnc, ':');
3474 if (h) {
3475 char *host;
3476 size_t hlen = h - vnc;
3478 if (vnc[0] == '[' && vnc[hlen - 1] == ']') {
3479 host = g_strndup(vnc + 1, hlen - 2);
3480 } else {
3481 host = g_strndup(vnc, hlen);
3483 qemu_opt_set(sopts, "host", host, &error_abort);
3484 qemu_opt_set(wsopts, "host", host, &error_abort);
3485 qemu_opt_set(sopts, "port", h+1, &error_abort);
3486 g_free(host);
3487 } else {
3488 error_setg(errp, "no vnc port specified");
3489 goto fail;
3492 has_to = qemu_opt_get(opts, "to");
3493 has_ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3494 has_ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3495 if (has_to) {
3496 qemu_opt_set(sopts, "to", has_to, &error_abort);
3497 qemu_opt_set(wsopts, "to", has_to, &error_abort);
3499 if (has_ipv4) {
3500 qemu_opt_set(sopts, "ipv4", "on", &error_abort);
3501 qemu_opt_set(wsopts, "ipv4", "on", &error_abort);
3503 if (has_ipv6) {
3504 qemu_opt_set(sopts, "ipv6", "on", &error_abort);
3505 qemu_opt_set(wsopts, "ipv6", "on", &error_abort);
3508 password = qemu_opt_get_bool(opts, "password", false);
3509 if (password) {
3510 if (fips_get_state()) {
3511 error_setg(errp,
3512 "VNC password auth disabled due to FIPS mode, "
3513 "consider using the VeNCrypt or SASL authentication "
3514 "methods as an alternative");
3515 goto fail;
3517 if (!qcrypto_cipher_supports(
3518 QCRYPTO_CIPHER_ALG_DES_RFB)) {
3519 error_setg(errp,
3520 "Cipher backend does not support DES RFB algorithm");
3521 goto fail;
3525 reverse = qemu_opt_get_bool(opts, "reverse", false);
3526 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3527 sasl = qemu_opt_get_bool(opts, "sasl", false);
3528 #ifndef CONFIG_VNC_SASL
3529 if (sasl) {
3530 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3531 goto fail;
3533 #endif /* CONFIG_VNC_SASL */
3534 tls = qemu_opt_get_bool(opts, "tls", false);
3535 #ifdef CONFIG_VNC_TLS
3536 path = qemu_opt_get(opts, "x509");
3537 if (!path) {
3538 path = qemu_opt_get(opts, "x509verify");
3539 if (path) {
3540 vs->tls.x509verify = true;
3543 if (path) {
3544 x509 = true;
3545 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
3546 error_setg(errp, "Failed to find x509 certificates/keys in %s",
3547 path);
3548 goto fail;
3551 #else /* ! CONFIG_VNC_TLS */
3552 if (tls) {
3553 error_setg(errp, "VNC TLS auth requires gnutls support");
3554 goto fail;
3556 #endif /* ! CONFIG_VNC_TLS */
3557 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3558 acl = qemu_opt_get_bool(opts, "acl", false);
3559 #endif
3561 share = qemu_opt_get(opts, "share");
3562 if (share) {
3563 if (strcmp(share, "ignore") == 0) {
3564 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
3565 } else if (strcmp(share, "allow-exclusive") == 0) {
3566 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3567 } else if (strcmp(share, "force-shared") == 0) {
3568 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3569 } else {
3570 error_setg(errp, "unknown vnc share= option");
3571 goto fail;
3573 } else {
3574 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3576 vs->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3578 websocket = qemu_opt_get(opts, "websocket");
3579 if (websocket) {
3580 vs->ws_enabled = true;
3581 qemu_opt_set(wsopts, "port", websocket, &error_abort);
3582 if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3583 error_setg(errp, "SHA1 hash support is required for websockets");
3584 goto fail;
3588 #ifdef CONFIG_VNC_JPEG
3589 vs->lossy = qemu_opt_get_bool(opts, "lossy", false);
3590 #endif
3591 vs->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3592 /* adaptive updates are only used with tight encoding and
3593 * if lossy updates are enabled so we can disable all the
3594 * calculations otherwise */
3595 if (!vs->lossy) {
3596 vs->non_adaptive = true;
3599 #ifdef CONFIG_VNC_TLS
3600 if (acl && x509 && vs->tls.x509verify) {
3601 char *aclname;
3603 if (strcmp(vs->id, "default") == 0) {
3604 aclname = g_strdup("vnc.x509dname");
3605 } else {
3606 aclname = g_strdup_printf("vnc.%s.x509dname", vs->id);
3608 vs->tls.acl = qemu_acl_init(aclname);
3609 g_free(aclname);
3611 #endif
3612 #ifdef CONFIG_VNC_SASL
3613 if (acl && sasl) {
3614 char *aclname;
3616 if (strcmp(vs->id, "default") == 0) {
3617 aclname = g_strdup("vnc.username");
3618 } else {
3619 aclname = g_strdup_printf("vnc.%s.username", vs->id);
3621 vs->sasl.acl = qemu_acl_init(aclname);
3622 g_free(aclname);
3624 #endif
3626 vnc_display_setup_auth(vs, password, sasl, tls, x509, websocket);
3628 #ifdef CONFIG_VNC_SASL
3629 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3630 error_setg(errp, "Failed to initialize SASL auth: %s",
3631 sasl_errstring(saslErr, NULL, NULL));
3632 goto fail;
3634 #endif
3635 vs->lock_key_sync = lock_key_sync;
3637 device_id = qemu_opt_get(opts, "display");
3638 if (device_id) {
3639 DeviceState *dev;
3640 int head = qemu_opt_get_number(opts, "head", 0);
3642 dev = qdev_find_recursive(sysbus_get_default(), device_id);
3643 if (dev == NULL) {
3644 error_setg(errp, "Device '%s' not found", device_id);
3645 goto fail;
3648 con = qemu_console_lookup_by_device(dev, head);
3649 if (con == NULL) {
3650 error_setg(errp, "Device %s is not bound to a QemuConsole",
3651 device_id);
3652 goto fail;
3654 } else {
3655 con = NULL;
3658 if (con != vs->dcl.con) {
3659 unregister_displaychangelistener(&vs->dcl);
3660 vs->dcl.con = con;
3661 register_displaychangelistener(&vs->dcl);
3664 if (reverse) {
3665 /* connect to viewer */
3666 int csock;
3667 vs->lsock = -1;
3668 vs->lwebsock = -1;
3669 if (strncmp(vnc, "unix:", 5) == 0) {
3670 csock = unix_connect(vnc+5, errp);
3671 } else {
3672 csock = inet_connect(vnc, errp);
3674 if (csock < 0) {
3675 goto fail;
3677 vnc_connect(vs, csock, false, false);
3678 } else {
3679 /* listen for connects */
3680 if (strncmp(vnc, "unix:", 5) == 0) {
3681 vs->lsock = unix_listen(vnc+5, NULL, 0, errp);
3682 if (vs->lsock < 0) {
3683 goto fail;
3685 vs->is_unix = true;
3686 } else {
3687 vs->lsock = inet_listen_opts(sopts, 5900, errp);
3688 if (vs->lsock < 0) {
3689 goto fail;
3691 if (vs->ws_enabled) {
3692 vs->lwebsock = inet_listen_opts(wsopts, 0, errp);
3693 if (vs->lwebsock < 0) {
3694 if (vs->lsock != -1) {
3695 close(vs->lsock);
3696 vs->lsock = -1;
3698 goto fail;
3702 vs->enabled = true;
3703 qemu_set_fd_handler(vs->lsock, vnc_listen_regular_read, NULL, vs);
3704 if (vs->ws_enabled) {
3705 qemu_set_fd_handler(vs->lwebsock, vnc_listen_websocket_read,
3706 NULL, vs);
3709 qemu_opts_del(sopts);
3710 qemu_opts_del(wsopts);
3711 return;
3713 fail:
3714 qemu_opts_del(sopts);
3715 qemu_opts_del(wsopts);
3716 vs->enabled = false;
3717 vs->ws_enabled = false;
3720 void vnc_display_add_client(const char *id, int csock, bool skipauth)
3722 VncDisplay *vs = vnc_display_find(id);
3724 if (!vs) {
3725 return;
3727 vnc_connect(vs, csock, skipauth, false);
3730 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
3732 int i = 2;
3733 char *id;
3735 id = g_strdup("default");
3736 while (qemu_opts_find(olist, id)) {
3737 g_free(id);
3738 id = g_strdup_printf("vnc%d", i++);
3740 qemu_opts_set_id(opts, id);
3743 QemuOpts *vnc_parse(const char *str, Error **errp)
3745 QemuOptsList *olist = qemu_find_opts("vnc");
3746 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
3747 const char *id;
3749 if (!opts) {
3750 return NULL;
3753 id = qemu_opts_id(opts);
3754 if (!id) {
3755 /* auto-assign id if not present */
3756 vnc_auto_assign_id(olist, opts);
3758 return opts;
3761 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
3763 Error *local_err = NULL;
3764 char *id = (char *)qemu_opts_id(opts);
3766 assert(id);
3767 vnc_display_init(id);
3768 vnc_display_open(id, &local_err);
3769 if (local_err != NULL) {
3770 error_report("Failed to start VNC server: %s",
3771 error_get_pretty(local_err));
3772 error_free(local_err);
3773 exit(1);
3775 return 0;
3778 static void vnc_register_config(void)
3780 qemu_add_opts(&qemu_vnc_opts);
3782 machine_init(vnc_register_config);