monitor: add query-vnc-servers command
[qemu/ar7.git] / ui / vnc.c
blobc85d9c392e9b60e7c98d25ea4cfcb1766be6294b
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/sockets.h"
33 #include "qemu/timer.h"
34 #include "qemu/acl.h"
35 #include "qemu/config-file.h"
36 #include "qapi/qmp/types.h"
37 #include "qmp-commands.h"
38 #include "qemu/osdep.h"
39 #include "ui/input.h"
40 #include "qapi-event.h"
42 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
43 #define VNC_REFRESH_INTERVAL_INC 50
44 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
45 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
46 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
48 #include "vnc_keysym.h"
49 #include "d3des.h"
51 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
52 QTAILQ_HEAD_INITIALIZER(vnc_displays);
54 static int vnc_cursor_define(VncState *vs);
55 static void vnc_release_modifiers(VncState *vs);
57 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
59 #ifdef _VNC_DEBUG
60 static const char *mn[] = {
61 [0] = "undefined",
62 [VNC_SHARE_MODE_CONNECTING] = "connecting",
63 [VNC_SHARE_MODE_SHARED] = "shared",
64 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
65 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
67 fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
68 vs->csock, mn[vs->share_mode], mn[mode]);
69 #endif
71 switch (vs->share_mode) {
72 case VNC_SHARE_MODE_CONNECTING:
73 vs->vd->num_connecting--;
74 break;
75 case VNC_SHARE_MODE_SHARED:
76 vs->vd->num_shared--;
77 break;
78 case VNC_SHARE_MODE_EXCLUSIVE:
79 vs->vd->num_exclusive--;
80 break;
81 default:
82 break;
85 vs->share_mode = mode;
87 switch (vs->share_mode) {
88 case VNC_SHARE_MODE_CONNECTING:
89 vs->vd->num_connecting++;
90 break;
91 case VNC_SHARE_MODE_SHARED:
92 vs->vd->num_shared++;
93 break;
94 case VNC_SHARE_MODE_EXCLUSIVE:
95 vs->vd->num_exclusive++;
96 break;
97 default:
98 break;
102 static char *addr_to_string(const char *format,
103 struct sockaddr_storage *sa,
104 socklen_t salen) {
105 char *addr;
106 char host[NI_MAXHOST];
107 char serv[NI_MAXSERV];
108 int err;
109 size_t addrlen;
111 if ((err = getnameinfo((struct sockaddr *)sa, salen,
112 host, sizeof(host),
113 serv, sizeof(serv),
114 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
115 VNC_DEBUG("Cannot resolve address %d: %s\n",
116 err, gai_strerror(err));
117 return NULL;
120 /* Enough for the existing format + the 2 vars we're
121 * substituting in. */
122 addrlen = strlen(format) + strlen(host) + strlen(serv);
123 addr = g_malloc(addrlen + 1);
124 snprintf(addr, addrlen, format, host, serv);
125 addr[addrlen] = '\0';
127 return addr;
131 char *vnc_socket_local_addr(const char *format, int fd) {
132 struct sockaddr_storage sa;
133 socklen_t salen;
135 salen = sizeof(sa);
136 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
137 return NULL;
139 return addr_to_string(format, &sa, salen);
142 char *vnc_socket_remote_addr(const char *format, int fd) {
143 struct sockaddr_storage sa;
144 socklen_t salen;
146 salen = sizeof(sa);
147 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
148 return NULL;
150 return addr_to_string(format, &sa, salen);
153 static VncBasicInfo *vnc_basic_info_get(struct sockaddr_storage *sa,
154 socklen_t salen)
156 VncBasicInfo *info;
157 char host[NI_MAXHOST];
158 char serv[NI_MAXSERV];
159 int err;
161 if ((err = getnameinfo((struct sockaddr *)sa, salen,
162 host, sizeof(host),
163 serv, sizeof(serv),
164 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
165 VNC_DEBUG("Cannot resolve address %d: %s\n",
166 err, gai_strerror(err));
167 return NULL;
170 info = g_malloc0(sizeof(VncBasicInfo));
171 info->host = g_strdup(host);
172 info->service = g_strdup(serv);
173 info->family = inet_netfamily(sa->ss_family);
174 return info;
177 static VncBasicInfo *vnc_basic_info_get_from_server_addr(int fd)
179 struct sockaddr_storage sa;
180 socklen_t salen;
182 salen = sizeof(sa);
183 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
184 return NULL;
187 return vnc_basic_info_get(&sa, salen);
190 static VncBasicInfo *vnc_basic_info_get_from_remote_addr(int fd)
192 struct sockaddr_storage sa;
193 socklen_t salen;
195 salen = sizeof(sa);
196 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
197 return NULL;
200 return vnc_basic_info_get(&sa, salen);
203 static const char *vnc_auth_name(VncDisplay *vd) {
204 switch (vd->auth) {
205 case VNC_AUTH_INVALID:
206 return "invalid";
207 case VNC_AUTH_NONE:
208 return "none";
209 case VNC_AUTH_VNC:
210 return "vnc";
211 case VNC_AUTH_RA2:
212 return "ra2";
213 case VNC_AUTH_RA2NE:
214 return "ra2ne";
215 case VNC_AUTH_TIGHT:
216 return "tight";
217 case VNC_AUTH_ULTRA:
218 return "ultra";
219 case VNC_AUTH_TLS:
220 return "tls";
221 case VNC_AUTH_VENCRYPT:
222 #ifdef CONFIG_VNC_TLS
223 switch (vd->subauth) {
224 case VNC_AUTH_VENCRYPT_PLAIN:
225 return "vencrypt+plain";
226 case VNC_AUTH_VENCRYPT_TLSNONE:
227 return "vencrypt+tls+none";
228 case VNC_AUTH_VENCRYPT_TLSVNC:
229 return "vencrypt+tls+vnc";
230 case VNC_AUTH_VENCRYPT_TLSPLAIN:
231 return "vencrypt+tls+plain";
232 case VNC_AUTH_VENCRYPT_X509NONE:
233 return "vencrypt+x509+none";
234 case VNC_AUTH_VENCRYPT_X509VNC:
235 return "vencrypt+x509+vnc";
236 case VNC_AUTH_VENCRYPT_X509PLAIN:
237 return "vencrypt+x509+plain";
238 case VNC_AUTH_VENCRYPT_TLSSASL:
239 return "vencrypt+tls+sasl";
240 case VNC_AUTH_VENCRYPT_X509SASL:
241 return "vencrypt+x509+sasl";
242 default:
243 return "vencrypt";
245 #else
246 return "vencrypt";
247 #endif
248 case VNC_AUTH_SASL:
249 return "sasl";
251 return "unknown";
254 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
256 VncServerInfo *info;
257 VncBasicInfo *bi = vnc_basic_info_get_from_server_addr(vd->lsock);
258 if (!bi) {
259 return NULL;
262 info = g_malloc(sizeof(*info));
263 info->base = bi;
264 info->has_auth = true;
265 info->auth = g_strdup(vnc_auth_name(vd));
266 return info;
269 static void vnc_client_cache_auth(VncState *client)
271 if (!client->info) {
272 return;
275 #ifdef CONFIG_VNC_TLS
276 if (client->tls.session &&
277 client->tls.dname) {
278 client->info->has_x509_dname = true;
279 client->info->x509_dname = g_strdup(client->tls.dname);
281 #endif
282 #ifdef CONFIG_VNC_SASL
283 if (client->sasl.conn &&
284 client->sasl.username) {
285 client->info->has_sasl_username = true;
286 client->info->sasl_username = g_strdup(client->sasl.username);
288 #endif
291 static void vnc_client_cache_addr(VncState *client)
293 VncBasicInfo *bi = vnc_basic_info_get_from_remote_addr(client->csock);
295 if (bi) {
296 client->info = g_malloc0(sizeof(*client->info));
297 client->info->base = bi;
301 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
303 VncServerInfo *si;
305 if (!vs->info) {
306 return;
308 g_assert(vs->info->base);
310 si = vnc_server_info_get(vs->vd);
311 if (!si) {
312 return;
315 switch (event) {
316 case QAPI_EVENT_VNC_CONNECTED:
317 qapi_event_send_vnc_connected(si, vs->info->base, &error_abort);
318 break;
319 case QAPI_EVENT_VNC_INITIALIZED:
320 qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
321 break;
322 case QAPI_EVENT_VNC_DISCONNECTED:
323 qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
324 break;
325 default:
326 break;
329 qapi_free_VncServerInfo(si);
332 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
334 struct sockaddr_storage sa;
335 socklen_t salen = sizeof(sa);
336 char host[NI_MAXHOST];
337 char serv[NI_MAXSERV];
338 VncClientInfo *info;
340 if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
341 return NULL;
344 if (getnameinfo((struct sockaddr *)&sa, salen,
345 host, sizeof(host),
346 serv, sizeof(serv),
347 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
348 return NULL;
351 info = g_malloc0(sizeof(*info));
352 info->base = g_malloc0(sizeof(*info->base));
353 info->base->host = g_strdup(host);
354 info->base->service = g_strdup(serv);
355 info->base->family = inet_netfamily(sa.ss_family);
357 #ifdef CONFIG_VNC_TLS
358 if (client->tls.session && client->tls.dname) {
359 info->has_x509_dname = true;
360 info->x509_dname = g_strdup(client->tls.dname);
362 #endif
363 #ifdef CONFIG_VNC_SASL
364 if (client->sasl.conn && client->sasl.username) {
365 info->has_sasl_username = true;
366 info->sasl_username = g_strdup(client->sasl.username);
368 #endif
370 return info;
373 static VncDisplay *vnc_display_find(const char *id)
375 VncDisplay *vd;
377 if (id == NULL) {
378 return QTAILQ_FIRST(&vnc_displays);
380 QTAILQ_FOREACH(vd, &vnc_displays, next) {
381 if (strcmp(id, vd->id) == 0) {
382 return vd;
385 return NULL;
388 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
390 VncClientInfoList *cinfo, *prev = NULL;
391 VncState *client;
393 QTAILQ_FOREACH(client, &vd->clients, next) {
394 cinfo = g_new0(VncClientInfoList, 1);
395 cinfo->value = qmp_query_vnc_client(client);
396 cinfo->next = prev;
397 prev = cinfo;
399 return prev;
402 VncInfo *qmp_query_vnc(Error **errp)
404 VncInfo *info = g_malloc0(sizeof(*info));
405 VncDisplay *vd = vnc_display_find(NULL);
407 if (vd == NULL || vd->display == NULL) {
408 info->enabled = false;
409 } else {
410 struct sockaddr_storage sa;
411 socklen_t salen = sizeof(sa);
412 char host[NI_MAXHOST];
413 char serv[NI_MAXSERV];
415 info->enabled = true;
417 /* for compatibility with the original command */
418 info->has_clients = true;
419 info->clients = qmp_query_client_list(vd);
421 if (vd->lsock == -1) {
422 return info;
425 if (getsockname(vd->lsock, (struct sockaddr *)&sa,
426 &salen) == -1) {
427 error_set(errp, QERR_UNDEFINED_ERROR);
428 goto out_error;
431 if (getnameinfo((struct sockaddr *)&sa, salen,
432 host, sizeof(host),
433 serv, sizeof(serv),
434 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
435 error_set(errp, QERR_UNDEFINED_ERROR);
436 goto out_error;
439 info->has_host = true;
440 info->host = g_strdup(host);
442 info->has_service = true;
443 info->service = g_strdup(serv);
445 info->has_family = true;
446 info->family = inet_netfamily(sa.ss_family);
448 info->has_auth = true;
449 info->auth = g_strdup(vnc_auth_name(vd));
452 return info;
454 out_error:
455 qapi_free_VncInfo(info);
456 return NULL;
459 static VncBasicInfoList *qmp_query_server_entry(int socket,
460 VncBasicInfoList *prev)
462 VncBasicInfoList *list;
463 VncBasicInfo *info;
464 struct sockaddr_storage sa;
465 socklen_t salen = sizeof(sa);
466 char host[NI_MAXHOST];
467 char serv[NI_MAXSERV];
469 if (getsockname(socket, (struct sockaddr *)&sa, &salen) < 0 ||
470 getnameinfo((struct sockaddr *)&sa, salen,
471 host, sizeof(host), serv, sizeof(serv),
472 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
473 return prev;
476 info = g_new0(VncBasicInfo, 1);
477 info->host = g_strdup(host);
478 info->service = g_strdup(serv);
479 info->family = inet_netfamily(sa.ss_family);
481 list = g_new0(VncBasicInfoList, 1);
482 list->value = info;
483 list->next = prev;
484 return list;
487 static void qmp_query_auth(VncDisplay *vd, VncInfo2 *info)
489 switch (vd->auth) {
490 case VNC_AUTH_VNC:
491 info->auth = VNC_PRIMARY_AUTH_VNC;
492 break;
493 case VNC_AUTH_RA2:
494 info->auth = VNC_PRIMARY_AUTH_RA2;
495 break;
496 case VNC_AUTH_RA2NE:
497 info->auth = VNC_PRIMARY_AUTH_RA2NE;
498 break;
499 case VNC_AUTH_TIGHT:
500 info->auth = VNC_PRIMARY_AUTH_TIGHT;
501 break;
502 case VNC_AUTH_ULTRA:
503 info->auth = VNC_PRIMARY_AUTH_ULTRA;
504 break;
505 case VNC_AUTH_TLS:
506 info->auth = VNC_PRIMARY_AUTH_TLS;
507 break;
508 case VNC_AUTH_VENCRYPT:
509 info->auth = VNC_PRIMARY_AUTH_VENCRYPT;
510 #ifdef CONFIG_VNC_TLS
511 info->has_vencrypt = true;
512 switch (vd->subauth) {
513 case VNC_AUTH_VENCRYPT_PLAIN:
514 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
515 break;
516 case VNC_AUTH_VENCRYPT_TLSNONE:
517 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
518 break;
519 case VNC_AUTH_VENCRYPT_TLSVNC:
520 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
521 break;
522 case VNC_AUTH_VENCRYPT_TLSPLAIN:
523 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
524 break;
525 case VNC_AUTH_VENCRYPT_X509NONE:
526 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
527 break;
528 case VNC_AUTH_VENCRYPT_X509VNC:
529 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
530 break;
531 case VNC_AUTH_VENCRYPT_X509PLAIN:
532 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
533 break;
534 case VNC_AUTH_VENCRYPT_TLSSASL:
535 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
536 break;
537 case VNC_AUTH_VENCRYPT_X509SASL:
538 info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
539 break;
540 default:
541 info->has_vencrypt = false;
542 break;
544 #endif
545 break;
546 case VNC_AUTH_SASL:
547 info->auth = VNC_PRIMARY_AUTH_SASL;
548 break;
549 case VNC_AUTH_NONE:
550 default:
551 info->auth = VNC_PRIMARY_AUTH_NONE;
552 break;
556 VncInfo2List *qmp_query_vnc_servers(Error **errp)
558 VncInfo2List *item, *prev = NULL;
559 VncInfo2 *info;
560 VncDisplay *vd;
561 DeviceState *dev;
563 QTAILQ_FOREACH(vd, &vnc_displays, next) {
564 info = g_new0(VncInfo2, 1);
565 info->id = g_strdup(vd->id);
566 info->clients = qmp_query_client_list(vd);
567 qmp_query_auth(vd, info);
568 if (vd->dcl.con) {
569 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
570 "device", NULL));
571 info->has_display = true;
572 info->display = g_strdup(dev->id);
574 if (vd->lsock != -1) {
575 info->server = qmp_query_server_entry(vd->lsock,
576 info->server);
578 #ifdef CONFIG_VNC_WS
579 if (vd->lwebsock != -1) {
580 /* TODO */
582 #endif
584 item = g_new0(VncInfo2List, 1);
585 item->value = info;
586 item->next = prev;
587 prev = item;
589 return prev;
592 /* TODO
593 1) Get the queue working for IO.
594 2) there is some weirdness when using the -S option (the screen is grey
595 and not totally invalidated
596 3) resolutions > 1024
599 static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
600 static void vnc_disconnect_start(VncState *vs);
602 static void vnc_colordepth(VncState *vs);
603 static void framebuffer_update_request(VncState *vs, int incremental,
604 int x_position, int y_position,
605 int w, int h);
606 static void vnc_refresh(DisplayChangeListener *dcl);
607 static int vnc_refresh_server_surface(VncDisplay *vd);
609 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
610 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
611 int width, int height,
612 int x, int y, int w, int h) {
613 /* this is needed this to ensure we updated all affected
614 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
615 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
616 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
618 x = MIN(x, width);
619 y = MIN(y, height);
620 w = MIN(x + w, width) - x;
621 h = MIN(y + h, height);
623 for (; y < h; y++) {
624 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
625 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
629 static void vnc_dpy_update(DisplayChangeListener *dcl,
630 int x, int y, int w, int h)
632 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
633 struct VncSurface *s = &vd->guest;
634 int width = pixman_image_get_width(vd->server);
635 int height = pixman_image_get_height(vd->server);
637 vnc_set_area_dirty(s->dirty, width, height, x, y, w, h);
640 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
641 int32_t encoding)
643 vnc_write_u16(vs, x);
644 vnc_write_u16(vs, y);
645 vnc_write_u16(vs, w);
646 vnc_write_u16(vs, h);
648 vnc_write_s32(vs, encoding);
651 void buffer_reserve(Buffer *buffer, size_t len)
653 if ((buffer->capacity - buffer->offset) < len) {
654 buffer->capacity += (len + 1024);
655 buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
656 if (buffer->buffer == NULL) {
657 fprintf(stderr, "vnc: out of memory\n");
658 exit(1);
663 static int buffer_empty(Buffer *buffer)
665 return buffer->offset == 0;
668 uint8_t *buffer_end(Buffer *buffer)
670 return buffer->buffer + buffer->offset;
673 void buffer_reset(Buffer *buffer)
675 buffer->offset = 0;
678 void buffer_free(Buffer *buffer)
680 g_free(buffer->buffer);
681 buffer->offset = 0;
682 buffer->capacity = 0;
683 buffer->buffer = NULL;
686 void buffer_append(Buffer *buffer, const void *data, size_t len)
688 memcpy(buffer->buffer + buffer->offset, data, len);
689 buffer->offset += len;
692 void buffer_advance(Buffer *buf, size_t len)
694 memmove(buf->buffer, buf->buffer + len,
695 (buf->offset - len));
696 buf->offset -= len;
699 static void vnc_desktop_resize(VncState *vs)
701 if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
702 return;
704 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
705 vs->client_height == pixman_image_get_height(vs->vd->server)) {
706 return;
708 vs->client_width = pixman_image_get_width(vs->vd->server);
709 vs->client_height = pixman_image_get_height(vs->vd->server);
710 vnc_lock_output(vs);
711 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
712 vnc_write_u8(vs, 0);
713 vnc_write_u16(vs, 1); /* number of rects */
714 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
715 VNC_ENCODING_DESKTOPRESIZE);
716 vnc_unlock_output(vs);
717 vnc_flush(vs);
720 static void vnc_abort_display_jobs(VncDisplay *vd)
722 VncState *vs;
724 QTAILQ_FOREACH(vs, &vd->clients, next) {
725 vnc_lock_output(vs);
726 vs->abort = true;
727 vnc_unlock_output(vs);
729 QTAILQ_FOREACH(vs, &vd->clients, next) {
730 vnc_jobs_join(vs);
732 QTAILQ_FOREACH(vs, &vd->clients, next) {
733 vnc_lock_output(vs);
734 vs->abort = false;
735 vnc_unlock_output(vs);
739 int vnc_server_fb_stride(VncDisplay *vd)
741 return pixman_image_get_stride(vd->server);
744 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
746 uint8_t *ptr;
748 ptr = (uint8_t *)pixman_image_get_data(vd->server);
749 ptr += y * vnc_server_fb_stride(vd);
750 ptr += x * VNC_SERVER_FB_BYTES;
751 return ptr;
754 static void vnc_dpy_switch(DisplayChangeListener *dcl,
755 DisplaySurface *surface)
757 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
758 VncState *vs;
759 int width, height;
761 vnc_abort_display_jobs(vd);
763 /* server surface */
764 qemu_pixman_image_unref(vd->server);
765 vd->ds = surface;
766 width = MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
767 VNC_DIRTY_PIXELS_PER_BIT));
768 height = MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
769 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
770 width, height, NULL, 0);
772 /* guest surface */
773 #if 0 /* FIXME */
774 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
775 console_color_init(ds);
776 #endif
777 qemu_pixman_image_unref(vd->guest.fb);
778 vd->guest.fb = pixman_image_ref(surface->image);
779 vd->guest.format = surface->format;
780 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
781 vnc_set_area_dirty(vd->guest.dirty, width, height, 0, 0,
782 width, height);
784 QTAILQ_FOREACH(vs, &vd->clients, next) {
785 vnc_colordepth(vs);
786 vnc_desktop_resize(vs);
787 if (vs->vd->cursor) {
788 vnc_cursor_define(vs);
790 memset(vs->dirty, 0x00, sizeof(vs->dirty));
791 vnc_set_area_dirty(vs->dirty, width, height, 0, 0,
792 width, height);
796 /* fastest code */
797 static void vnc_write_pixels_copy(VncState *vs,
798 void *pixels, int size)
800 vnc_write(vs, pixels, size);
803 /* slowest but generic code. */
804 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
806 uint8_t r, g, b;
808 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
809 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
810 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
811 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
812 #else
813 # error need some bits here if you change VNC_SERVER_FB_FORMAT
814 #endif
815 v = (r << vs->client_pf.rshift) |
816 (g << vs->client_pf.gshift) |
817 (b << vs->client_pf.bshift);
818 switch (vs->client_pf.bytes_per_pixel) {
819 case 1:
820 buf[0] = v;
821 break;
822 case 2:
823 if (vs->client_be) {
824 buf[0] = v >> 8;
825 buf[1] = v;
826 } else {
827 buf[1] = v >> 8;
828 buf[0] = v;
830 break;
831 default:
832 case 4:
833 if (vs->client_be) {
834 buf[0] = v >> 24;
835 buf[1] = v >> 16;
836 buf[2] = v >> 8;
837 buf[3] = v;
838 } else {
839 buf[3] = v >> 24;
840 buf[2] = v >> 16;
841 buf[1] = v >> 8;
842 buf[0] = v;
844 break;
848 static void vnc_write_pixels_generic(VncState *vs,
849 void *pixels1, int size)
851 uint8_t buf[4];
853 if (VNC_SERVER_FB_BYTES == 4) {
854 uint32_t *pixels = pixels1;
855 int n, i;
856 n = size >> 2;
857 for (i = 0; i < n; i++) {
858 vnc_convert_pixel(vs, buf, pixels[i]);
859 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
864 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
866 int i;
867 uint8_t *row;
868 VncDisplay *vd = vs->vd;
870 row = vnc_server_fb_ptr(vd, x, y);
871 for (i = 0; i < h; i++) {
872 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
873 row += vnc_server_fb_stride(vd);
875 return 1;
878 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
880 int n = 0;
882 switch(vs->vnc_encoding) {
883 case VNC_ENCODING_ZLIB:
884 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
885 break;
886 case VNC_ENCODING_HEXTILE:
887 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
888 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
889 break;
890 case VNC_ENCODING_TIGHT:
891 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
892 break;
893 case VNC_ENCODING_TIGHT_PNG:
894 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
895 break;
896 case VNC_ENCODING_ZRLE:
897 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
898 break;
899 case VNC_ENCODING_ZYWRLE:
900 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
901 break;
902 default:
903 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
904 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
905 break;
907 return n;
910 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
912 /* send bitblit op to the vnc client */
913 vnc_lock_output(vs);
914 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
915 vnc_write_u8(vs, 0);
916 vnc_write_u16(vs, 1); /* number of rects */
917 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
918 vnc_write_u16(vs, src_x);
919 vnc_write_u16(vs, src_y);
920 vnc_unlock_output(vs);
921 vnc_flush(vs);
924 static void vnc_dpy_copy(DisplayChangeListener *dcl,
925 int src_x, int src_y,
926 int dst_x, int dst_y, int w, int h)
928 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
929 VncState *vs, *vn;
930 uint8_t *src_row;
931 uint8_t *dst_row;
932 int i, x, y, pitch, inc, w_lim, s;
933 int cmp_bytes;
935 vnc_refresh_server_surface(vd);
936 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
937 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
938 vs->force_update = 1;
939 vnc_update_client(vs, 1, true);
940 /* vs might be free()ed here */
944 /* do bitblit op on the local surface too */
945 pitch = vnc_server_fb_stride(vd);
946 src_row = vnc_server_fb_ptr(vd, src_x, src_y);
947 dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
948 y = dst_y;
949 inc = 1;
950 if (dst_y > src_y) {
951 /* copy backwards */
952 src_row += pitch * (h-1);
953 dst_row += pitch * (h-1);
954 pitch = -pitch;
955 y = dst_y + h - 1;
956 inc = -1;
958 w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
959 if (w_lim < 0) {
960 w_lim = w;
961 } else {
962 w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
964 for (i = 0; i < h; i++) {
965 for (x = 0; x <= w_lim;
966 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
967 if (x == w_lim) {
968 if ((s = w - w_lim) == 0)
969 break;
970 } else if (!x) {
971 s = (VNC_DIRTY_PIXELS_PER_BIT -
972 (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
973 s = MIN(s, w_lim);
974 } else {
975 s = VNC_DIRTY_PIXELS_PER_BIT;
977 cmp_bytes = s * VNC_SERVER_FB_BYTES;
978 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
979 continue;
980 memmove(dst_row, src_row, cmp_bytes);
981 QTAILQ_FOREACH(vs, &vd->clients, next) {
982 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
983 set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
984 vs->dirty[y]);
988 src_row += pitch - w * VNC_SERVER_FB_BYTES;
989 dst_row += pitch - w * VNC_SERVER_FB_BYTES;
990 y += inc;
993 QTAILQ_FOREACH(vs, &vd->clients, next) {
994 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
995 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
1000 static void vnc_mouse_set(DisplayChangeListener *dcl,
1001 int x, int y, int visible)
1003 /* can we ask the client(s) to move the pointer ??? */
1006 static int vnc_cursor_define(VncState *vs)
1008 QEMUCursor *c = vs->vd->cursor;
1009 int isize;
1011 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
1012 vnc_lock_output(vs);
1013 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1014 vnc_write_u8(vs, 0); /* padding */
1015 vnc_write_u16(vs, 1); /* # of rects */
1016 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
1017 VNC_ENCODING_RICH_CURSOR);
1018 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
1019 vnc_write_pixels_generic(vs, c->data, isize);
1020 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
1021 vnc_unlock_output(vs);
1022 return 0;
1024 return -1;
1027 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
1028 QEMUCursor *c)
1030 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
1031 VncState *vs;
1033 cursor_put(vd->cursor);
1034 g_free(vd->cursor_mask);
1036 vd->cursor = c;
1037 cursor_get(vd->cursor);
1038 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
1039 vd->cursor_mask = g_malloc0(vd->cursor_msize);
1040 cursor_get_mono_mask(c, 0, vd->cursor_mask);
1042 QTAILQ_FOREACH(vs, &vd->clients, next) {
1043 vnc_cursor_define(vs);
1047 static int find_and_clear_dirty_height(struct VncState *vs,
1048 int y, int last_x, int x, int height)
1050 int h;
1052 for (h = 1; h < (height - y); h++) {
1053 if (!test_bit(last_x, vs->dirty[y + h])) {
1054 break;
1056 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
1059 return h;
1062 static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
1064 vs->has_dirty += has_dirty;
1065 if (vs->need_update && vs->csock != -1) {
1066 VncDisplay *vd = vs->vd;
1067 VncJob *job;
1068 int y;
1069 int height, width;
1070 int n = 0;
1072 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
1073 /* kernel send buffers are full -> drop frames to throttle */
1074 return 0;
1076 if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)
1077 return 0;
1080 * Send screen updates to the vnc client using the server
1081 * surface and server dirty map. guest surface updates
1082 * happening in parallel don't disturb us, the next pass will
1083 * send them to the client.
1085 job = vnc_job_new(vs);
1087 height = pixman_image_get_height(vd->server);
1088 width = pixman_image_get_width(vd->server);
1090 y = 0;
1091 for (;;) {
1092 int x, h;
1093 unsigned long x2;
1094 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1095 height * VNC_DIRTY_BPL(vs),
1096 y * VNC_DIRTY_BPL(vs));
1097 if (offset == height * VNC_DIRTY_BPL(vs)) {
1098 /* no more dirty bits */
1099 break;
1101 y = offset / VNC_DIRTY_BPL(vs);
1102 x = offset % VNC_DIRTY_BPL(vs);
1103 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1104 VNC_DIRTY_BPL(vs), x);
1105 bitmap_clear(vs->dirty[y], x, x2 - x);
1106 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1107 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1108 if (x2 > x) {
1109 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1110 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1114 vnc_job_push(job);
1115 if (sync) {
1116 vnc_jobs_join(vs);
1118 vs->force_update = 0;
1119 vs->has_dirty = 0;
1120 return n;
1123 if (vs->csock == -1) {
1124 vnc_disconnect_finish(vs);
1125 } else if (sync) {
1126 vnc_jobs_join(vs);
1129 return 0;
1132 /* audio */
1133 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1135 VncState *vs = opaque;
1137 switch (cmd) {
1138 case AUD_CNOTIFY_DISABLE:
1139 vnc_lock_output(vs);
1140 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1141 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1142 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1143 vnc_unlock_output(vs);
1144 vnc_flush(vs);
1145 break;
1147 case AUD_CNOTIFY_ENABLE:
1148 vnc_lock_output(vs);
1149 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1150 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1151 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1152 vnc_unlock_output(vs);
1153 vnc_flush(vs);
1154 break;
1158 static void audio_capture_destroy(void *opaque)
1162 static void audio_capture(void *opaque, void *buf, int size)
1164 VncState *vs = opaque;
1166 vnc_lock_output(vs);
1167 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1168 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1169 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1170 vnc_write_u32(vs, size);
1171 vnc_write(vs, buf, size);
1172 vnc_unlock_output(vs);
1173 vnc_flush(vs);
1176 static void audio_add(VncState *vs)
1178 struct audio_capture_ops ops;
1180 if (vs->audio_cap) {
1181 error_report("audio already running");
1182 return;
1185 ops.notify = audio_capture_notify;
1186 ops.destroy = audio_capture_destroy;
1187 ops.capture = audio_capture;
1189 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1190 if (!vs->audio_cap) {
1191 error_report("Failed to add audio capture");
1195 static void audio_del(VncState *vs)
1197 if (vs->audio_cap) {
1198 AUD_del_capture(vs->audio_cap, vs);
1199 vs->audio_cap = NULL;
1203 static void vnc_disconnect_start(VncState *vs)
1205 if (vs->csock == -1)
1206 return;
1207 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1208 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1209 closesocket(vs->csock);
1210 vs->csock = -1;
1213 void vnc_disconnect_finish(VncState *vs)
1215 int i;
1217 vnc_jobs_join(vs); /* Wait encoding jobs */
1219 vnc_lock_output(vs);
1220 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1222 buffer_free(&vs->input);
1223 buffer_free(&vs->output);
1224 #ifdef CONFIG_VNC_WS
1225 buffer_free(&vs->ws_input);
1226 buffer_free(&vs->ws_output);
1227 #endif /* CONFIG_VNC_WS */
1229 qapi_free_VncClientInfo(vs->info);
1231 vnc_zlib_clear(vs);
1232 vnc_tight_clear(vs);
1233 vnc_zrle_clear(vs);
1235 #ifdef CONFIG_VNC_TLS
1236 vnc_tls_client_cleanup(vs);
1237 #endif /* CONFIG_VNC_TLS */
1238 #ifdef CONFIG_VNC_SASL
1239 vnc_sasl_client_cleanup(vs);
1240 #endif /* CONFIG_VNC_SASL */
1241 audio_del(vs);
1242 vnc_release_modifiers(vs);
1244 if (vs->initialized) {
1245 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1246 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1249 if (vs->vd->lock_key_sync)
1250 qemu_remove_led_event_handler(vs->led);
1251 vnc_unlock_output(vs);
1253 qemu_mutex_destroy(&vs->output_mutex);
1254 if (vs->bh != NULL) {
1255 qemu_bh_delete(vs->bh);
1257 buffer_free(&vs->jobs_buffer);
1259 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1260 g_free(vs->lossy_rect[i]);
1262 g_free(vs->lossy_rect);
1263 g_free(vs);
1266 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1268 if (ret == 0 || ret == -1) {
1269 if (ret == -1) {
1270 switch (last_errno) {
1271 case EINTR:
1272 case EAGAIN:
1273 #ifdef _WIN32
1274 case WSAEWOULDBLOCK:
1275 #endif
1276 return 0;
1277 default:
1278 break;
1282 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1283 ret, ret < 0 ? last_errno : 0);
1284 vnc_disconnect_start(vs);
1286 return 0;
1288 return ret;
1292 void vnc_client_error(VncState *vs)
1294 VNC_DEBUG("Closing down client sock: protocol error\n");
1295 vnc_disconnect_start(vs);
1298 #ifdef CONFIG_VNC_TLS
1299 static long vnc_client_write_tls(gnutls_session_t *session,
1300 const uint8_t *data,
1301 size_t datalen)
1303 long ret = gnutls_write(*session, data, datalen);
1304 if (ret < 0) {
1305 if (ret == GNUTLS_E_AGAIN) {
1306 errno = EAGAIN;
1307 } else {
1308 errno = EIO;
1310 ret = -1;
1312 return ret;
1314 #endif /* CONFIG_VNC_TLS */
1317 * Called to write a chunk of data to the client socket. The data may
1318 * be the raw data, or may have already been encoded by SASL.
1319 * The data will be written either straight onto the socket, or
1320 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1322 * NB, it is theoretically possible to have 2 layers of encryption,
1323 * both SASL, and this TLS layer. It is highly unlikely in practice
1324 * though, since SASL encryption will typically be a no-op if TLS
1325 * is active
1327 * Returns the number of bytes written, which may be less than
1328 * the requested 'datalen' if the socket would block. Returns
1329 * -1 on error, and disconnects the client socket.
1331 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1333 long ret;
1334 #ifdef CONFIG_VNC_TLS
1335 if (vs->tls.session) {
1336 ret = vnc_client_write_tls(&vs->tls.session, data, datalen);
1337 } else {
1338 #ifdef CONFIG_VNC_WS
1339 if (vs->ws_tls.session) {
1340 ret = vnc_client_write_tls(&vs->ws_tls.session, data, datalen);
1341 } else
1342 #endif /* CONFIG_VNC_WS */
1343 #endif /* CONFIG_VNC_TLS */
1345 ret = send(vs->csock, (const void *)data, datalen, 0);
1347 #ifdef CONFIG_VNC_TLS
1349 #endif /* CONFIG_VNC_TLS */
1350 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1351 return vnc_client_io_error(vs, ret, socket_error());
1356 * Called to write buffered data to the client socket, when not
1357 * using any SASL SSF encryption layers. Will write as much data
1358 * as possible without blocking. If all buffered data is written,
1359 * will switch the FD poll() handler back to read monitoring.
1361 * Returns the number of bytes written, which may be less than
1362 * the buffered output data if the socket would block. Returns
1363 * -1 on error, and disconnects the client socket.
1365 static long vnc_client_write_plain(VncState *vs)
1367 long ret;
1369 #ifdef CONFIG_VNC_SASL
1370 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1371 vs->output.buffer, vs->output.capacity, vs->output.offset,
1372 vs->sasl.waitWriteSSF);
1374 if (vs->sasl.conn &&
1375 vs->sasl.runSSF &&
1376 vs->sasl.waitWriteSSF) {
1377 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1378 if (ret)
1379 vs->sasl.waitWriteSSF -= ret;
1380 } else
1381 #endif /* CONFIG_VNC_SASL */
1382 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1383 if (!ret)
1384 return 0;
1386 buffer_advance(&vs->output, ret);
1388 if (vs->output.offset == 0) {
1389 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1392 return ret;
1397 * First function called whenever there is data to be written to
1398 * the client socket. Will delegate actual work according to whether
1399 * SASL SSF layers are enabled (thus requiring encryption calls)
1401 static void vnc_client_write_locked(void *opaque)
1403 VncState *vs = opaque;
1405 #ifdef CONFIG_VNC_SASL
1406 if (vs->sasl.conn &&
1407 vs->sasl.runSSF &&
1408 !vs->sasl.waitWriteSSF) {
1409 vnc_client_write_sasl(vs);
1410 } else
1411 #endif /* CONFIG_VNC_SASL */
1413 #ifdef CONFIG_VNC_WS
1414 if (vs->encode_ws) {
1415 vnc_client_write_ws(vs);
1416 } else
1417 #endif /* CONFIG_VNC_WS */
1419 vnc_client_write_plain(vs);
1424 void vnc_client_write(void *opaque)
1426 VncState *vs = opaque;
1428 vnc_lock_output(vs);
1429 if (vs->output.offset
1430 #ifdef CONFIG_VNC_WS
1431 || vs->ws_output.offset
1432 #endif
1434 vnc_client_write_locked(opaque);
1435 } else if (vs->csock != -1) {
1436 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1438 vnc_unlock_output(vs);
1441 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1443 vs->read_handler = func;
1444 vs->read_handler_expect = expecting;
1447 #ifdef CONFIG_VNC_TLS
1448 static long vnc_client_read_tls(gnutls_session_t *session, uint8_t *data,
1449 size_t datalen)
1451 long ret = gnutls_read(*session, data, datalen);
1452 if (ret < 0) {
1453 if (ret == GNUTLS_E_AGAIN) {
1454 errno = EAGAIN;
1455 } else {
1456 errno = EIO;
1458 ret = -1;
1460 return ret;
1462 #endif /* CONFIG_VNC_TLS */
1465 * Called to read a chunk of data from the client socket. The data may
1466 * be the raw data, or may need to be further decoded by SASL.
1467 * The data will be read either straight from to the socket, or
1468 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1470 * NB, it is theoretically possible to have 2 layers of encryption,
1471 * both SASL, and this TLS layer. It is highly unlikely in practice
1472 * though, since SASL encryption will typically be a no-op if TLS
1473 * is active
1475 * Returns the number of bytes read, which may be less than
1476 * the requested 'datalen' if the socket would block. Returns
1477 * -1 on error, and disconnects the client socket.
1479 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1481 long ret;
1482 #ifdef CONFIG_VNC_TLS
1483 if (vs->tls.session) {
1484 ret = vnc_client_read_tls(&vs->tls.session, data, datalen);
1485 } else {
1486 #ifdef CONFIG_VNC_WS
1487 if (vs->ws_tls.session) {
1488 ret = vnc_client_read_tls(&vs->ws_tls.session, data, datalen);
1489 } else
1490 #endif /* CONFIG_VNC_WS */
1491 #endif /* CONFIG_VNC_TLS */
1493 ret = qemu_recv(vs->csock, data, datalen, 0);
1495 #ifdef CONFIG_VNC_TLS
1497 #endif /* CONFIG_VNC_TLS */
1498 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1499 return vnc_client_io_error(vs, ret, socket_error());
1504 * Called to read data from the client socket to the input buffer,
1505 * when not using any SASL SSF encryption layers. Will read as much
1506 * data as possible without blocking.
1508 * Returns the number of bytes read. Returns -1 on error, and
1509 * disconnects the client socket.
1511 static long vnc_client_read_plain(VncState *vs)
1513 int ret;
1514 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1515 vs->input.buffer, vs->input.capacity, vs->input.offset);
1516 buffer_reserve(&vs->input, 4096);
1517 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1518 if (!ret)
1519 return 0;
1520 vs->input.offset += ret;
1521 return ret;
1524 static void vnc_jobs_bh(void *opaque)
1526 VncState *vs = opaque;
1528 vnc_jobs_consume_buffer(vs);
1532 * First function called whenever there is more data to be read from
1533 * the client socket. Will delegate actual work according to whether
1534 * SASL SSF layers are enabled (thus requiring decryption calls)
1536 void vnc_client_read(void *opaque)
1538 VncState *vs = opaque;
1539 long ret;
1541 #ifdef CONFIG_VNC_SASL
1542 if (vs->sasl.conn && vs->sasl.runSSF)
1543 ret = vnc_client_read_sasl(vs);
1544 else
1545 #endif /* CONFIG_VNC_SASL */
1546 #ifdef CONFIG_VNC_WS
1547 if (vs->encode_ws) {
1548 ret = vnc_client_read_ws(vs);
1549 if (ret == -1) {
1550 vnc_disconnect_start(vs);
1551 return;
1552 } else if (ret == -2) {
1553 vnc_client_error(vs);
1554 return;
1556 } else
1557 #endif /* CONFIG_VNC_WS */
1559 ret = vnc_client_read_plain(vs);
1561 if (!ret) {
1562 if (vs->csock == -1)
1563 vnc_disconnect_finish(vs);
1564 return;
1567 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1568 size_t len = vs->read_handler_expect;
1569 int ret;
1571 ret = vs->read_handler(vs, vs->input.buffer, len);
1572 if (vs->csock == -1) {
1573 vnc_disconnect_finish(vs);
1574 return;
1577 if (!ret) {
1578 buffer_advance(&vs->input, len);
1579 } else {
1580 vs->read_handler_expect = ret;
1585 void vnc_write(VncState *vs, const void *data, size_t len)
1587 buffer_reserve(&vs->output, len);
1589 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1590 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1593 buffer_append(&vs->output, data, len);
1596 void vnc_write_s32(VncState *vs, int32_t value)
1598 vnc_write_u32(vs, *(uint32_t *)&value);
1601 void vnc_write_u32(VncState *vs, uint32_t value)
1603 uint8_t buf[4];
1605 buf[0] = (value >> 24) & 0xFF;
1606 buf[1] = (value >> 16) & 0xFF;
1607 buf[2] = (value >> 8) & 0xFF;
1608 buf[3] = value & 0xFF;
1610 vnc_write(vs, buf, 4);
1613 void vnc_write_u16(VncState *vs, uint16_t value)
1615 uint8_t buf[2];
1617 buf[0] = (value >> 8) & 0xFF;
1618 buf[1] = value & 0xFF;
1620 vnc_write(vs, buf, 2);
1623 void vnc_write_u8(VncState *vs, uint8_t value)
1625 vnc_write(vs, (char *)&value, 1);
1628 void vnc_flush(VncState *vs)
1630 vnc_lock_output(vs);
1631 if (vs->csock != -1 && (vs->output.offset
1632 #ifdef CONFIG_VNC_WS
1633 || vs->ws_output.offset
1634 #endif
1635 )) {
1636 vnc_client_write_locked(vs);
1638 vnc_unlock_output(vs);
1641 static uint8_t read_u8(uint8_t *data, size_t offset)
1643 return data[offset];
1646 static uint16_t read_u16(uint8_t *data, size_t offset)
1648 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1651 static int32_t read_s32(uint8_t *data, size_t offset)
1653 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1654 (data[offset + 2] << 8) | data[offset + 3]);
1657 uint32_t read_u32(uint8_t *data, size_t offset)
1659 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1660 (data[offset + 2] << 8) | data[offset + 3]);
1663 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1667 static void check_pointer_type_change(Notifier *notifier, void *data)
1669 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1670 int absolute = qemu_input_is_absolute();
1672 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1673 vnc_lock_output(vs);
1674 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1675 vnc_write_u8(vs, 0);
1676 vnc_write_u16(vs, 1);
1677 vnc_framebuffer_update(vs, absolute, 0,
1678 pixman_image_get_width(vs->vd->server),
1679 pixman_image_get_height(vs->vd->server),
1680 VNC_ENCODING_POINTER_TYPE_CHANGE);
1681 vnc_unlock_output(vs);
1682 vnc_flush(vs);
1684 vs->absolute = absolute;
1687 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1689 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1690 [INPUT_BUTTON_LEFT] = 0x01,
1691 [INPUT_BUTTON_MIDDLE] = 0x02,
1692 [INPUT_BUTTON_RIGHT] = 0x04,
1693 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1694 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1696 QemuConsole *con = vs->vd->dcl.con;
1697 int width = pixman_image_get_width(vs->vd->server);
1698 int height = pixman_image_get_height(vs->vd->server);
1700 if (vs->last_bmask != button_mask) {
1701 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1702 vs->last_bmask = button_mask;
1705 if (vs->absolute) {
1706 qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
1707 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
1708 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1709 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1710 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1711 } else {
1712 if (vs->last_x != -1) {
1713 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1714 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1716 vs->last_x = x;
1717 vs->last_y = y;
1719 qemu_input_event_sync();
1722 static void reset_keys(VncState *vs)
1724 int i;
1725 for(i = 0; i < 256; i++) {
1726 if (vs->modifiers_state[i]) {
1727 qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1728 vs->modifiers_state[i] = 0;
1733 static void press_key(VncState *vs, int keysym)
1735 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1736 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1737 qemu_input_event_send_key_delay(0);
1738 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1739 qemu_input_event_send_key_delay(0);
1742 static int current_led_state(VncState *vs)
1744 int ledstate = 0;
1746 if (vs->modifiers_state[0x46]) {
1747 ledstate |= QEMU_SCROLL_LOCK_LED;
1749 if (vs->modifiers_state[0x45]) {
1750 ledstate |= QEMU_NUM_LOCK_LED;
1752 if (vs->modifiers_state[0x3a]) {
1753 ledstate |= QEMU_CAPS_LOCK_LED;
1756 return ledstate;
1759 static void vnc_led_state_change(VncState *vs)
1761 int ledstate = 0;
1763 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1764 return;
1767 ledstate = current_led_state(vs);
1768 vnc_lock_output(vs);
1769 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1770 vnc_write_u8(vs, 0);
1771 vnc_write_u16(vs, 1);
1772 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1773 vnc_write_u8(vs, ledstate);
1774 vnc_unlock_output(vs);
1775 vnc_flush(vs);
1778 static void kbd_leds(void *opaque, int ledstate)
1780 VncState *vs = opaque;
1781 int caps, num, scr;
1782 bool has_changed = (ledstate != current_led_state(vs));
1784 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1785 (ledstate & QEMU_NUM_LOCK_LED),
1786 (ledstate & QEMU_SCROLL_LOCK_LED));
1788 caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1789 num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
1790 scr = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
1792 if (vs->modifiers_state[0x3a] != caps) {
1793 vs->modifiers_state[0x3a] = caps;
1795 if (vs->modifiers_state[0x45] != num) {
1796 vs->modifiers_state[0x45] = num;
1798 if (vs->modifiers_state[0x46] != scr) {
1799 vs->modifiers_state[0x46] = scr;
1802 /* Sending the current led state message to the client */
1803 if (has_changed) {
1804 vnc_led_state_change(vs);
1808 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1810 /* QEMU console switch */
1811 switch(keycode) {
1812 case 0x2a: /* Left Shift */
1813 case 0x36: /* Right Shift */
1814 case 0x1d: /* Left CTRL */
1815 case 0x9d: /* Right CTRL */
1816 case 0x38: /* Left ALT */
1817 case 0xb8: /* Right ALT */
1818 if (down)
1819 vs->modifiers_state[keycode] = 1;
1820 else
1821 vs->modifiers_state[keycode] = 0;
1822 break;
1823 case 0x02 ... 0x0a: /* '1' to '9' keys */
1824 if (vs->vd->dcl.con == NULL &&
1825 down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1826 /* Reset the modifiers sent to the current console */
1827 reset_keys(vs);
1828 console_select(keycode - 0x02);
1829 return;
1831 break;
1832 case 0x3a: /* CapsLock */
1833 case 0x45: /* NumLock */
1834 if (down)
1835 vs->modifiers_state[keycode] ^= 1;
1836 break;
1839 /* Turn off the lock state sync logic if the client support the led
1840 state extension.
1842 if (down && vs->vd->lock_key_sync &&
1843 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1844 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1845 /* If the numlock state needs to change then simulate an additional
1846 keypress before sending this one. This will happen if the user
1847 toggles numlock away from the VNC window.
1849 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1850 if (!vs->modifiers_state[0x45]) {
1851 trace_vnc_key_sync_numlock(true);
1852 vs->modifiers_state[0x45] = 1;
1853 press_key(vs, 0xff7f);
1855 } else {
1856 if (vs->modifiers_state[0x45]) {
1857 trace_vnc_key_sync_numlock(false);
1858 vs->modifiers_state[0x45] = 0;
1859 press_key(vs, 0xff7f);
1864 if (down && vs->vd->lock_key_sync &&
1865 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1866 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1867 /* If the capslock state needs to change then simulate an additional
1868 keypress before sending this one. This will happen if the user
1869 toggles capslock away from the VNC window.
1871 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1872 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1873 int capslock = !!(vs->modifiers_state[0x3a]);
1874 if (capslock) {
1875 if (uppercase == shift) {
1876 trace_vnc_key_sync_capslock(false);
1877 vs->modifiers_state[0x3a] = 0;
1878 press_key(vs, 0xffe5);
1880 } else {
1881 if (uppercase != shift) {
1882 trace_vnc_key_sync_capslock(true);
1883 vs->modifiers_state[0x3a] = 1;
1884 press_key(vs, 0xffe5);
1889 if (qemu_console_is_graphic(NULL)) {
1890 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1891 } else {
1892 bool numlock = vs->modifiers_state[0x45];
1893 bool control = (vs->modifiers_state[0x1d] ||
1894 vs->modifiers_state[0x9d]);
1895 /* QEMU console emulation */
1896 if (down) {
1897 switch (keycode) {
1898 case 0x2a: /* Left Shift */
1899 case 0x36: /* Right Shift */
1900 case 0x1d: /* Left CTRL */
1901 case 0x9d: /* Right CTRL */
1902 case 0x38: /* Left ALT */
1903 case 0xb8: /* Right ALT */
1904 break;
1905 case 0xc8:
1906 kbd_put_keysym(QEMU_KEY_UP);
1907 break;
1908 case 0xd0:
1909 kbd_put_keysym(QEMU_KEY_DOWN);
1910 break;
1911 case 0xcb:
1912 kbd_put_keysym(QEMU_KEY_LEFT);
1913 break;
1914 case 0xcd:
1915 kbd_put_keysym(QEMU_KEY_RIGHT);
1916 break;
1917 case 0xd3:
1918 kbd_put_keysym(QEMU_KEY_DELETE);
1919 break;
1920 case 0xc7:
1921 kbd_put_keysym(QEMU_KEY_HOME);
1922 break;
1923 case 0xcf:
1924 kbd_put_keysym(QEMU_KEY_END);
1925 break;
1926 case 0xc9:
1927 kbd_put_keysym(QEMU_KEY_PAGEUP);
1928 break;
1929 case 0xd1:
1930 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1931 break;
1933 case 0x47:
1934 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1935 break;
1936 case 0x48:
1937 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1938 break;
1939 case 0x49:
1940 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1941 break;
1942 case 0x4b:
1943 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1944 break;
1945 case 0x4c:
1946 kbd_put_keysym('5');
1947 break;
1948 case 0x4d:
1949 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1950 break;
1951 case 0x4f:
1952 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1953 break;
1954 case 0x50:
1955 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1956 break;
1957 case 0x51:
1958 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1959 break;
1960 case 0x52:
1961 kbd_put_keysym('0');
1962 break;
1963 case 0x53:
1964 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1965 break;
1967 case 0xb5:
1968 kbd_put_keysym('/');
1969 break;
1970 case 0x37:
1971 kbd_put_keysym('*');
1972 break;
1973 case 0x4a:
1974 kbd_put_keysym('-');
1975 break;
1976 case 0x4e:
1977 kbd_put_keysym('+');
1978 break;
1979 case 0x9c:
1980 kbd_put_keysym('\n');
1981 break;
1983 default:
1984 if (control) {
1985 kbd_put_keysym(sym & 0x1f);
1986 } else {
1987 kbd_put_keysym(sym);
1989 break;
1995 static void vnc_release_modifiers(VncState *vs)
1997 static const int keycodes[] = {
1998 /* shift, control, alt keys, both left & right */
1999 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
2001 int i, keycode;
2003 if (!qemu_console_is_graphic(NULL)) {
2004 return;
2006 for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
2007 keycode = keycodes[i];
2008 if (!vs->modifiers_state[keycode]) {
2009 continue;
2011 qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
2015 static const char *code2name(int keycode)
2017 return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
2020 static void key_event(VncState *vs, int down, uint32_t sym)
2022 int keycode;
2023 int lsym = sym;
2025 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
2026 lsym = lsym - 'A' + 'a';
2029 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
2030 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
2031 do_key_event(vs, down, keycode, sym);
2034 static void ext_key_event(VncState *vs, int down,
2035 uint32_t sym, uint16_t keycode)
2037 /* if the user specifies a keyboard layout, always use it */
2038 if (keyboard_layout) {
2039 key_event(vs, down, sym);
2040 } else {
2041 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2042 do_key_event(vs, down, keycode, sym);
2046 static void framebuffer_update_request(VncState *vs, int incremental,
2047 int x, int y, int w, int h)
2049 int width = pixman_image_get_width(vs->vd->server);
2050 int height = pixman_image_get_height(vs->vd->server);
2052 vs->need_update = 1;
2054 if (incremental) {
2055 return;
2058 vs->force_update = 1;
2059 vnc_set_area_dirty(vs->dirty, width, height, x, y, w, h);
2062 static void send_ext_key_event_ack(VncState *vs)
2064 vnc_lock_output(vs);
2065 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2066 vnc_write_u8(vs, 0);
2067 vnc_write_u16(vs, 1);
2068 vnc_framebuffer_update(vs, 0, 0,
2069 pixman_image_get_width(vs->vd->server),
2070 pixman_image_get_height(vs->vd->server),
2071 VNC_ENCODING_EXT_KEY_EVENT);
2072 vnc_unlock_output(vs);
2073 vnc_flush(vs);
2076 static void send_ext_audio_ack(VncState *vs)
2078 vnc_lock_output(vs);
2079 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2080 vnc_write_u8(vs, 0);
2081 vnc_write_u16(vs, 1);
2082 vnc_framebuffer_update(vs, 0, 0,
2083 pixman_image_get_width(vs->vd->server),
2084 pixman_image_get_height(vs->vd->server),
2085 VNC_ENCODING_AUDIO);
2086 vnc_unlock_output(vs);
2087 vnc_flush(vs);
2090 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2092 int i;
2093 unsigned int enc = 0;
2095 vs->features = 0;
2096 vs->vnc_encoding = 0;
2097 vs->tight.compression = 9;
2098 vs->tight.quality = -1; /* Lossless by default */
2099 vs->absolute = -1;
2102 * Start from the end because the encodings are sent in order of preference.
2103 * This way the preferred encoding (first encoding defined in the array)
2104 * will be set at the end of the loop.
2106 for (i = n_encodings - 1; i >= 0; i--) {
2107 enc = encodings[i];
2108 switch (enc) {
2109 case VNC_ENCODING_RAW:
2110 vs->vnc_encoding = enc;
2111 break;
2112 case VNC_ENCODING_COPYRECT:
2113 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2114 break;
2115 case VNC_ENCODING_HEXTILE:
2116 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2117 vs->vnc_encoding = enc;
2118 break;
2119 case VNC_ENCODING_TIGHT:
2120 vs->features |= VNC_FEATURE_TIGHT_MASK;
2121 vs->vnc_encoding = enc;
2122 break;
2123 #ifdef CONFIG_VNC_PNG
2124 case VNC_ENCODING_TIGHT_PNG:
2125 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2126 vs->vnc_encoding = enc;
2127 break;
2128 #endif
2129 case VNC_ENCODING_ZLIB:
2130 vs->features |= VNC_FEATURE_ZLIB_MASK;
2131 vs->vnc_encoding = enc;
2132 break;
2133 case VNC_ENCODING_ZRLE:
2134 vs->features |= VNC_FEATURE_ZRLE_MASK;
2135 vs->vnc_encoding = enc;
2136 break;
2137 case VNC_ENCODING_ZYWRLE:
2138 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2139 vs->vnc_encoding = enc;
2140 break;
2141 case VNC_ENCODING_DESKTOPRESIZE:
2142 vs->features |= VNC_FEATURE_RESIZE_MASK;
2143 break;
2144 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2145 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2146 break;
2147 case VNC_ENCODING_RICH_CURSOR:
2148 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2149 break;
2150 case VNC_ENCODING_EXT_KEY_EVENT:
2151 send_ext_key_event_ack(vs);
2152 break;
2153 case VNC_ENCODING_AUDIO:
2154 send_ext_audio_ack(vs);
2155 break;
2156 case VNC_ENCODING_WMVi:
2157 vs->features |= VNC_FEATURE_WMVI_MASK;
2158 break;
2159 case VNC_ENCODING_LED_STATE:
2160 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2161 break;
2162 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2163 vs->tight.compression = (enc & 0x0F);
2164 break;
2165 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2166 if (vs->vd->lossy) {
2167 vs->tight.quality = (enc & 0x0F);
2169 break;
2170 default:
2171 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2172 break;
2175 vnc_desktop_resize(vs);
2176 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2177 vnc_led_state_change(vs);
2180 static void set_pixel_conversion(VncState *vs)
2182 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2184 if (fmt == VNC_SERVER_FB_FORMAT) {
2185 vs->write_pixels = vnc_write_pixels_copy;
2186 vnc_hextile_set_pixel_conversion(vs, 0);
2187 } else {
2188 vs->write_pixels = vnc_write_pixels_generic;
2189 vnc_hextile_set_pixel_conversion(vs, 1);
2193 static void set_pixel_format(VncState *vs,
2194 int bits_per_pixel, int depth,
2195 int big_endian_flag, int true_color_flag,
2196 int red_max, int green_max, int blue_max,
2197 int red_shift, int green_shift, int blue_shift)
2199 if (!true_color_flag) {
2200 vnc_client_error(vs);
2201 return;
2204 switch (bits_per_pixel) {
2205 case 8:
2206 case 16:
2207 case 32:
2208 break;
2209 default:
2210 vnc_client_error(vs);
2211 return;
2214 vs->client_pf.rmax = red_max;
2215 vs->client_pf.rbits = hweight_long(red_max);
2216 vs->client_pf.rshift = red_shift;
2217 vs->client_pf.rmask = red_max << red_shift;
2218 vs->client_pf.gmax = green_max;
2219 vs->client_pf.gbits = hweight_long(green_max);
2220 vs->client_pf.gshift = green_shift;
2221 vs->client_pf.gmask = green_max << green_shift;
2222 vs->client_pf.bmax = blue_max;
2223 vs->client_pf.bbits = hweight_long(blue_max);
2224 vs->client_pf.bshift = blue_shift;
2225 vs->client_pf.bmask = blue_max << blue_shift;
2226 vs->client_pf.bits_per_pixel = bits_per_pixel;
2227 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2228 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2229 vs->client_be = big_endian_flag;
2231 set_pixel_conversion(vs);
2233 graphic_hw_invalidate(vs->vd->dcl.con);
2234 graphic_hw_update(vs->vd->dcl.con);
2237 static void pixel_format_message (VncState *vs) {
2238 char pad[3] = { 0, 0, 0 };
2240 vs->client_pf = qemu_default_pixelformat(32);
2242 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2243 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2245 #ifdef HOST_WORDS_BIGENDIAN
2246 vnc_write_u8(vs, 1); /* big-endian-flag */
2247 #else
2248 vnc_write_u8(vs, 0); /* big-endian-flag */
2249 #endif
2250 vnc_write_u8(vs, 1); /* true-color-flag */
2251 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2252 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2253 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2254 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2255 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2256 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2257 vnc_write(vs, pad, 3); /* padding */
2259 vnc_hextile_set_pixel_conversion(vs, 0);
2260 vs->write_pixels = vnc_write_pixels_copy;
2263 static void vnc_colordepth(VncState *vs)
2265 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2266 /* Sending a WMVi message to notify the client*/
2267 vnc_lock_output(vs);
2268 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2269 vnc_write_u8(vs, 0);
2270 vnc_write_u16(vs, 1); /* number of rects */
2271 vnc_framebuffer_update(vs, 0, 0,
2272 pixman_image_get_width(vs->vd->server),
2273 pixman_image_get_height(vs->vd->server),
2274 VNC_ENCODING_WMVi);
2275 pixel_format_message(vs);
2276 vnc_unlock_output(vs);
2277 vnc_flush(vs);
2278 } else {
2279 set_pixel_conversion(vs);
2283 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2285 int i;
2286 uint16_t limit;
2287 VncDisplay *vd = vs->vd;
2289 if (data[0] > 3) {
2290 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2293 switch (data[0]) {
2294 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2295 if (len == 1)
2296 return 20;
2298 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
2299 read_u8(data, 6), read_u8(data, 7),
2300 read_u16(data, 8), read_u16(data, 10),
2301 read_u16(data, 12), read_u8(data, 14),
2302 read_u8(data, 15), read_u8(data, 16));
2303 break;
2304 case VNC_MSG_CLIENT_SET_ENCODINGS:
2305 if (len == 1)
2306 return 4;
2308 if (len == 4) {
2309 limit = read_u16(data, 2);
2310 if (limit > 0)
2311 return 4 + (limit * 4);
2312 } else
2313 limit = read_u16(data, 2);
2315 for (i = 0; i < limit; i++) {
2316 int32_t val = read_s32(data, 4 + (i * 4));
2317 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2320 set_encodings(vs, (int32_t *)(data + 4), limit);
2321 break;
2322 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2323 if (len == 1)
2324 return 10;
2326 framebuffer_update_request(vs,
2327 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2328 read_u16(data, 6), read_u16(data, 8));
2329 break;
2330 case VNC_MSG_CLIENT_KEY_EVENT:
2331 if (len == 1)
2332 return 8;
2334 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2335 break;
2336 case VNC_MSG_CLIENT_POINTER_EVENT:
2337 if (len == 1)
2338 return 6;
2340 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2341 break;
2342 case VNC_MSG_CLIENT_CUT_TEXT:
2343 if (len == 1) {
2344 return 8;
2346 if (len == 8) {
2347 uint32_t dlen = read_u32(data, 4);
2348 if (dlen > (1 << 20)) {
2349 error_report("vnc: client_cut_text msg payload has %u bytes"
2350 " which exceeds our limit of 1MB.", dlen);
2351 vnc_client_error(vs);
2352 break;
2354 if (dlen > 0) {
2355 return 8 + dlen;
2359 client_cut_text(vs, read_u32(data, 4), data + 8);
2360 break;
2361 case VNC_MSG_CLIENT_QEMU:
2362 if (len == 1)
2363 return 2;
2365 switch (read_u8(data, 1)) {
2366 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2367 if (len == 2)
2368 return 12;
2370 ext_key_event(vs, read_u16(data, 2),
2371 read_u32(data, 4), read_u32(data, 8));
2372 break;
2373 case VNC_MSG_CLIENT_QEMU_AUDIO:
2374 if (len == 2)
2375 return 4;
2377 switch (read_u16 (data, 2)) {
2378 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2379 audio_add(vs);
2380 break;
2381 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2382 audio_del(vs);
2383 break;
2384 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2385 if (len == 4)
2386 return 10;
2387 switch (read_u8(data, 4)) {
2388 case 0: vs->as.fmt = AUD_FMT_U8; break;
2389 case 1: vs->as.fmt = AUD_FMT_S8; break;
2390 case 2: vs->as.fmt = AUD_FMT_U16; break;
2391 case 3: vs->as.fmt = AUD_FMT_S16; break;
2392 case 4: vs->as.fmt = AUD_FMT_U32; break;
2393 case 5: vs->as.fmt = AUD_FMT_S32; break;
2394 default:
2395 printf("Invalid audio format %d\n", read_u8(data, 4));
2396 vnc_client_error(vs);
2397 break;
2399 vs->as.nchannels = read_u8(data, 5);
2400 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2401 printf("Invalid audio channel coount %d\n",
2402 read_u8(data, 5));
2403 vnc_client_error(vs);
2404 break;
2406 vs->as.freq = read_u32(data, 6);
2407 break;
2408 default:
2409 printf ("Invalid audio message %d\n", read_u8(data, 4));
2410 vnc_client_error(vs);
2411 break;
2413 break;
2415 default:
2416 printf("Msg: %d\n", read_u16(data, 0));
2417 vnc_client_error(vs);
2418 break;
2420 break;
2421 default:
2422 printf("Msg: %d\n", data[0]);
2423 vnc_client_error(vs);
2424 break;
2427 vnc_read_when(vs, protocol_client_msg, 1);
2428 return 0;
2431 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2433 char buf[1024];
2434 VncShareMode mode;
2435 int size;
2437 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2438 switch (vs->vd->share_policy) {
2439 case VNC_SHARE_POLICY_IGNORE:
2441 * Ignore the shared flag. Nothing to do here.
2443 * Doesn't conform to the rfb spec but is traditional qemu
2444 * behavior, thus left here as option for compatibility
2445 * reasons.
2447 break;
2448 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2450 * Policy: Allow clients ask for exclusive access.
2452 * Implementation: When a client asks for exclusive access,
2453 * disconnect all others. Shared connects are allowed as long
2454 * as no exclusive connection exists.
2456 * This is how the rfb spec suggests to handle the shared flag.
2458 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2459 VncState *client;
2460 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2461 if (vs == client) {
2462 continue;
2464 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2465 client->share_mode != VNC_SHARE_MODE_SHARED) {
2466 continue;
2468 vnc_disconnect_start(client);
2471 if (mode == VNC_SHARE_MODE_SHARED) {
2472 if (vs->vd->num_exclusive > 0) {
2473 vnc_disconnect_start(vs);
2474 return 0;
2477 break;
2478 case VNC_SHARE_POLICY_FORCE_SHARED:
2480 * Policy: Shared connects only.
2481 * Implementation: Disallow clients asking for exclusive access.
2483 * Useful for shared desktop sessions where you don't want
2484 * someone forgetting to say -shared when running the vnc
2485 * client disconnect everybody else.
2487 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2488 vnc_disconnect_start(vs);
2489 return 0;
2491 break;
2493 vnc_set_share_mode(vs, mode);
2495 if (vs->vd->num_shared > vs->vd->connections_limit) {
2496 vnc_disconnect_start(vs);
2497 return 0;
2500 vs->client_width = pixman_image_get_width(vs->vd->server);
2501 vs->client_height = pixman_image_get_height(vs->vd->server);
2502 vnc_write_u16(vs, vs->client_width);
2503 vnc_write_u16(vs, vs->client_height);
2505 pixel_format_message(vs);
2507 if (qemu_name)
2508 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2509 else
2510 size = snprintf(buf, sizeof(buf), "QEMU");
2512 vnc_write_u32(vs, size);
2513 vnc_write(vs, buf, size);
2514 vnc_flush(vs);
2516 vnc_client_cache_auth(vs);
2517 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2519 vnc_read_when(vs, protocol_client_msg, 1);
2521 return 0;
2524 void start_client_init(VncState *vs)
2526 vnc_read_when(vs, protocol_client_init, 1);
2529 static void make_challenge(VncState *vs)
2531 int i;
2533 srand(time(NULL)+getpid()+getpid()*987654+rand());
2535 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2536 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2539 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2541 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2542 int i, j, pwlen;
2543 unsigned char key[8];
2544 time_t now = time(NULL);
2546 if (!vs->vd->password) {
2547 VNC_DEBUG("No password configured on server");
2548 goto reject;
2550 if (vs->vd->expires < now) {
2551 VNC_DEBUG("Password is expired");
2552 goto reject;
2555 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2557 /* Calculate the expected challenge response */
2558 pwlen = strlen(vs->vd->password);
2559 for (i=0; i<sizeof(key); i++)
2560 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2561 deskey(key, EN0);
2562 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2563 des(response+j, response+j);
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 #ifdef CONFIG_VNC_TLS
3006 vs->subauth = VNC_AUTH_INVALID;
3007 #endif
3008 } else {
3009 vs->auth = vd->auth;
3010 #ifdef CONFIG_VNC_TLS
3011 vs->subauth = vd->subauth;
3012 #endif
3015 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3016 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3017 vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
3020 VNC_DEBUG("New client on socket %d\n", csock);
3021 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3022 qemu_set_nonblock(vs->csock);
3023 #ifdef CONFIG_VNC_WS
3024 if (websocket) {
3025 vs->websocket = 1;
3026 #ifdef CONFIG_VNC_TLS
3027 if (vd->tls.x509cert) {
3028 qemu_set_fd_handler2(vs->csock, NULL, vncws_tls_handshake_peek,
3029 NULL, vs);
3030 } else
3031 #endif /* CONFIG_VNC_TLS */
3033 qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read,
3034 NULL, vs);
3036 } else
3037 #endif /* CONFIG_VNC_WS */
3039 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
3042 vnc_client_cache_addr(vs);
3043 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3044 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3046 #ifdef CONFIG_VNC_WS
3047 if (!vs->websocket)
3048 #endif
3050 vnc_init_state(vs);
3053 if (vd->num_connecting > vd->connections_limit) {
3054 QTAILQ_FOREACH(vs, &vd->clients, next) {
3055 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3056 vnc_disconnect_start(vs);
3057 return;
3063 void vnc_init_state(VncState *vs)
3065 vs->initialized = true;
3066 VncDisplay *vd = vs->vd;
3068 vs->last_x = -1;
3069 vs->last_y = -1;
3071 vs->as.freq = 44100;
3072 vs->as.nchannels = 2;
3073 vs->as.fmt = AUD_FMT_S16;
3074 vs->as.endianness = 0;
3076 qemu_mutex_init(&vs->output_mutex);
3077 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3079 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3081 graphic_hw_update(vd->dcl.con);
3083 vnc_write(vs, "RFB 003.008\n", 12);
3084 vnc_flush(vs);
3085 vnc_read_when(vs, protocol_version, 12);
3086 reset_keys(vs);
3087 if (vs->vd->lock_key_sync)
3088 vs->led = qemu_add_led_event_handler(kbd_leds, vs);
3090 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3091 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3093 /* vs might be free()ed here */
3096 static void vnc_listen_read(void *opaque, bool websocket)
3098 VncDisplay *vs = opaque;
3099 struct sockaddr_in addr;
3100 socklen_t addrlen = sizeof(addr);
3101 int csock;
3103 /* Catch-up */
3104 graphic_hw_update(vs->dcl.con);
3105 #ifdef CONFIG_VNC_WS
3106 if (websocket) {
3107 csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
3108 } else
3109 #endif /* CONFIG_VNC_WS */
3111 csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
3114 if (csock != -1) {
3115 socket_set_nodelay(csock);
3116 vnc_connect(vs, csock, false, websocket);
3120 static void vnc_listen_regular_read(void *opaque)
3122 vnc_listen_read(opaque, false);
3125 #ifdef CONFIG_VNC_WS
3126 static void vnc_listen_websocket_read(void *opaque)
3128 vnc_listen_read(opaque, true);
3130 #endif /* CONFIG_VNC_WS */
3132 static const DisplayChangeListenerOps dcl_ops = {
3133 .dpy_name = "vnc",
3134 .dpy_refresh = vnc_refresh,
3135 .dpy_gfx_copy = vnc_dpy_copy,
3136 .dpy_gfx_update = vnc_dpy_update,
3137 .dpy_gfx_switch = vnc_dpy_switch,
3138 .dpy_gfx_check_format = qemu_pixman_check_format,
3139 .dpy_mouse_set = vnc_mouse_set,
3140 .dpy_cursor_define = vnc_dpy_cursor_define,
3143 void vnc_display_init(const char *id)
3145 VncDisplay *vs;
3147 if (vnc_display_find(id) != NULL) {
3148 return;
3150 vs = g_malloc0(sizeof(*vs));
3152 vs->id = strdup(id);
3153 QTAILQ_INSERT_TAIL(&vnc_displays, vs, next);
3155 vs->lsock = -1;
3156 #ifdef CONFIG_VNC_WS
3157 vs->lwebsock = -1;
3158 #endif
3160 QTAILQ_INIT(&vs->clients);
3161 vs->expires = TIME_MAX;
3163 if (keyboard_layout) {
3164 trace_vnc_key_map_init(keyboard_layout);
3165 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
3166 } else {
3167 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
3170 if (!vs->kbd_layout)
3171 exit(1);
3173 qemu_mutex_init(&vs->mutex);
3174 vnc_start_worker_thread();
3176 vs->dcl.ops = &dcl_ops;
3177 register_displaychangelistener(&vs->dcl);
3181 static void vnc_display_close(VncDisplay *vs)
3183 if (!vs)
3184 return;
3185 g_free(vs->display);
3186 vs->display = NULL;
3187 if (vs->lsock != -1) {
3188 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
3189 close(vs->lsock);
3190 vs->lsock = -1;
3192 #ifdef CONFIG_VNC_WS
3193 g_free(vs->ws_display);
3194 vs->ws_display = NULL;
3195 if (vs->lwebsock != -1) {
3196 qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
3197 close(vs->lwebsock);
3198 vs->lwebsock = -1;
3200 #endif /* CONFIG_VNC_WS */
3201 vs->auth = VNC_AUTH_INVALID;
3202 #ifdef CONFIG_VNC_TLS
3203 vs->subauth = VNC_AUTH_INVALID;
3204 vs->tls.x509verify = 0;
3205 #endif
3208 int vnc_display_password(const char *id, const char *password)
3210 VncDisplay *vs = vnc_display_find(id);
3212 if (!vs) {
3213 return -EINVAL;
3215 if (vs->auth == VNC_AUTH_NONE) {
3216 error_printf_unless_qmp("If you want use passwords please enable "
3217 "password auth using '-vnc ${dpy},password'.");
3218 return -EINVAL;
3221 g_free(vs->password);
3222 vs->password = g_strdup(password);
3224 return 0;
3227 int vnc_display_pw_expire(const char *id, time_t expires)
3229 VncDisplay *vs = vnc_display_find(id);
3231 if (!vs) {
3232 return -EINVAL;
3235 vs->expires = expires;
3236 return 0;
3239 char *vnc_display_local_addr(const char *id)
3241 VncDisplay *vs = vnc_display_find(id);
3243 return vnc_socket_local_addr("%s:%s", vs->lsock);
3246 static QemuOptsList qemu_vnc_opts = {
3247 .name = "vnc",
3248 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3249 .implied_opt_name = "vnc",
3250 .desc = {
3252 .name = "vnc",
3253 .type = QEMU_OPT_STRING,
3255 .name = "websocket",
3256 .type = QEMU_OPT_STRING,
3258 .name = "x509",
3259 .type = QEMU_OPT_STRING,
3261 .name = "share",
3262 .type = QEMU_OPT_STRING,
3264 .name = "display",
3265 .type = QEMU_OPT_STRING,
3267 .name = "head",
3268 .type = QEMU_OPT_NUMBER,
3270 .name = "connections",
3271 .type = QEMU_OPT_NUMBER,
3273 .name = "password",
3274 .type = QEMU_OPT_BOOL,
3276 .name = "reverse",
3277 .type = QEMU_OPT_BOOL,
3279 .name = "lock-key-sync",
3280 .type = QEMU_OPT_BOOL,
3282 .name = "sasl",
3283 .type = QEMU_OPT_BOOL,
3285 .name = "tls",
3286 .type = QEMU_OPT_BOOL,
3288 .name = "x509verify",
3289 .type = QEMU_OPT_BOOL,
3291 .name = "acl",
3292 .type = QEMU_OPT_BOOL,
3294 .name = "lossy",
3295 .type = QEMU_OPT_BOOL,
3297 .name = "non-adaptive",
3298 .type = QEMU_OPT_BOOL,
3300 { /* end of list */ }
3304 void vnc_display_open(const char *id, Error **errp)
3306 VncDisplay *vs = vnc_display_find(id);
3307 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3308 const char *display, *websocket, *share, *device_id;
3309 QemuConsole *con;
3310 int password = 0;
3311 int reverse = 0;
3312 #ifdef CONFIG_VNC_TLS
3313 int tls = 0, x509 = 0;
3314 const char *path;
3315 #endif
3316 #ifdef CONFIG_VNC_SASL
3317 int sasl = 0;
3318 int saslErr;
3319 #endif
3320 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3321 int acl = 0;
3322 #endif
3323 int lock_key_sync = 1;
3325 if (!vs) {
3326 error_setg(errp, "VNC display not active");
3327 return;
3329 vnc_display_close(vs);
3331 if (!opts) {
3332 return;
3334 display = qemu_opt_get(opts, "vnc");
3335 if (!display || strcmp(display, "none") == 0) {
3336 return;
3338 vs->display = g_strdup(display);
3340 password = qemu_opt_get_bool(opts, "password", false);
3341 if (password && fips_get_state()) {
3342 error_setg(errp,
3343 "VNC password auth disabled due to FIPS mode, "
3344 "consider using the VeNCrypt or SASL authentication "
3345 "methods as an alternative");
3346 goto fail;
3349 reverse = qemu_opt_get_bool(opts, "reverse", false);
3350 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3351 #ifdef CONFIG_VNC_SASL
3352 sasl = qemu_opt_get_bool(opts, "sasl", false);
3353 #endif
3354 #ifdef CONFIG_VNC_TLS
3355 tls = qemu_opt_get_bool(opts, "tls", false);
3356 path = qemu_opt_get(opts, "x509");
3357 if (path) {
3358 x509 = 1;
3359 vs->tls.x509verify = qemu_opt_get_bool(opts, "x509verify", false);
3360 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
3361 error_setg(errp, "Failed to find x509 certificates/keys in %s",
3362 path);
3363 goto fail;
3366 #endif
3367 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3368 acl = qemu_opt_get_bool(opts, "acl", false);
3369 #endif
3371 share = qemu_opt_get(opts, "share");
3372 if (share) {
3373 if (strcmp(share, "ignore") == 0) {
3374 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
3375 } else if (strcmp(share, "allow-exclusive") == 0) {
3376 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3377 } else if (strcmp(share, "force-shared") == 0) {
3378 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3379 } else {
3380 error_setg(errp, "unknown vnc share= option");
3381 goto fail;
3383 } else {
3384 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3386 vs->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3388 #ifdef CONFIG_VNC_WS
3389 websocket = qemu_opt_get(opts, "websocket");
3390 if (websocket) {
3391 /* extract the host specification from display */
3392 char *host = NULL, *host_end = NULL;
3393 vs->websocket = 1;
3395 /* ipv6 hosts have colons */
3396 host_end = strrchr(display, ':');
3397 if (host_end) {
3398 host = g_strndup(display, host_end - display + 1);
3399 } else {
3400 host = g_strdup(":");
3402 vs->ws_display = g_strconcat(host, websocket, NULL);
3403 g_free(host);
3405 #endif /* CONFIG_VNC_WS */
3407 #ifdef CONFIG_VNC_JPEG
3408 vs->lossy = qemu_opt_get_bool(opts, "lossy", false);
3409 #endif
3410 vs->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3411 /* adaptive updates are only used with tight encoding and
3412 * if lossy updates are enabled so we can disable all the
3413 * calculations otherwise */
3414 if (!vs->lossy) {
3415 vs->non_adaptive = true;
3418 #ifdef CONFIG_VNC_TLS
3419 if (acl && x509 && vs->tls.x509verify) {
3420 char *aclname;
3422 if (strcmp(vs->id, "default") == 0) {
3423 aclname = g_strdup("vnc.x509dname");
3424 } else {
3425 aclname = g_strdup_printf("vnc.%s.x509dname", vs->id);
3427 vs->tls.acl = qemu_acl_init(aclname);
3428 if (!vs->tls.acl) {
3429 fprintf(stderr, "Failed to create x509 dname ACL\n");
3430 exit(1);
3432 g_free(aclname);
3434 #endif
3435 #ifdef CONFIG_VNC_SASL
3436 if (acl && sasl) {
3437 char *aclname;
3439 if (strcmp(vs->id, "default") == 0) {
3440 aclname = g_strdup("vnc.username");
3441 } else {
3442 aclname = g_strdup_printf("vnc.%s.username", vs->id);
3444 vs->sasl.acl = qemu_acl_init(aclname);
3445 if (!vs->sasl.acl) {
3446 fprintf(stderr, "Failed to create username ACL\n");
3447 exit(1);
3449 g_free(aclname);
3451 #endif
3454 * Combinations we support here:
3456 * - no-auth (clear text, no auth)
3457 * - password (clear text, weak auth)
3458 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
3459 * - tls (encrypt, weak anonymous creds, no auth)
3460 * - tls + password (encrypt, weak anonymous creds, weak auth)
3461 * - tls + sasl (encrypt, weak anonymous creds, good auth)
3462 * - tls + x509 (encrypt, good x509 creds, no auth)
3463 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
3464 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
3466 * NB1. TLS is a stackable auth scheme.
3467 * NB2. the x509 schemes have option to validate a client cert dname
3469 if (password) {
3470 #ifdef CONFIG_VNC_TLS
3471 if (tls) {
3472 vs->auth = VNC_AUTH_VENCRYPT;
3473 if (x509) {
3474 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3475 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
3476 } else {
3477 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3478 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3480 } else {
3481 #endif /* CONFIG_VNC_TLS */
3482 VNC_DEBUG("Initializing VNC server with password auth\n");
3483 vs->auth = VNC_AUTH_VNC;
3484 #ifdef CONFIG_VNC_TLS
3485 vs->subauth = VNC_AUTH_INVALID;
3487 #endif /* CONFIG_VNC_TLS */
3488 #ifdef CONFIG_VNC_SASL
3489 } else if (sasl) {
3490 #ifdef CONFIG_VNC_TLS
3491 if (tls) {
3492 vs->auth = VNC_AUTH_VENCRYPT;
3493 if (x509) {
3494 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3495 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3496 } else {
3497 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3498 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3500 } else {
3501 #endif /* CONFIG_VNC_TLS */
3502 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3503 vs->auth = VNC_AUTH_SASL;
3504 #ifdef CONFIG_VNC_TLS
3505 vs->subauth = VNC_AUTH_INVALID;
3507 #endif /* CONFIG_VNC_TLS */
3508 #endif /* CONFIG_VNC_SASL */
3509 } else {
3510 #ifdef CONFIG_VNC_TLS
3511 if (tls) {
3512 vs->auth = VNC_AUTH_VENCRYPT;
3513 if (x509) {
3514 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3515 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3516 } else {
3517 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3518 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3520 } else {
3521 #endif
3522 VNC_DEBUG("Initializing VNC server with no auth\n");
3523 vs->auth = VNC_AUTH_NONE;
3524 #ifdef CONFIG_VNC_TLS
3525 vs->subauth = VNC_AUTH_INVALID;
3527 #endif
3530 #ifdef CONFIG_VNC_SASL
3531 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3532 error_setg(errp, "Failed to initialize SASL auth: %s",
3533 sasl_errstring(saslErr, NULL, NULL));
3534 goto fail;
3536 #endif
3537 vs->lock_key_sync = lock_key_sync;
3539 device_id = qemu_opt_get(opts, "display");
3540 if (device_id) {
3541 DeviceState *dev;
3542 int head = qemu_opt_get_number(opts, "head", 0);
3544 dev = qdev_find_recursive(sysbus_get_default(), device_id);
3545 if (dev == NULL) {
3546 error_set(errp, QERR_DEVICE_NOT_FOUND, device_id);
3547 goto fail;
3550 con = qemu_console_lookup_by_device(dev, head);
3551 if (con == NULL) {
3552 error_setg(errp, "Device %s is not bound to a QemuConsole",
3553 device_id);
3554 goto fail;
3556 } else {
3557 con = NULL;
3560 if (con != vs->dcl.con) {
3561 unregister_displaychangelistener(&vs->dcl);
3562 vs->dcl.con = con;
3563 register_displaychangelistener(&vs->dcl);
3566 if (reverse) {
3567 /* connect to viewer */
3568 int csock;
3569 vs->lsock = -1;
3570 #ifdef CONFIG_VNC_WS
3571 vs->lwebsock = -1;
3572 #endif
3573 if (strncmp(display, "unix:", 5) == 0) {
3574 csock = unix_connect(display+5, errp);
3575 } else {
3576 csock = inet_connect(display, errp);
3578 if (csock < 0) {
3579 goto fail;
3581 vnc_connect(vs, csock, false, false);
3582 } else {
3583 /* listen for connects */
3584 char *dpy;
3585 dpy = g_malloc(256);
3586 if (strncmp(display, "unix:", 5) == 0) {
3587 pstrcpy(dpy, 256, "unix:");
3588 vs->lsock = unix_listen(display+5, dpy+5, 256-5, errp);
3589 } else {
3590 vs->lsock = inet_listen(display, dpy, 256,
3591 SOCK_STREAM, 5900, errp);
3592 if (vs->lsock < 0) {
3593 g_free(dpy);
3594 goto fail;
3596 #ifdef CONFIG_VNC_WS
3597 if (vs->websocket) {
3598 if (vs->ws_display) {
3599 vs->lwebsock = inet_listen(vs->ws_display, NULL, 256,
3600 SOCK_STREAM, 0, errp);
3601 } else {
3602 vs->lwebsock = inet_listen(vs->display, NULL, 256,
3603 SOCK_STREAM, 5700, errp);
3606 if (vs->lwebsock < 0) {
3607 if (vs->lsock) {
3608 close(vs->lsock);
3609 vs->lsock = -1;
3611 g_free(dpy);
3612 goto fail;
3615 #endif /* CONFIG_VNC_WS */
3617 g_free(vs->display);
3618 vs->display = dpy;
3619 qemu_set_fd_handler2(vs->lsock, NULL,
3620 vnc_listen_regular_read, NULL, vs);
3621 #ifdef CONFIG_VNC_WS
3622 if (vs->websocket) {
3623 qemu_set_fd_handler2(vs->lwebsock, NULL,
3624 vnc_listen_websocket_read, NULL, vs);
3626 #endif /* CONFIG_VNC_WS */
3628 return;
3630 fail:
3631 g_free(vs->display);
3632 vs->display = NULL;
3633 #ifdef CONFIG_VNC_WS
3634 g_free(vs->ws_display);
3635 vs->ws_display = NULL;
3636 #endif /* CONFIG_VNC_WS */
3639 void vnc_display_add_client(const char *id, int csock, bool skipauth)
3641 VncDisplay *vs = vnc_display_find(id);
3643 if (!vs) {
3644 return;
3646 vnc_connect(vs, csock, skipauth, false);
3649 QemuOpts *vnc_parse_func(const char *str)
3651 return qemu_opts_parse(qemu_find_opts("vnc"), str, 1);
3654 int vnc_init_func(QemuOpts *opts, void *opaque)
3656 Error *local_err = NULL;
3657 QemuOptsList *olist = qemu_find_opts("vnc");
3658 char *id = (char *)qemu_opts_id(opts);
3660 if (!id) {
3661 /* auto-assign id if not present */
3662 int i = 2;
3663 id = g_strdup("default");
3664 while (qemu_opts_find(olist, id)) {
3665 g_free(id);
3666 id = g_strdup_printf("vnc%d", i++);
3668 qemu_opts_set_id(opts, id);
3671 vnc_display_init(id);
3672 vnc_display_open(id, &local_err);
3673 if (local_err != NULL) {
3674 error_report("Failed to start VNC server on `%s': %s",
3675 qemu_opt_get(opts, "display"),
3676 error_get_pretty(local_err));
3677 error_free(local_err);
3678 exit(1);
3680 return 0;
3683 static void vnc_register_config(void)
3685 qemu_add_opts(&qemu_vnc_opts);
3687 machine_init(vnc_register_config);