2 * QEMU VNC display driver
5 * Copyright (C) 2006 Fabrice Bellard
6 * Copyright (C) 2009 Red Hat, Inc
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 #include "qemu_socket.h"
31 #include "qemu-timer.h"
33 #include "qemu-objects.h"
34 #include "qmp-commands.h"
36 #define VNC_REFRESH_INTERVAL_BASE 30
37 #define VNC_REFRESH_INTERVAL_INC 50
38 #define VNC_REFRESH_INTERVAL_MAX 2000
39 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
40 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
42 #include "vnc_keysym.h"
45 static VncDisplay *vnc_display; /* needed for info vnc */
46 static DisplayChangeListener *dcl;
48 static int vnc_cursor_define(VncState *vs);
50 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
53 static const char *mn[] = {
55 [VNC_SHARE_MODE_CONNECTING] = "connecting",
56 [VNC_SHARE_MODE_SHARED] = "shared",
57 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
58 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
60 fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
61 vs->csock, mn[vs->share_mode], mn[mode]);
64 if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
65 vs->vd->num_exclusive--;
67 vs->share_mode = mode;
68 if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
69 vs->vd->num_exclusive++;
73 static char *addr_to_string(const char *format,
74 struct sockaddr_storage *sa,
77 char host[NI_MAXHOST];
78 char serv[NI_MAXSERV];
82 if ((err = getnameinfo((struct sockaddr *)sa, salen,
85 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
86 VNC_DEBUG("Cannot resolve address %d: %s\n",
87 err, gai_strerror(err));
91 /* Enough for the existing format + the 2 vars we're
93 addrlen = strlen(format) + strlen(host) + strlen(serv);
94 addr = g_malloc(addrlen + 1);
95 snprintf(addr, addrlen, format, host, serv);
102 char *vnc_socket_local_addr(const char *format, int fd) {
103 struct sockaddr_storage sa;
107 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
110 return addr_to_string(format, &sa, salen);
113 char *vnc_socket_remote_addr(const char *format, int fd) {
114 struct sockaddr_storage sa;
118 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
121 return addr_to_string(format, &sa, salen);
124 static int put_addr_qdict(QDict *qdict, struct sockaddr_storage *sa,
127 char host[NI_MAXHOST];
128 char serv[NI_MAXSERV];
131 if ((err = getnameinfo((struct sockaddr *)sa, salen,
134 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
135 VNC_DEBUG("Cannot resolve address %d: %s\n",
136 err, gai_strerror(err));
140 qdict_put(qdict, "host", qstring_from_str(host));
141 qdict_put(qdict, "service", qstring_from_str(serv));
142 qdict_put(qdict, "family",qstring_from_str(inet_strfamily(sa->ss_family)));
147 static int vnc_server_addr_put(QDict *qdict, int fd)
149 struct sockaddr_storage sa;
153 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
157 return put_addr_qdict(qdict, &sa, salen);
160 static int vnc_qdict_remote_addr(QDict *qdict, int fd)
162 struct sockaddr_storage sa;
166 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
170 return put_addr_qdict(qdict, &sa, salen);
173 static const char *vnc_auth_name(VncDisplay *vd) {
175 case VNC_AUTH_INVALID:
191 case VNC_AUTH_VENCRYPT:
192 #ifdef CONFIG_VNC_TLS
193 switch (vd->subauth) {
194 case VNC_AUTH_VENCRYPT_PLAIN:
195 return "vencrypt+plain";
196 case VNC_AUTH_VENCRYPT_TLSNONE:
197 return "vencrypt+tls+none";
198 case VNC_AUTH_VENCRYPT_TLSVNC:
199 return "vencrypt+tls+vnc";
200 case VNC_AUTH_VENCRYPT_TLSPLAIN:
201 return "vencrypt+tls+plain";
202 case VNC_AUTH_VENCRYPT_X509NONE:
203 return "vencrypt+x509+none";
204 case VNC_AUTH_VENCRYPT_X509VNC:
205 return "vencrypt+x509+vnc";
206 case VNC_AUTH_VENCRYPT_X509PLAIN:
207 return "vencrypt+x509+plain";
208 case VNC_AUTH_VENCRYPT_TLSSASL:
209 return "vencrypt+tls+sasl";
210 case VNC_AUTH_VENCRYPT_X509SASL:
211 return "vencrypt+x509+sasl";
224 static int vnc_server_info_put(QDict *qdict)
226 if (vnc_server_addr_put(qdict, vnc_display->lsock) < 0) {
230 qdict_put(qdict, "auth", qstring_from_str(vnc_auth_name(vnc_display)));
234 static void vnc_client_cache_auth(VncState *client)
236 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
244 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
245 qdict = qobject_to_qdict(client->info);
248 #ifdef CONFIG_VNC_TLS
249 if (client->tls.session &&
251 qdict_put(qdict, "x509_dname", qstring_from_str(client->tls.dname));
254 #ifdef CONFIG_VNC_SASL
255 if (client->sasl.conn &&
256 client->sasl.username) {
257 qdict_put(qdict, "sasl_username",
258 qstring_from_str(client->sasl.username));
263 static void vnc_client_cache_addr(VncState *client)
268 if (vnc_qdict_remote_addr(qdict, client->csock) < 0) {
270 /* XXX: how to report the error? */
274 client->info = QOBJECT(qdict);
277 static void vnc_qmp_event(VncState *vs, MonitorEvent event)
286 server = qdict_new();
287 if (vnc_server_info_put(server) < 0) {
292 data = qobject_from_jsonf("{ 'client': %p, 'server': %p }",
293 vs->info, QOBJECT(server));
295 monitor_protocol_event(event, data);
297 qobject_incref(vs->info);
298 qobject_decref(data);
301 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
303 struct sockaddr_storage sa;
304 socklen_t salen = sizeof(sa);
305 char host[NI_MAXHOST];
306 char serv[NI_MAXSERV];
309 if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
313 if (getnameinfo((struct sockaddr *)&sa, salen,
316 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
320 info = g_malloc0(sizeof(*info));
321 info->host = g_strdup(host);
322 info->service = g_strdup(serv);
323 info->family = g_strdup(inet_strfamily(sa.ss_family));
325 #ifdef CONFIG_VNC_TLS
326 if (client->tls.session && client->tls.dname) {
327 info->has_x509_dname = true;
328 info->x509_dname = g_strdup(client->tls.dname);
331 #ifdef CONFIG_VNC_SASL
332 if (client->sasl.conn && client->sasl.username) {
333 info->has_sasl_username = true;
334 info->sasl_username = g_strdup(client->sasl.username);
341 VncInfo *qmp_query_vnc(Error **errp)
343 VncInfo *info = g_malloc0(sizeof(*info));
345 if (vnc_display == NULL || vnc_display->display == NULL) {
346 info->enabled = false;
348 VncClientInfoList *cur_item = NULL;
349 struct sockaddr_storage sa;
350 socklen_t salen = sizeof(sa);
351 char host[NI_MAXHOST];
352 char serv[NI_MAXSERV];
355 info->enabled = true;
357 /* for compatibility with the original command */
358 info->has_clients = true;
360 QTAILQ_FOREACH(client, &vnc_display->clients, next) {
361 VncClientInfoList *cinfo = g_malloc0(sizeof(*info));
362 cinfo->value = qmp_query_vnc_client(client);
364 /* XXX: waiting for the qapi to support GSList */
366 info->clients = cur_item = cinfo;
368 cur_item->next = cinfo;
373 if (getsockname(vnc_display->lsock, (struct sockaddr *)&sa,
375 error_set(errp, QERR_UNDEFINED_ERROR);
379 if (getnameinfo((struct sockaddr *)&sa, salen,
382 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
383 error_set(errp, QERR_UNDEFINED_ERROR);
387 info->has_host = true;
388 info->host = g_strdup(host);
390 info->has_service = true;
391 info->service = g_strdup(serv);
393 info->has_family = true;
394 info->family = g_strdup(inet_strfamily(sa.ss_family));
396 info->has_auth = true;
397 info->auth = g_strdup(vnc_auth_name(vnc_display));
403 qapi_free_VncInfo(info);
408 1) Get the queue working for IO.
409 2) there is some weirdness when using the -S option (the screen is grey
410 and not totally invalidated
411 3) resolutions > 1024
414 static int vnc_update_client(VncState *vs, int has_dirty);
415 static int vnc_update_client_sync(VncState *vs, int has_dirty);
416 static void vnc_disconnect_start(VncState *vs);
417 static void vnc_disconnect_finish(VncState *vs);
418 static void vnc_init_timer(VncDisplay *vd);
419 static void vnc_remove_timer(VncDisplay *vd);
421 static void vnc_colordepth(VncState *vs);
422 static void framebuffer_update_request(VncState *vs, int incremental,
423 int x_position, int y_position,
425 static void vnc_refresh(void *opaque);
426 static int vnc_refresh_server_surface(VncDisplay *vd);
428 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
431 VncDisplay *vd = ds->opaque;
432 struct VncSurface *s = &vd->guest;
436 /* round x down to ensure the loop only spans one 16-pixel block per,
437 iteration. otherwise, if (x % 16) != 0, the last iteration may span
438 two 16-pixel blocks but we only mark the first as dirty
443 x = MIN(x, s->ds->width);
444 y = MIN(y, s->ds->height);
445 w = MIN(x + w, s->ds->width) - x;
446 h = MIN(h, s->ds->height);
449 for (i = 0; i < w; i += 16)
450 set_bit((x + i) / 16, s->dirty[y]);
453 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
456 vnc_write_u16(vs, x);
457 vnc_write_u16(vs, y);
458 vnc_write_u16(vs, w);
459 vnc_write_u16(vs, h);
461 vnc_write_s32(vs, encoding);
464 void buffer_reserve(Buffer *buffer, size_t len)
466 if ((buffer->capacity - buffer->offset) < len) {
467 buffer->capacity += (len + 1024);
468 buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
469 if (buffer->buffer == NULL) {
470 fprintf(stderr, "vnc: out of memory\n");
476 int buffer_empty(Buffer *buffer)
478 return buffer->offset == 0;
481 uint8_t *buffer_end(Buffer *buffer)
483 return buffer->buffer + buffer->offset;
486 void buffer_reset(Buffer *buffer)
491 void buffer_free(Buffer *buffer)
493 g_free(buffer->buffer);
495 buffer->capacity = 0;
496 buffer->buffer = NULL;
499 void buffer_append(Buffer *buffer, const void *data, size_t len)
501 memcpy(buffer->buffer + buffer->offset, data, len);
502 buffer->offset += len;
505 static void vnc_desktop_resize(VncState *vs)
507 DisplayState *ds = vs->ds;
509 if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
512 if (vs->client_width == ds_get_width(ds) &&
513 vs->client_height == ds_get_height(ds)) {
516 vs->client_width = ds_get_width(ds);
517 vs->client_height = ds_get_height(ds);
519 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
521 vnc_write_u16(vs, 1); /* number of rects */
522 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
523 VNC_ENCODING_DESKTOPRESIZE);
524 vnc_unlock_output(vs);
528 #ifdef CONFIG_VNC_THREAD
529 static void vnc_abort_display_jobs(VncDisplay *vd)
533 QTAILQ_FOREACH(vs, &vd->clients, next) {
536 vnc_unlock_output(vs);
538 QTAILQ_FOREACH(vs, &vd->clients, next) {
541 QTAILQ_FOREACH(vs, &vd->clients, next) {
544 vnc_unlock_output(vs);
548 static void vnc_abort_display_jobs(VncDisplay *vd)
553 static void vnc_dpy_resize(DisplayState *ds)
555 VncDisplay *vd = ds->opaque;
558 vnc_abort_display_jobs(vd);
562 vd->server = g_malloc0(sizeof(*vd->server));
563 if (vd->server->data)
564 g_free(vd->server->data);
565 *(vd->server) = *(ds->surface);
566 vd->server->data = g_malloc0(vd->server->linesize *
571 vd->guest.ds = g_malloc0(sizeof(*vd->guest.ds));
572 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
573 console_color_init(ds);
574 *(vd->guest.ds) = *(ds->surface);
575 memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
577 QTAILQ_FOREACH(vs, &vd->clients, next) {
579 vnc_desktop_resize(vs);
580 if (vs->vd->cursor) {
581 vnc_cursor_define(vs);
583 memset(vs->dirty, 0xFF, sizeof(vs->dirty));
588 static void vnc_write_pixels_copy(VncState *vs, struct PixelFormat *pf,
589 void *pixels, int size)
591 vnc_write(vs, pixels, size);
594 /* slowest but generic code. */
595 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
598 VncDisplay *vd = vs->vd;
600 r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>
601 vd->server->pf.rbits);
602 g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>
603 vd->server->pf.gbits);
604 b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>
605 vd->server->pf.bbits);
606 v = (r << vs->clientds.pf.rshift) |
607 (g << vs->clientds.pf.gshift) |
608 (b << vs->clientds.pf.bshift);
609 switch(vs->clientds.pf.bytes_per_pixel) {
614 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
624 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
639 static void vnc_write_pixels_generic(VncState *vs, struct PixelFormat *pf,
640 void *pixels1, int size)
644 if (pf->bytes_per_pixel == 4) {
645 uint32_t *pixels = pixels1;
648 for(i = 0; i < n; i++) {
649 vnc_convert_pixel(vs, buf, pixels[i]);
650 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
652 } else if (pf->bytes_per_pixel == 2) {
653 uint16_t *pixels = pixels1;
656 for(i = 0; i < n; i++) {
657 vnc_convert_pixel(vs, buf, pixels[i]);
658 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
660 } else if (pf->bytes_per_pixel == 1) {
661 uint8_t *pixels = pixels1;
664 for(i = 0; i < n; i++) {
665 vnc_convert_pixel(vs, buf, pixels[i]);
666 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
669 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
673 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
677 VncDisplay *vd = vs->vd;
679 row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
680 for (i = 0; i < h; i++) {
681 vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds));
682 row += ds_get_linesize(vs->ds);
687 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
691 switch(vs->vnc_encoding) {
692 case VNC_ENCODING_ZLIB:
693 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
695 case VNC_ENCODING_HEXTILE:
696 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
697 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
699 case VNC_ENCODING_TIGHT:
700 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
702 case VNC_ENCODING_TIGHT_PNG:
703 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
705 case VNC_ENCODING_ZRLE:
706 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
708 case VNC_ENCODING_ZYWRLE:
709 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
712 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
713 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
719 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
721 /* send bitblit op to the vnc client */
723 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
725 vnc_write_u16(vs, 1); /* number of rects */
726 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
727 vnc_write_u16(vs, src_x);
728 vnc_write_u16(vs, src_y);
729 vnc_unlock_output(vs);
733 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
735 VncDisplay *vd = ds->opaque;
739 int i,x,y,pitch,depth,inc,w_lim,s;
742 vnc_refresh_server_surface(vd);
743 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
744 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
745 vs->force_update = 1;
746 vnc_update_client_sync(vs, 1);
747 /* vs might be free()ed here */
751 /* do bitblit op on the local surface too */
752 pitch = ds_get_linesize(vd->ds);
753 depth = ds_get_bytes_per_pixel(vd->ds);
754 src_row = vd->server->data + pitch * src_y + depth * src_x;
755 dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
760 src_row += pitch * (h-1);
761 dst_row += pitch * (h-1);
766 w_lim = w - (16 - (dst_x % 16));
770 w_lim = w - (w_lim % 16);
771 for (i = 0; i < h; i++) {
772 for (x = 0; x <= w_lim;
773 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
775 if ((s = w - w_lim) == 0)
778 s = (16 - (dst_x % 16));
783 cmp_bytes = s * depth;
784 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
786 memmove(dst_row, src_row, cmp_bytes);
787 QTAILQ_FOREACH(vs, &vd->clients, next) {
788 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
789 set_bit(((x + dst_x) / 16), vs->dirty[y]);
793 src_row += pitch - w * depth;
794 dst_row += pitch - w * depth;
798 QTAILQ_FOREACH(vs, &vd->clients, next) {
799 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
800 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
805 static void vnc_mouse_set(int x, int y, int visible)
807 /* can we ask the client(s) to move the pointer ??? */
810 static int vnc_cursor_define(VncState *vs)
812 QEMUCursor *c = vs->vd->cursor;
813 PixelFormat pf = qemu_default_pixelformat(32);
816 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
818 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
819 vnc_write_u8(vs, 0); /* padding */
820 vnc_write_u16(vs, 1); /* # of rects */
821 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
822 VNC_ENCODING_RICH_CURSOR);
823 isize = c->width * c->height * vs->clientds.pf.bytes_per_pixel;
824 vnc_write_pixels_generic(vs, &pf, c->data, isize);
825 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
826 vnc_unlock_output(vs);
832 static void vnc_dpy_cursor_define(QEMUCursor *c)
834 VncDisplay *vd = vnc_display;
837 cursor_put(vd->cursor);
838 g_free(vd->cursor_mask);
841 cursor_get(vd->cursor);
842 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
843 vd->cursor_mask = g_malloc0(vd->cursor_msize);
844 cursor_get_mono_mask(c, 0, vd->cursor_mask);
846 QTAILQ_FOREACH(vs, &vd->clients, next) {
847 vnc_cursor_define(vs);
851 static int find_and_clear_dirty_height(struct VncState *vs,
852 int y, int last_x, int x, int height)
856 for (h = 1; h < (height - y); h++) {
858 if (!test_bit(last_x, vs->dirty[y + h])) {
861 for (tmp_x = last_x; tmp_x < x; tmp_x++) {
862 clear_bit(tmp_x, vs->dirty[y + h]);
869 #ifdef CONFIG_VNC_THREAD
870 static int vnc_update_client_sync(VncState *vs, int has_dirty)
872 int ret = vnc_update_client(vs, has_dirty);
877 static int vnc_update_client_sync(VncState *vs, int has_dirty)
879 return vnc_update_client(vs, has_dirty);
883 static int vnc_update_client(VncState *vs, int has_dirty)
885 if (vs->need_update && vs->csock != -1) {
886 VncDisplay *vd = vs->vd;
893 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
894 /* kernel send buffers are full -> drop frames to throttle */
897 if (!has_dirty && !vs->audio_cap && !vs->force_update)
901 * Send screen updates to the vnc client using the server
902 * surface and server dirty map. guest surface updates
903 * happening in parallel don't disturb us, the next pass will
904 * send them to the client.
906 job = vnc_job_new(vs);
908 width = MIN(vd->server->width, vs->client_width);
909 height = MIN(vd->server->height, vs->client_height);
911 for (y = 0; y < height; y++) {
914 for (x = 0; x < width / 16; x++) {
915 if (test_and_clear_bit(x, vs->dirty[y])) {
921 int h = find_and_clear_dirty_height(vs, y, last_x, x,
924 n += vnc_job_add_rect(job, last_x * 16, y,
925 (x - last_x) * 16, h);
931 int h = find_and_clear_dirty_height(vs, y, last_x, x, height);
932 n += vnc_job_add_rect(job, last_x * 16, y,
933 (x - last_x) * 16, h);
938 vs->force_update = 0;
943 vnc_disconnect_finish(vs);
949 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
951 VncState *vs = opaque;
954 case AUD_CNOTIFY_DISABLE:
956 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
957 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
958 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
959 vnc_unlock_output(vs);
963 case AUD_CNOTIFY_ENABLE:
965 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
966 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
967 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
968 vnc_unlock_output(vs);
974 static void audio_capture_destroy(void *opaque)
978 static void audio_capture(void *opaque, void *buf, int size)
980 VncState *vs = opaque;
983 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
984 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
985 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
986 vnc_write_u32(vs, size);
987 vnc_write(vs, buf, size);
988 vnc_unlock_output(vs);
992 static void audio_add(VncState *vs)
994 struct audio_capture_ops ops;
997 monitor_printf(default_mon, "audio already running\n");
1001 ops.notify = audio_capture_notify;
1002 ops.destroy = audio_capture_destroy;
1003 ops.capture = audio_capture;
1005 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1006 if (!vs->audio_cap) {
1007 monitor_printf(default_mon, "Failed to add audio capture\n");
1011 static void audio_del(VncState *vs)
1013 if (vs->audio_cap) {
1014 AUD_del_capture(vs->audio_cap, vs);
1015 vs->audio_cap = NULL;
1019 static void vnc_disconnect_start(VncState *vs)
1021 if (vs->csock == -1)
1023 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1024 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1025 closesocket(vs->csock);
1029 static void vnc_disconnect_finish(VncState *vs)
1033 vnc_jobs_join(vs); /* Wait encoding jobs */
1035 vnc_lock_output(vs);
1036 vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
1038 buffer_free(&vs->input);
1039 buffer_free(&vs->output);
1041 qobject_decref(vs->info);
1044 vnc_tight_clear(vs);
1047 #ifdef CONFIG_VNC_TLS
1048 vnc_tls_client_cleanup(vs);
1049 #endif /* CONFIG_VNC_TLS */
1050 #ifdef CONFIG_VNC_SASL
1051 vnc_sasl_client_cleanup(vs);
1052 #endif /* CONFIG_VNC_SASL */
1055 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1057 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1061 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1062 vnc_remove_timer(vs->vd);
1063 if (vs->vd->lock_key_sync)
1064 qemu_remove_led_event_handler(vs->led);
1065 vnc_unlock_output(vs);
1067 #ifdef CONFIG_VNC_THREAD
1068 qemu_mutex_destroy(&vs->output_mutex);
1070 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1071 g_free(vs->lossy_rect[i]);
1073 g_free(vs->lossy_rect);
1077 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1079 if (ret == 0 || ret == -1) {
1081 switch (last_errno) {
1085 case WSAEWOULDBLOCK:
1093 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1094 ret, ret < 0 ? last_errno : 0);
1095 vnc_disconnect_start(vs);
1103 void vnc_client_error(VncState *vs)
1105 VNC_DEBUG("Closing down client sock: protocol error\n");
1106 vnc_disconnect_start(vs);
1111 * Called to write a chunk of data to the client socket. The data may
1112 * be the raw data, or may have already been encoded by SASL.
1113 * The data will be written either straight onto the socket, or
1114 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1116 * NB, it is theoretically possible to have 2 layers of encryption,
1117 * both SASL, and this TLS layer. It is highly unlikely in practice
1118 * though, since SASL encryption will typically be a no-op if TLS
1121 * Returns the number of bytes written, which may be less than
1122 * the requested 'datalen' if the socket would block. Returns
1123 * -1 on error, and disconnects the client socket.
1125 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1128 #ifdef CONFIG_VNC_TLS
1129 if (vs->tls.session) {
1130 ret = gnutls_write(vs->tls.session, data, datalen);
1132 if (ret == GNUTLS_E_AGAIN)
1139 #endif /* CONFIG_VNC_TLS */
1140 ret = send(vs->csock, (const void *)data, datalen, 0);
1141 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1142 return vnc_client_io_error(vs, ret, socket_error());
1147 * Called to write buffered data to the client socket, when not
1148 * using any SASL SSF encryption layers. Will write as much data
1149 * as possible without blocking. If all buffered data is written,
1150 * will switch the FD poll() handler back to read monitoring.
1152 * Returns the number of bytes written, which may be less than
1153 * the buffered output data if the socket would block. Returns
1154 * -1 on error, and disconnects the client socket.
1156 static long vnc_client_write_plain(VncState *vs)
1160 #ifdef CONFIG_VNC_SASL
1161 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1162 vs->output.buffer, vs->output.capacity, vs->output.offset,
1163 vs->sasl.waitWriteSSF);
1165 if (vs->sasl.conn &&
1167 vs->sasl.waitWriteSSF) {
1168 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1170 vs->sasl.waitWriteSSF -= ret;
1172 #endif /* CONFIG_VNC_SASL */
1173 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1177 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1178 vs->output.offset -= ret;
1180 if (vs->output.offset == 0) {
1181 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1189 * First function called whenever there is data to be written to
1190 * the client socket. Will delegate actual work according to whether
1191 * SASL SSF layers are enabled (thus requiring encryption calls)
1193 static void vnc_client_write_locked(void *opaque)
1195 VncState *vs = opaque;
1197 #ifdef CONFIG_VNC_SASL
1198 if (vs->sasl.conn &&
1200 !vs->sasl.waitWriteSSF) {
1201 vnc_client_write_sasl(vs);
1203 #endif /* CONFIG_VNC_SASL */
1204 vnc_client_write_plain(vs);
1207 void vnc_client_write(void *opaque)
1209 VncState *vs = opaque;
1211 vnc_lock_output(vs);
1212 if (vs->output.offset) {
1213 vnc_client_write_locked(opaque);
1214 } else if (vs->csock != -1) {
1215 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1217 vnc_unlock_output(vs);
1220 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1222 vs->read_handler = func;
1223 vs->read_handler_expect = expecting;
1228 * Called to read a chunk of data from the client socket. The data may
1229 * be the raw data, or may need to be further decoded by SASL.
1230 * The data will be read either straight from to the socket, or
1231 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1233 * NB, it is theoretically possible to have 2 layers of encryption,
1234 * both SASL, and this TLS layer. It is highly unlikely in practice
1235 * though, since SASL encryption will typically be a no-op if TLS
1238 * Returns the number of bytes read, which may be less than
1239 * the requested 'datalen' if the socket would block. Returns
1240 * -1 on error, and disconnects the client socket.
1242 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1245 #ifdef CONFIG_VNC_TLS
1246 if (vs->tls.session) {
1247 ret = gnutls_read(vs->tls.session, data, datalen);
1249 if (ret == GNUTLS_E_AGAIN)
1256 #endif /* CONFIG_VNC_TLS */
1257 ret = qemu_recv(vs->csock, data, datalen, 0);
1258 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1259 return vnc_client_io_error(vs, ret, socket_error());
1264 * Called to read data from the client socket to the input buffer,
1265 * when not using any SASL SSF encryption layers. Will read as much
1266 * data as possible without blocking.
1268 * Returns the number of bytes read. Returns -1 on error, and
1269 * disconnects the client socket.
1271 static long vnc_client_read_plain(VncState *vs)
1274 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1275 vs->input.buffer, vs->input.capacity, vs->input.offset);
1276 buffer_reserve(&vs->input, 4096);
1277 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1280 vs->input.offset += ret;
1286 * First function called whenever there is more data to be read from
1287 * the client socket. Will delegate actual work according to whether
1288 * SASL SSF layers are enabled (thus requiring decryption calls)
1290 void vnc_client_read(void *opaque)
1292 VncState *vs = opaque;
1295 #ifdef CONFIG_VNC_SASL
1296 if (vs->sasl.conn && vs->sasl.runSSF)
1297 ret = vnc_client_read_sasl(vs);
1299 #endif /* CONFIG_VNC_SASL */
1300 ret = vnc_client_read_plain(vs);
1302 if (vs->csock == -1)
1303 vnc_disconnect_finish(vs);
1307 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1308 size_t len = vs->read_handler_expect;
1311 ret = vs->read_handler(vs, vs->input.buffer, len);
1312 if (vs->csock == -1) {
1313 vnc_disconnect_finish(vs);
1318 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1319 vs->input.offset -= len;
1321 vs->read_handler_expect = ret;
1326 void vnc_write(VncState *vs, const void *data, size_t len)
1328 buffer_reserve(&vs->output, len);
1330 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1331 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1334 buffer_append(&vs->output, data, len);
1337 void vnc_write_s32(VncState *vs, int32_t value)
1339 vnc_write_u32(vs, *(uint32_t *)&value);
1342 void vnc_write_u32(VncState *vs, uint32_t value)
1346 buf[0] = (value >> 24) & 0xFF;
1347 buf[1] = (value >> 16) & 0xFF;
1348 buf[2] = (value >> 8) & 0xFF;
1349 buf[3] = value & 0xFF;
1351 vnc_write(vs, buf, 4);
1354 void vnc_write_u16(VncState *vs, uint16_t value)
1358 buf[0] = (value >> 8) & 0xFF;
1359 buf[1] = value & 0xFF;
1361 vnc_write(vs, buf, 2);
1364 void vnc_write_u8(VncState *vs, uint8_t value)
1366 vnc_write(vs, (char *)&value, 1);
1369 void vnc_flush(VncState *vs)
1371 vnc_lock_output(vs);
1372 if (vs->csock != -1 && vs->output.offset) {
1373 vnc_client_write_locked(vs);
1375 vnc_unlock_output(vs);
1378 uint8_t read_u8(uint8_t *data, size_t offset)
1380 return data[offset];
1383 uint16_t read_u16(uint8_t *data, size_t offset)
1385 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1388 int32_t read_s32(uint8_t *data, size_t offset)
1390 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1391 (data[offset + 2] << 8) | data[offset + 3]);
1394 uint32_t read_u32(uint8_t *data, size_t offset)
1396 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1397 (data[offset + 2] << 8) | data[offset + 3]);
1400 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1404 static void check_pointer_type_change(Notifier *notifier, void *data)
1406 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1407 int absolute = kbd_mouse_is_absolute();
1409 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1410 vnc_lock_output(vs);
1411 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1412 vnc_write_u8(vs, 0);
1413 vnc_write_u16(vs, 1);
1414 vnc_framebuffer_update(vs, absolute, 0,
1415 ds_get_width(vs->ds), ds_get_height(vs->ds),
1416 VNC_ENCODING_POINTER_TYPE_CHANGE);
1417 vnc_unlock_output(vs);
1420 vs->absolute = absolute;
1423 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1428 if (button_mask & 0x01)
1429 buttons |= MOUSE_EVENT_LBUTTON;
1430 if (button_mask & 0x02)
1431 buttons |= MOUSE_EVENT_MBUTTON;
1432 if (button_mask & 0x04)
1433 buttons |= MOUSE_EVENT_RBUTTON;
1434 if (button_mask & 0x08)
1436 if (button_mask & 0x10)
1440 kbd_mouse_event(ds_get_width(vs->ds) > 1 ?
1441 x * 0x7FFF / (ds_get_width(vs->ds) - 1) : 0x4000,
1442 ds_get_height(vs->ds) > 1 ?
1443 y * 0x7FFF / (ds_get_height(vs->ds) - 1) : 0x4000,
1445 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1449 kbd_mouse_event(x, y, dz, buttons);
1451 if (vs->last_x != -1)
1452 kbd_mouse_event(x - vs->last_x,
1460 static void reset_keys(VncState *vs)
1463 for(i = 0; i < 256; i++) {
1464 if (vs->modifiers_state[i]) {
1465 if (i & SCANCODE_GREY)
1466 kbd_put_keycode(SCANCODE_EMUL0);
1467 kbd_put_keycode(i | SCANCODE_UP);
1468 vs->modifiers_state[i] = 0;
1473 static void press_key(VncState *vs, int keysym)
1475 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1476 if (keycode & SCANCODE_GREY)
1477 kbd_put_keycode(SCANCODE_EMUL0);
1478 kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1479 if (keycode & SCANCODE_GREY)
1480 kbd_put_keycode(SCANCODE_EMUL0);
1481 kbd_put_keycode(keycode | SCANCODE_UP);
1484 static void kbd_leds(void *opaque, int ledstate)
1486 VncState *vs = opaque;
1489 caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1490 num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
1492 if (vs->modifiers_state[0x3a] != caps) {
1493 vs->modifiers_state[0x3a] = caps;
1495 if (vs->modifiers_state[0x45] != num) {
1496 vs->modifiers_state[0x45] = num;
1500 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1502 /* QEMU console switch */
1504 case 0x2a: /* Left Shift */
1505 case 0x36: /* Right Shift */
1506 case 0x1d: /* Left CTRL */
1507 case 0x9d: /* Right CTRL */
1508 case 0x38: /* Left ALT */
1509 case 0xb8: /* Right ALT */
1511 vs->modifiers_state[keycode] = 1;
1513 vs->modifiers_state[keycode] = 0;
1515 case 0x02 ... 0x0a: /* '1' to '9' keys */
1516 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1517 /* Reset the modifiers sent to the current console */
1519 console_select(keycode - 0x02);
1523 case 0x3a: /* CapsLock */
1524 case 0x45: /* NumLock */
1526 vs->modifiers_state[keycode] ^= 1;
1530 if (down && vs->vd->lock_key_sync &&
1531 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1532 /* If the numlock state needs to change then simulate an additional
1533 keypress before sending this one. This will happen if the user
1534 toggles numlock away from the VNC window.
1536 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1537 if (!vs->modifiers_state[0x45]) {
1538 vs->modifiers_state[0x45] = 1;
1539 press_key(vs, 0xff7f);
1542 if (vs->modifiers_state[0x45]) {
1543 vs->modifiers_state[0x45] = 0;
1544 press_key(vs, 0xff7f);
1549 if (down && vs->vd->lock_key_sync &&
1550 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1551 /* If the capslock state needs to change then simulate an additional
1552 keypress before sending this one. This will happen if the user
1553 toggles capslock away from the VNC window.
1555 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1556 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1557 int capslock = !!(vs->modifiers_state[0x3a]);
1559 if (uppercase == shift) {
1560 vs->modifiers_state[0x3a] = 0;
1561 press_key(vs, 0xffe5);
1564 if (uppercase != shift) {
1565 vs->modifiers_state[0x3a] = 1;
1566 press_key(vs, 0xffe5);
1571 if (is_graphic_console()) {
1572 if (keycode & SCANCODE_GREY)
1573 kbd_put_keycode(SCANCODE_EMUL0);
1575 kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1577 kbd_put_keycode(keycode | SCANCODE_UP);
1579 bool numlock = vs->modifiers_state[0x45];
1580 bool control = (vs->modifiers_state[0x1d] ||
1581 vs->modifiers_state[0x9d]);
1582 /* QEMU console emulation */
1585 case 0x2a: /* Left Shift */
1586 case 0x36: /* Right Shift */
1587 case 0x1d: /* Left CTRL */
1588 case 0x9d: /* Right CTRL */
1589 case 0x38: /* Left ALT */
1590 case 0xb8: /* Right ALT */
1593 kbd_put_keysym(QEMU_KEY_UP);
1596 kbd_put_keysym(QEMU_KEY_DOWN);
1599 kbd_put_keysym(QEMU_KEY_LEFT);
1602 kbd_put_keysym(QEMU_KEY_RIGHT);
1605 kbd_put_keysym(QEMU_KEY_DELETE);
1608 kbd_put_keysym(QEMU_KEY_HOME);
1611 kbd_put_keysym(QEMU_KEY_END);
1614 kbd_put_keysym(QEMU_KEY_PAGEUP);
1617 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1621 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1624 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1627 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1630 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1633 kbd_put_keysym('5');
1636 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1639 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1642 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1645 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1648 kbd_put_keysym('0');
1651 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1655 kbd_put_keysym('/');
1658 kbd_put_keysym('*');
1661 kbd_put_keysym('-');
1664 kbd_put_keysym('+');
1667 kbd_put_keysym('\n');
1672 kbd_put_keysym(sym & 0x1f);
1674 kbd_put_keysym(sym);
1682 static void key_event(VncState *vs, int down, uint32_t sym)
1687 if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1688 lsym = lsym - 'A' + 'a';
1691 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1692 do_key_event(vs, down, keycode, sym);
1695 static void ext_key_event(VncState *vs, int down,
1696 uint32_t sym, uint16_t keycode)
1698 /* if the user specifies a keyboard layout, always use it */
1699 if (keyboard_layout)
1700 key_event(vs, down, sym);
1702 do_key_event(vs, down, keycode, sym);
1705 static void framebuffer_update_request(VncState *vs, int incremental,
1706 int x_position, int y_position,
1710 const size_t width = ds_get_width(vs->ds) / 16;
1712 if (y_position > ds_get_height(vs->ds))
1713 y_position = ds_get_height(vs->ds);
1714 if (y_position + h >= ds_get_height(vs->ds))
1715 h = ds_get_height(vs->ds) - y_position;
1717 vs->need_update = 1;
1719 vs->force_update = 1;
1720 for (i = 0; i < h; i++) {
1721 bitmap_set(vs->dirty[y_position + i], 0, width);
1722 bitmap_clear(vs->dirty[y_position + i], width,
1723 VNC_DIRTY_BITS - width);
1728 static void send_ext_key_event_ack(VncState *vs)
1730 vnc_lock_output(vs);
1731 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1732 vnc_write_u8(vs, 0);
1733 vnc_write_u16(vs, 1);
1734 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1735 VNC_ENCODING_EXT_KEY_EVENT);
1736 vnc_unlock_output(vs);
1740 static void send_ext_audio_ack(VncState *vs)
1742 vnc_lock_output(vs);
1743 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1744 vnc_write_u8(vs, 0);
1745 vnc_write_u16(vs, 1);
1746 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1747 VNC_ENCODING_AUDIO);
1748 vnc_unlock_output(vs);
1752 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1755 unsigned int enc = 0;
1758 vs->vnc_encoding = 0;
1759 vs->tight.compression = 9;
1760 vs->tight.quality = -1; /* Lossless by default */
1764 * Start from the end because the encodings are sent in order of preference.
1765 * This way the preferred encoding (first encoding defined in the array)
1766 * will be set at the end of the loop.
1768 for (i = n_encodings - 1; i >= 0; i--) {
1771 case VNC_ENCODING_RAW:
1772 vs->vnc_encoding = enc;
1774 case VNC_ENCODING_COPYRECT:
1775 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1777 case VNC_ENCODING_HEXTILE:
1778 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1779 vs->vnc_encoding = enc;
1781 case VNC_ENCODING_TIGHT:
1782 vs->features |= VNC_FEATURE_TIGHT_MASK;
1783 vs->vnc_encoding = enc;
1785 case VNC_ENCODING_TIGHT_PNG:
1786 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
1787 vs->vnc_encoding = enc;
1789 case VNC_ENCODING_ZLIB:
1790 vs->features |= VNC_FEATURE_ZLIB_MASK;
1791 vs->vnc_encoding = enc;
1793 case VNC_ENCODING_ZRLE:
1794 vs->features |= VNC_FEATURE_ZRLE_MASK;
1795 vs->vnc_encoding = enc;
1797 case VNC_ENCODING_ZYWRLE:
1798 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
1799 vs->vnc_encoding = enc;
1801 case VNC_ENCODING_DESKTOPRESIZE:
1802 vs->features |= VNC_FEATURE_RESIZE_MASK;
1804 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1805 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1807 case VNC_ENCODING_RICH_CURSOR:
1808 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1810 case VNC_ENCODING_EXT_KEY_EVENT:
1811 send_ext_key_event_ack(vs);
1813 case VNC_ENCODING_AUDIO:
1814 send_ext_audio_ack(vs);
1816 case VNC_ENCODING_WMVi:
1817 vs->features |= VNC_FEATURE_WMVI_MASK;
1819 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1820 vs->tight.compression = (enc & 0x0F);
1822 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1823 if (vs->vd->lossy) {
1824 vs->tight.quality = (enc & 0x0F);
1828 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1832 vnc_desktop_resize(vs);
1833 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
1836 static void set_pixel_conversion(VncState *vs)
1838 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1839 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1840 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1841 vs->write_pixels = vnc_write_pixels_copy;
1842 vnc_hextile_set_pixel_conversion(vs, 0);
1844 vs->write_pixels = vnc_write_pixels_generic;
1845 vnc_hextile_set_pixel_conversion(vs, 1);
1849 static void set_pixel_format(VncState *vs,
1850 int bits_per_pixel, int depth,
1851 int big_endian_flag, int true_color_flag,
1852 int red_max, int green_max, int blue_max,
1853 int red_shift, int green_shift, int blue_shift)
1855 if (!true_color_flag) {
1856 vnc_client_error(vs);
1860 vs->clientds = *(vs->vd->guest.ds);
1861 vs->clientds.pf.rmax = red_max;
1862 vs->clientds.pf.rbits = hweight_long(red_max);
1863 vs->clientds.pf.rshift = red_shift;
1864 vs->clientds.pf.rmask = red_max << red_shift;
1865 vs->clientds.pf.gmax = green_max;
1866 vs->clientds.pf.gbits = hweight_long(green_max);
1867 vs->clientds.pf.gshift = green_shift;
1868 vs->clientds.pf.gmask = green_max << green_shift;
1869 vs->clientds.pf.bmax = blue_max;
1870 vs->clientds.pf.bbits = hweight_long(blue_max);
1871 vs->clientds.pf.bshift = blue_shift;
1872 vs->clientds.pf.bmask = blue_max << blue_shift;
1873 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1874 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1875 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1876 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1878 set_pixel_conversion(vs);
1880 vga_hw_invalidate();
1884 static void pixel_format_message (VncState *vs) {
1885 char pad[3] = { 0, 0, 0 };
1887 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1888 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1890 #ifdef HOST_WORDS_BIGENDIAN
1891 vnc_write_u8(vs, 1); /* big-endian-flag */
1893 vnc_write_u8(vs, 0); /* big-endian-flag */
1895 vnc_write_u8(vs, 1); /* true-color-flag */
1896 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1897 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1898 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1899 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1900 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1901 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1903 vnc_hextile_set_pixel_conversion(vs, 0);
1905 vs->clientds = *(vs->ds->surface);
1906 vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1907 vs->write_pixels = vnc_write_pixels_copy;
1909 vnc_write(vs, pad, 3); /* padding */
1912 static void vnc_dpy_setdata(DisplayState *ds)
1914 /* We don't have to do anything */
1917 static void vnc_colordepth(VncState *vs)
1919 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1920 /* Sending a WMVi message to notify the client*/
1921 vnc_lock_output(vs);
1922 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1923 vnc_write_u8(vs, 0);
1924 vnc_write_u16(vs, 1); /* number of rects */
1925 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1926 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1927 pixel_format_message(vs);
1928 vnc_unlock_output(vs);
1931 set_pixel_conversion(vs);
1935 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1939 VncDisplay *vd = vs->vd;
1942 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1943 if (!qemu_timer_expired(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval))
1944 qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval);
1948 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
1952 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1953 read_u8(data, 6), read_u8(data, 7),
1954 read_u16(data, 8), read_u16(data, 10),
1955 read_u16(data, 12), read_u8(data, 14),
1956 read_u8(data, 15), read_u8(data, 16));
1958 case VNC_MSG_CLIENT_SET_ENCODINGS:
1963 limit = read_u16(data, 2);
1965 return 4 + (limit * 4);
1967 limit = read_u16(data, 2);
1969 for (i = 0; i < limit; i++) {
1970 int32_t val = read_s32(data, 4 + (i * 4));
1971 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1974 set_encodings(vs, (int32_t *)(data + 4), limit);
1976 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
1980 framebuffer_update_request(vs,
1981 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1982 read_u16(data, 6), read_u16(data, 8));
1984 case VNC_MSG_CLIENT_KEY_EVENT:
1988 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1990 case VNC_MSG_CLIENT_POINTER_EVENT:
1994 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1996 case VNC_MSG_CLIENT_CUT_TEXT:
2001 uint32_t dlen = read_u32(data, 4);
2006 client_cut_text(vs, read_u32(data, 4), data + 8);
2008 case VNC_MSG_CLIENT_QEMU:
2012 switch (read_u8(data, 1)) {
2013 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2017 ext_key_event(vs, read_u16(data, 2),
2018 read_u32(data, 4), read_u32(data, 8));
2020 case VNC_MSG_CLIENT_QEMU_AUDIO:
2024 switch (read_u16 (data, 2)) {
2025 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2028 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2031 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2034 switch (read_u8(data, 4)) {
2035 case 0: vs->as.fmt = AUD_FMT_U8; break;
2036 case 1: vs->as.fmt = AUD_FMT_S8; break;
2037 case 2: vs->as.fmt = AUD_FMT_U16; break;
2038 case 3: vs->as.fmt = AUD_FMT_S16; break;
2039 case 4: vs->as.fmt = AUD_FMT_U32; break;
2040 case 5: vs->as.fmt = AUD_FMT_S32; break;
2042 printf("Invalid audio format %d\n", read_u8(data, 4));
2043 vnc_client_error(vs);
2046 vs->as.nchannels = read_u8(data, 5);
2047 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2048 printf("Invalid audio channel coount %d\n",
2050 vnc_client_error(vs);
2053 vs->as.freq = read_u32(data, 6);
2056 printf ("Invalid audio message %d\n", read_u8(data, 4));
2057 vnc_client_error(vs);
2063 printf("Msg: %d\n", read_u16(data, 0));
2064 vnc_client_error(vs);
2069 printf("Msg: %d\n", data[0]);
2070 vnc_client_error(vs);
2074 vnc_read_when(vs, protocol_client_msg, 1);
2078 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2084 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2085 switch (vs->vd->share_policy) {
2086 case VNC_SHARE_POLICY_IGNORE:
2088 * Ignore the shared flag. Nothing to do here.
2090 * Doesn't conform to the rfb spec but is traditional qemu
2091 * behavior, thus left here as option for compatibility
2095 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2097 * Policy: Allow clients ask for exclusive access.
2099 * Implementation: When a client asks for exclusive access,
2100 * disconnect all others. Shared connects are allowed as long
2101 * as no exclusive connection exists.
2103 * This is how the rfb spec suggests to handle the shared flag.
2105 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2107 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2111 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2112 client->share_mode != VNC_SHARE_MODE_SHARED) {
2115 vnc_disconnect_start(client);
2118 if (mode == VNC_SHARE_MODE_SHARED) {
2119 if (vs->vd->num_exclusive > 0) {
2120 vnc_disconnect_start(vs);
2125 case VNC_SHARE_POLICY_FORCE_SHARED:
2127 * Policy: Shared connects only.
2128 * Implementation: Disallow clients asking for exclusive access.
2130 * Useful for shared desktop sessions where you don't want
2131 * someone forgetting to say -shared when running the vnc
2132 * client disconnect everybody else.
2134 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2135 vnc_disconnect_start(vs);
2140 vnc_set_share_mode(vs, mode);
2142 vs->client_width = ds_get_width(vs->ds);
2143 vs->client_height = ds_get_height(vs->ds);
2144 vnc_write_u16(vs, vs->client_width);
2145 vnc_write_u16(vs, vs->client_height);
2147 pixel_format_message(vs);
2150 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2152 size = snprintf(buf, sizeof(buf), "QEMU");
2154 vnc_write_u32(vs, size);
2155 vnc_write(vs, buf, size);
2158 vnc_client_cache_auth(vs);
2159 vnc_qmp_event(vs, QEVENT_VNC_INITIALIZED);
2161 vnc_read_when(vs, protocol_client_msg, 1);
2166 void start_client_init(VncState *vs)
2168 vnc_read_when(vs, protocol_client_init, 1);
2171 static void make_challenge(VncState *vs)
2175 srand(time(NULL)+getpid()+getpid()*987654+rand());
2177 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2178 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2181 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2183 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2185 unsigned char key[8];
2186 time_t now = time(NULL);
2188 if (!vs->vd->password) {
2189 VNC_DEBUG("No password configured on server");
2192 if (vs->vd->expires < now) {
2193 VNC_DEBUG("Password is expired");
2197 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2199 /* Calculate the expected challenge response */
2200 pwlen = strlen(vs->vd->password);
2201 for (i=0; i<sizeof(key); i++)
2202 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2204 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2205 des(response+j, response+j);
2207 /* Compare expected vs actual challenge response */
2208 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2209 VNC_DEBUG("Client challenge response did not match\n");
2212 VNC_DEBUG("Accepting VNC challenge response\n");
2213 vnc_write_u32(vs, 0); /* Accept auth */
2216 start_client_init(vs);
2221 vnc_write_u32(vs, 1); /* Reject auth */
2222 if (vs->minor >= 8) {
2223 static const char err[] = "Authentication failed";
2224 vnc_write_u32(vs, sizeof(err));
2225 vnc_write(vs, err, sizeof(err));
2228 vnc_client_error(vs);
2232 void start_auth_vnc(VncState *vs)
2235 /* Send client a 'random' challenge */
2236 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2239 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2243 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2245 /* We only advertise 1 auth scheme at a time, so client
2246 * must pick the one we sent. Verify this */
2247 if (data[0] != vs->auth) { /* Reject auth */
2248 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2249 vnc_write_u32(vs, 1);
2250 if (vs->minor >= 8) {
2251 static const char err[] = "Authentication failed";
2252 vnc_write_u32(vs, sizeof(err));
2253 vnc_write(vs, err, sizeof(err));
2255 vnc_client_error(vs);
2256 } else { /* Accept requested auth */
2257 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2260 VNC_DEBUG("Accept auth none\n");
2261 if (vs->minor >= 8) {
2262 vnc_write_u32(vs, 0); /* Accept auth completion */
2265 start_client_init(vs);
2269 VNC_DEBUG("Start VNC auth\n");
2273 #ifdef CONFIG_VNC_TLS
2274 case VNC_AUTH_VENCRYPT:
2275 VNC_DEBUG("Accept VeNCrypt auth\n");
2276 start_auth_vencrypt(vs);
2278 #endif /* CONFIG_VNC_TLS */
2280 #ifdef CONFIG_VNC_SASL
2282 VNC_DEBUG("Accept SASL auth\n");
2283 start_auth_sasl(vs);
2285 #endif /* CONFIG_VNC_SASL */
2287 default: /* Should not be possible, but just in case */
2288 VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2289 vnc_write_u8(vs, 1);
2290 if (vs->minor >= 8) {
2291 static const char err[] = "Authentication failed";
2292 vnc_write_u32(vs, sizeof(err));
2293 vnc_write(vs, err, sizeof(err));
2295 vnc_client_error(vs);
2301 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2305 memcpy(local, version, 12);
2308 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2309 VNC_DEBUG("Malformed protocol version %s\n", local);
2310 vnc_client_error(vs);
2313 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2314 if (vs->major != 3 ||
2320 VNC_DEBUG("Unsupported client version\n");
2321 vnc_write_u32(vs, VNC_AUTH_INVALID);
2323 vnc_client_error(vs);
2326 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2327 * as equivalent to v3.3 by servers
2329 if (vs->minor == 4 || vs->minor == 5)
2332 if (vs->minor == 3) {
2333 if (vs->auth == VNC_AUTH_NONE) {
2334 VNC_DEBUG("Tell client auth none\n");
2335 vnc_write_u32(vs, vs->auth);
2337 start_client_init(vs);
2338 } else if (vs->auth == VNC_AUTH_VNC) {
2339 VNC_DEBUG("Tell client VNC auth\n");
2340 vnc_write_u32(vs, vs->auth);
2344 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2345 vnc_write_u32(vs, VNC_AUTH_INVALID);
2347 vnc_client_error(vs);
2350 VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2351 vnc_write_u8(vs, 1); /* num auth */
2352 vnc_write_u8(vs, vs->auth);
2353 vnc_read_when(vs, protocol_client_auth, 1);
2360 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2362 struct VncSurface *vs = &vd->guest;
2364 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2367 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2371 w = (x + w) / VNC_STAT_RECT;
2372 h = (y + h) / VNC_STAT_RECT;
2376 for (j = y; j <= h; j++) {
2377 for (i = x; i <= w; i++) {
2378 vs->lossy_rect[j][i] = 1;
2383 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2386 int sty = y / VNC_STAT_RECT;
2387 int stx = x / VNC_STAT_RECT;
2390 y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2391 x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2393 QTAILQ_FOREACH(vs, &vd->clients, next) {
2396 /* kernel send buffers are full -> refresh later */
2397 if (vs->output.offset) {
2401 if (!vs->lossy_rect[sty][stx]) {
2405 vs->lossy_rect[sty][stx] = 0;
2406 for (j = 0; j < VNC_STAT_RECT; ++j) {
2407 bitmap_set(vs->dirty[y + j], x / 16, VNC_STAT_RECT / 16);
2415 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2421 for (y = 0; y < vd->guest.ds->height; y += VNC_STAT_RECT) {
2422 for (x = 0; x < vd->guest.ds->width; x += VNC_STAT_RECT) {
2423 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2425 rect->updated = false;
2429 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2431 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2434 vd->guest.last_freq_check = *tv;
2436 for (y = 0; y < vd->guest.ds->height; y += VNC_STAT_RECT) {
2437 for (x = 0; x < vd->guest.ds->width; x += VNC_STAT_RECT) {
2438 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2439 int count = ARRAY_SIZE(rect->times);
2440 struct timeval min, max;
2442 if (!timerisset(&rect->times[count - 1])) {
2446 max = rect->times[(rect->idx + count - 1) % count];
2447 qemu_timersub(tv, &max, &res);
2449 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2451 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2452 memset(rect->times, 0, sizeof (rect->times));
2456 min = rect->times[rect->idx];
2457 max = rect->times[(rect->idx + count - 1) % count];
2458 qemu_timersub(&max, &min, &res);
2460 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2461 rect->freq /= count;
2462 rect->freq = 1. / rect->freq;
2468 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2474 x = (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2475 y = (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2477 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2478 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2479 total += vnc_stat_rect(vs->vd, i, j)->freq;
2491 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2495 rect = vnc_stat_rect(vd, x, y);
2496 if (rect->updated) {
2499 rect->times[rect->idx] = *tv;
2500 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2501 rect->updated = true;
2504 static int vnc_refresh_server_surface(VncDisplay *vd)
2508 uint8_t *server_row;
2513 struct timeval tv = { 0, 0 };
2515 if (!vd->non_adaptive) {
2516 gettimeofday(&tv, NULL);
2517 has_dirty = vnc_update_stats(vd, &tv);
2521 * Walk through the guest dirty map.
2522 * Check and copy modified bits from guest to server surface.
2523 * Update server dirty map.
2525 cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2526 guest_row = vd->guest.ds->data;
2527 server_row = vd->server->data;
2528 for (y = 0; y < vd->guest.ds->height; y++) {
2529 if (!bitmap_empty(vd->guest.dirty[y], VNC_DIRTY_BITS)) {
2532 uint8_t *server_ptr;
2534 guest_ptr = guest_row;
2535 server_ptr = server_row;
2537 for (x = 0; x + 15 < vd->guest.ds->width;
2538 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2539 if (!test_and_clear_bit((x / 16), vd->guest.dirty[y]))
2541 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2543 memcpy(server_ptr, guest_ptr, cmp_bytes);
2544 if (!vd->non_adaptive)
2545 vnc_rect_updated(vd, x, y, &tv);
2546 QTAILQ_FOREACH(vs, &vd->clients, next) {
2547 set_bit((x / 16), vs->dirty[y]);
2552 guest_row += ds_get_linesize(vd->ds);
2553 server_row += ds_get_linesize(vd->ds);
2558 static void vnc_refresh(void *opaque)
2560 VncDisplay *vd = opaque;
2562 int has_dirty, rects = 0;
2566 if (vnc_trylock_display(vd)) {
2567 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2568 qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) +
2569 vd->timer_interval);
2573 has_dirty = vnc_refresh_server_surface(vd);
2574 vnc_unlock_display(vd);
2576 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2577 rects += vnc_update_client(vs, has_dirty);
2578 /* vs might be free()ed here */
2581 /* vd->timer could be NULL now if the last client disconnected,
2582 * in this case don't update the timer */
2583 if (vd->timer == NULL)
2586 if (has_dirty && rects) {
2587 vd->timer_interval /= 2;
2588 if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2589 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2591 vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2592 if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2593 vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2595 qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval);
2598 static void vnc_init_timer(VncDisplay *vd)
2600 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2601 if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {
2602 vd->timer = qemu_new_timer_ms(rt_clock, vnc_refresh, vd);
2603 vnc_dpy_resize(vd->ds);
2608 static void vnc_remove_timer(VncDisplay *vd)
2610 if (vd->timer != NULL && QTAILQ_EMPTY(&vd->clients)) {
2611 qemu_del_timer(vd->timer);
2612 qemu_free_timer(vd->timer);
2617 static void vnc_connect(VncDisplay *vd, int csock, int skipauth)
2619 VncState *vs = g_malloc0(sizeof(VncState));
2625 vs->auth = VNC_AUTH_NONE;
2626 #ifdef CONFIG_VNC_TLS
2627 vs->subauth = VNC_AUTH_INVALID;
2630 vs->auth = vd->auth;
2631 #ifdef CONFIG_VNC_TLS
2632 vs->subauth = vd->subauth;
2636 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
2637 for (i = 0; i < VNC_STAT_ROWS; ++i) {
2638 vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
2641 VNC_DEBUG("New client on socket %d\n", csock);
2643 socket_set_nonblock(vs->csock);
2644 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2646 vnc_client_cache_addr(vs);
2647 vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
2648 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
2655 vs->as.freq = 44100;
2656 vs->as.nchannels = 2;
2657 vs->as.fmt = AUD_FMT_S16;
2658 vs->as.endianness = 0;
2660 #ifdef CONFIG_VNC_THREAD
2661 qemu_mutex_init(&vs->output_mutex);
2664 QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2668 vnc_write(vs, "RFB 003.008\n", 12);
2670 vnc_read_when(vs, protocol_version, 12);
2672 if (vs->vd->lock_key_sync)
2673 vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2675 vs->mouse_mode_notifier.notify = check_pointer_type_change;
2676 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2680 /* vs might be free()ed here */
2683 static void vnc_listen_read(void *opaque)
2685 VncDisplay *vs = opaque;
2686 struct sockaddr_in addr;
2687 socklen_t addrlen = sizeof(addr);
2692 int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2694 vnc_connect(vs, csock, 0);
2698 void vnc_display_init(DisplayState *ds)
2700 VncDisplay *vs = g_malloc0(sizeof(*vs));
2702 dcl = g_malloc0(sizeof(DisplayChangeListener));
2711 QTAILQ_INIT(&vs->clients);
2712 vs->expires = TIME_MAX;
2714 if (keyboard_layout)
2715 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2717 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2719 if (!vs->kbd_layout)
2722 #ifdef CONFIG_VNC_THREAD
2723 qemu_mutex_init(&vs->mutex);
2724 vnc_start_worker_thread();
2727 dcl->dpy_copy = vnc_dpy_copy;
2728 dcl->dpy_update = vnc_dpy_update;
2729 dcl->dpy_resize = vnc_dpy_resize;
2730 dcl->dpy_setdata = vnc_dpy_setdata;
2731 register_displaychangelistener(ds, dcl);
2732 ds->mouse_set = vnc_mouse_set;
2733 ds->cursor_define = vnc_dpy_cursor_define;
2737 void vnc_display_close(DisplayState *ds)
2739 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2744 g_free(vs->display);
2747 if (vs->lsock != -1) {
2748 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2752 vs->auth = VNC_AUTH_INVALID;
2753 #ifdef CONFIG_VNC_TLS
2754 vs->subauth = VNC_AUTH_INVALID;
2755 vs->tls.x509verify = 0;
2759 int vnc_display_disable_login(DisplayState *ds)
2761 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2768 g_free(vs->password);
2771 vs->password = NULL;
2772 vs->auth = VNC_AUTH_VNC;
2777 int vnc_display_password(DisplayState *ds, const char *password)
2779 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2786 /* This is not the intention of this interface but err on the side
2788 return vnc_display_disable_login(ds);
2792 g_free(vs->password);
2793 vs->password = NULL;
2795 vs->password = g_strdup(password);
2796 vs->auth = VNC_AUTH_VNC;
2801 int vnc_display_pw_expire(DisplayState *ds, time_t expires)
2803 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2805 vs->expires = expires;
2809 char *vnc_display_local_addr(DisplayState *ds)
2811 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2813 return vnc_socket_local_addr("%s:%s", vs->lsock);
2816 int vnc_display_open(DisplayState *ds, const char *display)
2818 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2819 const char *options;
2822 #ifdef CONFIG_VNC_TLS
2823 int tls = 0, x509 = 0;
2825 #ifdef CONFIG_VNC_SASL
2829 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
2832 int lock_key_sync = 1;
2836 vnc_display_close(ds);
2837 if (strcmp(display, "none") == 0)
2840 if (!(vs->display = strdup(display)))
2842 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
2845 while ((options = strchr(options, ','))) {
2847 if (strncmp(options, "password", 8) == 0) {
2848 password = 1; /* Require password auth */
2849 } else if (strncmp(options, "reverse", 7) == 0) {
2851 } else if (strncmp(options, "no-lock-key-sync", 16) == 0) {
2853 #ifdef CONFIG_VNC_SASL
2854 } else if (strncmp(options, "sasl", 4) == 0) {
2855 sasl = 1; /* Require SASL auth */
2857 #ifdef CONFIG_VNC_TLS
2858 } else if (strncmp(options, "tls", 3) == 0) {
2859 tls = 1; /* Require TLS */
2860 } else if (strncmp(options, "x509", 4) == 0) {
2862 x509 = 1; /* Require x509 certificates */
2863 if (strncmp(options, "x509verify", 10) == 0)
2864 vs->tls.x509verify = 1; /* ...and verify client certs */
2866 /* Now check for 'x509=/some/path' postfix
2867 * and use that to setup x509 certificate/key paths */
2868 start = strchr(options, '=');
2869 end = strchr(options, ',');
2870 if (start && (!end || (start < end))) {
2871 int len = end ? end-(start+1) : strlen(start+1);
2872 char *path = g_strndup(start + 1, len);
2874 VNC_DEBUG("Trying certificate path '%s'\n", path);
2875 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2876 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2878 g_free(vs->display);
2884 fprintf(stderr, "No certificate path provided\n");
2885 g_free(vs->display);
2890 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
2891 } else if (strncmp(options, "acl", 3) == 0) {
2894 } else if (strncmp(options, "lossy", 5) == 0) {
2896 } else if (strncmp(options, "non-adapative", 13) == 0) {
2897 vs->non_adaptive = true;
2898 } else if (strncmp(options, "share=", 6) == 0) {
2899 if (strncmp(options+6, "ignore", 6) == 0) {
2900 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
2901 } else if (strncmp(options+6, "allow-exclusive", 15) == 0) {
2902 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
2903 } else if (strncmp(options+6, "force-shared", 12) == 0) {
2904 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
2906 fprintf(stderr, "unknown vnc share= option\n");
2907 g_free(vs->display);
2914 #ifdef CONFIG_VNC_TLS
2915 if (acl && x509 && vs->tls.x509verify) {
2916 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2917 fprintf(stderr, "Failed to create x509 dname ACL\n");
2922 #ifdef CONFIG_VNC_SASL
2924 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2925 fprintf(stderr, "Failed to create username ACL\n");
2932 * Combinations we support here:
2934 * - no-auth (clear text, no auth)
2935 * - password (clear text, weak auth)
2936 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
2937 * - tls (encrypt, weak anonymous creds, no auth)
2938 * - tls + password (encrypt, weak anonymous creds, weak auth)
2939 * - tls + sasl (encrypt, weak anonymous creds, good auth)
2940 * - tls + x509 (encrypt, good x509 creds, no auth)
2941 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
2942 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
2944 * NB1. TLS is a stackable auth scheme.
2945 * NB2. the x509 schemes have option to validate a client cert dname
2948 #ifdef CONFIG_VNC_TLS
2950 vs->auth = VNC_AUTH_VENCRYPT;
2952 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2953 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2955 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2956 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2959 #endif /* CONFIG_VNC_TLS */
2960 VNC_DEBUG("Initializing VNC server with password auth\n");
2961 vs->auth = VNC_AUTH_VNC;
2962 #ifdef CONFIG_VNC_TLS
2963 vs->subauth = VNC_AUTH_INVALID;
2965 #endif /* CONFIG_VNC_TLS */
2966 #ifdef CONFIG_VNC_SASL
2968 #ifdef CONFIG_VNC_TLS
2970 vs->auth = VNC_AUTH_VENCRYPT;
2972 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2973 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2975 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2976 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2979 #endif /* CONFIG_VNC_TLS */
2980 VNC_DEBUG("Initializing VNC server with SASL auth\n");
2981 vs->auth = VNC_AUTH_SASL;
2982 #ifdef CONFIG_VNC_TLS
2983 vs->subauth = VNC_AUTH_INVALID;
2985 #endif /* CONFIG_VNC_TLS */
2986 #endif /* CONFIG_VNC_SASL */
2988 #ifdef CONFIG_VNC_TLS
2990 vs->auth = VNC_AUTH_VENCRYPT;
2992 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2993 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2995 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2996 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3000 VNC_DEBUG("Initializing VNC server with no auth\n");
3001 vs->auth = VNC_AUTH_NONE;
3002 #ifdef CONFIG_VNC_TLS
3003 vs->subauth = VNC_AUTH_INVALID;
3008 #ifdef CONFIG_VNC_SASL
3009 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3010 fprintf(stderr, "Failed to initialize SASL auth %s",
3011 sasl_errstring(saslErr, NULL, NULL));
3012 g_free(vs->display);
3017 vs->lock_key_sync = lock_key_sync;
3020 /* connect to viewer */
3021 if (strncmp(display, "unix:", 5) == 0)
3022 vs->lsock = unix_connect(display+5);
3024 vs->lsock = inet_connect(display, SOCK_STREAM);
3025 if (-1 == vs->lsock) {
3026 g_free(vs->display);
3030 int csock = vs->lsock;
3032 vnc_connect(vs, csock, 0);
3037 /* listen for connects */
3039 dpy = g_malloc(256);
3040 if (strncmp(display, "unix:", 5) == 0) {
3041 pstrcpy(dpy, 256, "unix:");
3042 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
3044 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
3046 if (-1 == vs->lsock) {
3050 g_free(vs->display);
3054 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
3057 void vnc_display_add_client(DisplayState *ds, int csock, int skipauth)
3059 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
3061 return vnc_connect(vs, csock, skipauth);