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
29 #include "qemu_socket.h"
30 #include "qemu-timer.h"
32 #define VNC_REFRESH_INTERVAL (1000 / 30)
34 #include "vnc_keysym.h"
37 // #define _VNC_DEBUG 1
40 #define VNC_DEBUG(fmt, ...) do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
42 #if defined(CONFIG_VNC_TLS) && _VNC_DEBUG >= 2
43 /* Very verbose, so only enabled for _VNC_DEBUG >= 2 */
44 static void vnc_debug_gnutls_log(int level, const char* str) {
45 VNC_DEBUG("%d %s", level, str);
47 #endif /* CONFIG_VNC_TLS && _VNC_DEBUG */
49 #define VNC_DEBUG(fmt, ...) do { } while (0)
52 #define count_bits(c, v) { \
53 for (c = 0; v; v >>= 1) \
60 static VncDisplay *vnc_display; /* needed for info vnc */
61 static DisplayChangeListener *dcl;
63 static char *addr_to_string(const char *format,
64 struct sockaddr_storage *sa,
67 char host[NI_MAXHOST];
68 char serv[NI_MAXSERV];
71 if ((err = getnameinfo((struct sockaddr *)sa, salen,
74 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
75 VNC_DEBUG("Cannot resolve address %d: %s\n",
76 err, gai_strerror(err));
80 if (asprintf(&addr, format, host, serv) < 0)
86 static char *vnc_socket_local_addr(const char *format, int fd) {
87 struct sockaddr_storage sa;
91 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
94 return addr_to_string(format, &sa, salen);
97 static char *vnc_socket_remote_addr(const char *format, int fd) {
98 struct sockaddr_storage sa;
102 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
105 return addr_to_string(format, &sa, salen);
108 static const char *vnc_auth_name(VncDisplay *vd) {
110 case VNC_AUTH_INVALID:
126 case VNC_AUTH_VENCRYPT:
127 #ifdef CONFIG_VNC_TLS
128 switch (vd->subauth) {
129 case VNC_AUTH_VENCRYPT_PLAIN:
130 return "vencrypt+plain";
131 case VNC_AUTH_VENCRYPT_TLSNONE:
132 return "vencrypt+tls+none";
133 case VNC_AUTH_VENCRYPT_TLSVNC:
134 return "vencrypt+tls+vnc";
135 case VNC_AUTH_VENCRYPT_TLSPLAIN:
136 return "vencrypt+tls+plain";
137 case VNC_AUTH_VENCRYPT_X509NONE:
138 return "vencrypt+x509+none";
139 case VNC_AUTH_VENCRYPT_X509VNC:
140 return "vencrypt+x509+vnc";
141 case VNC_AUTH_VENCRYPT_X509PLAIN:
142 return "vencrypt+x509+plain";
153 #define VNC_SOCKET_FORMAT_PRETTY "local %s:%s"
155 static void do_info_vnc_client(Monitor *mon, VncState *client)
158 vnc_socket_remote_addr(" address: %s:%s\n",
163 monitor_printf(mon, "Client:\n");
164 monitor_printf(mon, "%s", clientAddr);
168 void do_info_vnc(Monitor *mon)
170 if (vnc_display == NULL || vnc_display->display == NULL) {
171 monitor_printf(mon, "Server: disabled\n");
173 char *serverAddr = vnc_socket_local_addr(" address: %s:%s\n",
179 monitor_printf(mon, "Server:\n");
180 monitor_printf(mon, "%s", serverAddr);
182 monitor_printf(mon, " auth: %s\n", vnc_auth_name(vnc_display));
184 if (vnc_display->clients) {
185 VncState *client = vnc_display->clients;
187 do_info_vnc_client(mon, client);
188 client = client->next;
191 monitor_printf(mon, "Client: none\n");
196 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
197 return (vs->features & (1 << feature));
201 1) Get the queue working for IO.
202 2) there is some weirdness when using the -S option (the screen is grey
203 and not totally invalidated
204 3) resolutions > 1024
207 static void vnc_write(VncState *vs, const void *data, size_t len);
208 static void vnc_write_u32(VncState *vs, uint32_t value);
209 static void vnc_write_s32(VncState *vs, int32_t value);
210 static void vnc_write_u16(VncState *vs, uint16_t value);
211 static void vnc_write_u8(VncState *vs, uint8_t value);
212 static void vnc_flush(VncState *vs);
213 static void vnc_update_client(void *opaque);
214 static void vnc_client_read(void *opaque);
216 static void vnc_colordepth(VncState *vs);
218 static inline void vnc_set_bit(uint32_t *d, int k)
220 d[k >> 5] |= 1 << (k & 0x1f);
223 static inline void vnc_clear_bit(uint32_t *d, int k)
225 d[k >> 5] &= ~(1 << (k & 0x1f));
228 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
238 d[j++] = (1 << n) - 1;
243 static inline int vnc_get_bit(const uint32_t *d, int k)
245 return (d[k >> 5] >> (k & 0x1f)) & 1;
248 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
252 for(i = 0; i < nb_words; i++) {
253 if ((d1[i] & d2[i]) != 0)
259 static void vnc_update(VncState *vs, int x, int y, int w, int h)
265 /* round x down to ensure the loop only spans one 16-pixel block per,
266 iteration. otherwise, if (x % 16) != 0, the last iteration may span
267 two 16-pixel blocks but we only mark the first as dirty
272 x = MIN(x, vs->serverds.width);
273 y = MIN(y, vs->serverds.height);
274 w = MIN(x + w, vs->serverds.width) - x;
275 h = MIN(h, vs->serverds.height);
278 for (i = 0; i < w; i += 16)
279 vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
282 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
284 VncDisplay *vd = ds->opaque;
285 VncState *vs = vd->clients;
287 vnc_update(vs, x, y, w, h);
292 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
295 vnc_write_u16(vs, x);
296 vnc_write_u16(vs, y);
297 vnc_write_u16(vs, w);
298 vnc_write_u16(vs, h);
300 vnc_write_s32(vs, encoding);
303 static void buffer_reserve(Buffer *buffer, size_t len)
305 if ((buffer->capacity - buffer->offset) < len) {
306 buffer->capacity += (len + 1024);
307 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
308 if (buffer->buffer == NULL) {
309 fprintf(stderr, "vnc: out of memory\n");
315 static int buffer_empty(Buffer *buffer)
317 return buffer->offset == 0;
320 static uint8_t *buffer_end(Buffer *buffer)
322 return buffer->buffer + buffer->offset;
325 static void buffer_reset(Buffer *buffer)
330 static void buffer_append(Buffer *buffer, const void *data, size_t len)
332 memcpy(buffer->buffer + buffer->offset, data, len);
333 buffer->offset += len;
336 static void vnc_resize(VncState *vs)
338 DisplayState *ds = vs->ds;
342 vs->old_data = qemu_realloc(vs->old_data, ds_get_linesize(ds) * ds_get_height(ds));
344 if (vs->old_data == NULL) {
345 fprintf(stderr, "vnc: memory allocation failed\n");
349 if (ds_get_bytes_per_pixel(ds) != vs->serverds.pf.bytes_per_pixel)
350 console_color_init(ds);
352 size_changed = ds_get_width(ds) != vs->serverds.width ||
353 ds_get_height(ds) != vs->serverds.height;
354 vs->serverds = *(ds->surface);
356 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
357 vnc_write_u8(vs, 0); /* msg id */
359 vnc_write_u16(vs, 1); /* number of rects */
360 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
361 VNC_ENCODING_DESKTOPRESIZE);
366 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
367 memset(vs->old_data, 42, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
370 static void vnc_dpy_resize(DisplayState *ds)
372 VncDisplay *vd = ds->opaque;
373 VncState *vs = vd->clients;
381 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
383 vnc_write(vs, pixels, size);
386 /* slowest but generic code. */
387 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
391 r = ((((v & vs->serverds.pf.rmask) >> vs->serverds.pf.rshift) << vs->clientds.pf.rbits) >>
392 vs->serverds.pf.rbits);
393 g = ((((v & vs->serverds.pf.gmask) >> vs->serverds.pf.gshift) << vs->clientds.pf.gbits) >>
394 vs->serverds.pf.gbits);
395 b = ((((v & vs->serverds.pf.bmask) >> vs->serverds.pf.bshift) << vs->clientds.pf.bbits) >>
396 vs->serverds.pf.bbits);
397 v = (r << vs->clientds.pf.rshift) |
398 (g << vs->clientds.pf.gshift) |
399 (b << vs->clientds.pf.bshift);
400 switch(vs->clientds.pf.bytes_per_pixel) {
405 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
415 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
430 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
434 if (vs->serverds.pf.bytes_per_pixel == 4) {
435 uint32_t *pixels = pixels1;
438 for(i = 0; i < n; i++) {
439 vnc_convert_pixel(vs, buf, pixels[i]);
440 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
442 } else if (vs->serverds.pf.bytes_per_pixel == 2) {
443 uint16_t *pixels = pixels1;
446 for(i = 0; i < n; i++) {
447 vnc_convert_pixel(vs, buf, pixels[i]);
448 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
450 } else if (vs->serverds.pf.bytes_per_pixel == 1) {
451 uint8_t *pixels = pixels1;
454 for(i = 0; i < n; i++) {
455 vnc_convert_pixel(vs, buf, pixels[i]);
456 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
459 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
463 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
468 row = ds_get_data(vs->ds) + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
469 for (i = 0; i < h; i++) {
470 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
471 row += ds_get_linesize(vs->ds);
475 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
477 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
478 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
482 #include "vnchextile.h"
486 #include "vnchextile.h"
490 #include "vnchextile.h"
495 #include "vnchextile.h"
501 #include "vnchextile.h"
507 #include "vnchextile.h"
511 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
515 uint8_t *last_fg, *last_bg;
517 last_fg = (uint8_t *) qemu_malloc(vs->serverds.pf.bytes_per_pixel);
518 last_bg = (uint8_t *) qemu_malloc(vs->serverds.pf.bytes_per_pixel);
520 for (j = y; j < (y + h); j += 16) {
521 for (i = x; i < (x + w); i += 16) {
522 vs->send_hextile_tile(vs, i, j,
523 MIN(16, x + w - i), MIN(16, y + h - j),
524 last_bg, last_fg, &has_bg, &has_fg);
532 static void vnc_zlib_init(VncState *vs)
535 for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
536 vs->zlib_stream[i].opaque = NULL;
539 static void vnc_zlib_start(VncState *vs)
541 buffer_reset(&vs->zlib);
543 // make the output buffer be the zlib buffer, so we can compress it later
544 vs->zlib_tmp = vs->output;
545 vs->output = vs->zlib;
548 static int vnc_zlib_stop(VncState *vs, int stream_id)
550 z_streamp zstream = &vs->zlib_stream[stream_id];
553 // switch back to normal output/zlib buffers
554 vs->zlib = vs->output;
555 vs->output = vs->zlib_tmp;
557 // compress the zlib buffer
559 // initialize the stream
560 // XXX need one stream per session
561 if (zstream->opaque != vs) {
564 VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
565 VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
566 zstream->zalloc = Z_NULL;
567 zstream->zfree = Z_NULL;
569 err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
570 MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
573 fprintf(stderr, "VNC: error initializing zlib\n");
577 zstream->opaque = vs;
580 // XXX what to do if tight_compression changed in between?
582 // reserve memory in output buffer
583 buffer_reserve(&vs->output, vs->zlib.offset + 64);
586 zstream->next_in = vs->zlib.buffer;
587 zstream->avail_in = vs->zlib.offset;
588 zstream->next_out = vs->output.buffer + vs->output.offset;
589 zstream->avail_out = vs->output.capacity - vs->output.offset;
590 zstream->data_type = Z_BINARY;
591 previous_out = zstream->total_out;
594 if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
595 fprintf(stderr, "VNC: error during zlib compression\n");
599 vs->output.offset = vs->output.capacity - zstream->avail_out;
600 return zstream->total_out - previous_out;
603 static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
605 int old_offset, new_offset, bytes_written;
607 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
609 // remember where we put in the follow-up size
610 old_offset = vs->output.offset;
611 vnc_write_s32(vs, 0);
613 // compress the stream
615 send_framebuffer_update_raw(vs, x, y, w, h);
616 bytes_written = vnc_zlib_stop(vs, 0);
618 if (bytes_written == -1)
622 new_offset = vs->output.offset;
623 vs->output.offset = old_offset;
624 vnc_write_u32(vs, bytes_written);
625 vs->output.offset = new_offset;
628 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
630 switch(vs->vnc_encoding) {
631 case VNC_ENCODING_ZLIB:
632 send_framebuffer_update_zlib(vs, x, y, w, h);
634 case VNC_ENCODING_HEXTILE:
635 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
636 send_framebuffer_update_hextile(vs, x, y, w, h);
639 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
640 send_framebuffer_update_raw(vs, x, y, w, h);
645 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
647 vnc_update_client(vs);
649 vnc_write_u8(vs, 0); /* msg id */
651 vnc_write_u16(vs, 1); /* number of rects */
652 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
653 vnc_write_u16(vs, src_x);
654 vnc_write_u16(vs, src_y);
658 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
660 VncDisplay *vd = ds->opaque;
661 VncState *vs = vd->clients;
663 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
664 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
666 vnc_update(vs, dst_x, dst_y, w, h);
671 static int find_dirty_height(VncState *vs, int y, int last_x, int x)
675 for (h = 1; h < (vs->serverds.height - y); h++) {
677 if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
679 for (tmp_x = last_x; tmp_x < x; tmp_x++)
680 vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
686 static void vnc_update_client(void *opaque)
688 VncState *vs = opaque;
689 if (vs->need_update && vs->csock != -1) {
693 uint32_t width_mask[VNC_DIRTY_WORDS];
700 vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
702 /* Walk through the dirty map and eliminate tiles that
703 really aren't dirty */
704 row = ds_get_data(vs->ds);
705 old_row = vs->old_data;
707 for (y = 0; y < ds_get_height(vs->ds); y++) {
708 if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
714 old_ptr = (char*)old_row;
716 for (x = 0; x < ds_get_width(vs->ds); x += 16) {
717 if (memcmp(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds)) == 0) {
718 vnc_clear_bit(vs->dirty_row[y], (x / 16));
721 memcpy(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds));
724 ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
725 old_ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
729 row += ds_get_linesize(vs->ds);
730 old_row += ds_get_linesize(vs->ds);
733 if (!has_dirty && !vs->audio_cap) {
734 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
738 /* Count rectangles */
740 vnc_write_u8(vs, 0); /* msg id */
742 saved_offset = vs->output.offset;
743 vnc_write_u16(vs, 0);
745 for (y = 0; y < vs->serverds.height; y++) {
748 for (x = 0; x < vs->serverds.width / 16; x++) {
749 if (vnc_get_bit(vs->dirty_row[y], x)) {
753 vnc_clear_bit(vs->dirty_row[y], x);
756 int h = find_dirty_height(vs, y, last_x, x);
757 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
764 int h = find_dirty_height(vs, y, last_x, x);
765 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
769 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
770 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
775 if (vs->csock != -1) {
776 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
782 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
784 VncState *vs = opaque;
787 case AUD_CNOTIFY_DISABLE:
788 vnc_write_u8(vs, 255);
790 vnc_write_u16(vs, 0);
794 case AUD_CNOTIFY_ENABLE:
795 vnc_write_u8(vs, 255);
797 vnc_write_u16(vs, 1);
803 static void audio_capture_destroy(void *opaque)
807 static void audio_capture(void *opaque, void *buf, int size)
809 VncState *vs = opaque;
811 vnc_write_u8(vs, 255);
813 vnc_write_u16(vs, 2);
814 vnc_write_u32(vs, size);
815 vnc_write(vs, buf, size);
819 static void audio_add(VncState *vs)
821 Monitor *mon = cur_mon;
822 struct audio_capture_ops ops;
825 monitor_printf(mon, "audio already running\n");
829 ops.notify = audio_capture_notify;
830 ops.destroy = audio_capture_destroy;
831 ops.capture = audio_capture;
833 vs->audio_cap = AUD_add_capture(NULL, &vs->as, &ops, vs);
834 if (!vs->audio_cap) {
835 monitor_printf(mon, "Failed to add audio capture\n");
839 static void audio_del(VncState *vs)
842 AUD_del_capture(vs->audio_cap, vs);
843 vs->audio_cap = NULL;
847 static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
849 if (ret == 0 || ret == -1) {
851 switch (last_errno) {
863 VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
864 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
865 closesocket(vs->csock);
866 qemu_del_timer(vs->timer);
867 qemu_free_timer(vs->timer);
868 if (vs->input.buffer) qemu_free(vs->input.buffer);
869 if (vs->output.buffer) qemu_free(vs->output.buffer);
870 #ifdef CONFIG_VNC_TLS
871 if (vs->tls_session) {
872 gnutls_deinit(vs->tls_session);
873 vs->tls_session = NULL;
875 #endif /* CONFIG_VNC_TLS */
878 VncState *p, *parent = NULL;
879 for (p = vs->vd->clients; p != NULL; p = p->next) {
882 parent->next = p->next;
884 vs->vd->clients = p->next;
889 if (!vs->vd->clients)
892 qemu_free(vs->old_data);
900 static void vnc_client_error(VncState *vs)
902 vnc_client_io_error(vs, -1, EINVAL);
905 static void vnc_client_write(void *opaque)
908 VncState *vs = opaque;
910 #ifdef CONFIG_VNC_TLS
911 if (vs->tls_session) {
912 ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
914 if (ret == GNUTLS_E_AGAIN)
921 #endif /* CONFIG_VNC_TLS */
922 ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
923 ret = vnc_client_io_error(vs, ret, socket_error());
927 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
928 vs->output.offset -= ret;
930 if (vs->output.offset == 0) {
931 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
935 static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
937 vs->read_handler = func;
938 vs->read_handler_expect = expecting;
941 static void vnc_client_read(void *opaque)
943 VncState *vs = opaque;
946 buffer_reserve(&vs->input, 4096);
948 #ifdef CONFIG_VNC_TLS
949 if (vs->tls_session) {
950 ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
952 if (ret == GNUTLS_E_AGAIN)
959 #endif /* CONFIG_VNC_TLS */
960 ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
961 ret = vnc_client_io_error(vs, ret, socket_error());
965 vs->input.offset += ret;
967 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
968 size_t len = vs->read_handler_expect;
971 ret = vs->read_handler(vs, vs->input.buffer, len);
976 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
977 vs->input.offset -= len;
979 vs->read_handler_expect = ret;
984 static void vnc_write(VncState *vs, const void *data, size_t len)
986 buffer_reserve(&vs->output, len);
988 if (buffer_empty(&vs->output)) {
989 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
992 buffer_append(&vs->output, data, len);
995 static void vnc_write_s32(VncState *vs, int32_t value)
997 vnc_write_u32(vs, *(uint32_t *)&value);
1000 static void vnc_write_u32(VncState *vs, uint32_t value)
1004 buf[0] = (value >> 24) & 0xFF;
1005 buf[1] = (value >> 16) & 0xFF;
1006 buf[2] = (value >> 8) & 0xFF;
1007 buf[3] = value & 0xFF;
1009 vnc_write(vs, buf, 4);
1012 static void vnc_write_u16(VncState *vs, uint16_t value)
1016 buf[0] = (value >> 8) & 0xFF;
1017 buf[1] = value & 0xFF;
1019 vnc_write(vs, buf, 2);
1022 static void vnc_write_u8(VncState *vs, uint8_t value)
1024 vnc_write(vs, (char *)&value, 1);
1027 static void vnc_flush(VncState *vs)
1029 if (vs->output.offset)
1030 vnc_client_write(vs);
1033 static uint8_t read_u8(uint8_t *data, size_t offset)
1035 return data[offset];
1038 static uint16_t read_u16(uint8_t *data, size_t offset)
1040 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1043 static int32_t read_s32(uint8_t *data, size_t offset)
1045 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1046 (data[offset + 2] << 8) | data[offset + 3]);
1049 static uint32_t read_u32(uint8_t *data, size_t offset)
1051 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1052 (data[offset + 2] << 8) | data[offset + 3]);
1055 #ifdef CONFIG_VNC_TLS
1056 static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
1059 struct VncState *vs = (struct VncState *)transport;
1063 ret = send(vs->csock, data, len, 0);
1073 static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
1076 struct VncState *vs = (struct VncState *)transport;
1080 ret = recv(vs->csock, data, len, 0);
1088 #endif /* CONFIG_VNC_TLS */
1090 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1094 static void check_pointer_type_change(VncState *vs, int absolute)
1096 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1097 vnc_write_u8(vs, 0);
1098 vnc_write_u8(vs, 0);
1099 vnc_write_u16(vs, 1);
1100 vnc_framebuffer_update(vs, absolute, 0,
1101 ds_get_width(vs->ds), ds_get_height(vs->ds),
1102 VNC_ENCODING_POINTER_TYPE_CHANGE);
1105 vs->absolute = absolute;
1108 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1113 if (button_mask & 0x01)
1114 buttons |= MOUSE_EVENT_LBUTTON;
1115 if (button_mask & 0x02)
1116 buttons |= MOUSE_EVENT_MBUTTON;
1117 if (button_mask & 0x04)
1118 buttons |= MOUSE_EVENT_RBUTTON;
1119 if (button_mask & 0x08)
1121 if (button_mask & 0x10)
1125 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1126 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1128 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1132 kbd_mouse_event(x, y, dz, buttons);
1134 if (vs->last_x != -1)
1135 kbd_mouse_event(x - vs->last_x,
1142 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1145 static void reset_keys(VncState *vs)
1148 for(i = 0; i < 256; i++) {
1149 if (vs->modifiers_state[i]) {
1151 kbd_put_keycode(0xe0);
1152 kbd_put_keycode(i | 0x80);
1153 vs->modifiers_state[i] = 0;
1158 static void press_key(VncState *vs, int keysym)
1160 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1161 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
1164 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1166 /* QEMU console switch */
1168 case 0x2a: /* Left Shift */
1169 case 0x36: /* Right Shift */
1170 case 0x1d: /* Left CTRL */
1171 case 0x9d: /* Right CTRL */
1172 case 0x38: /* Left ALT */
1173 case 0xb8: /* Right ALT */
1175 vs->modifiers_state[keycode] = 1;
1177 vs->modifiers_state[keycode] = 0;
1179 case 0x02 ... 0x0a: /* '1' to '9' keys */
1180 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1181 /* Reset the modifiers sent to the current console */
1183 console_select(keycode - 0x02);
1187 case 0x3a: /* CapsLock */
1188 case 0x45: /* NumLock */
1190 vs->modifiers_state[keycode] ^= 1;
1194 if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1195 /* If the numlock state needs to change then simulate an additional
1196 keypress before sending this one. This will happen if the user
1197 toggles numlock away from the VNC window.
1199 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1200 if (!vs->modifiers_state[0x45]) {
1201 vs->modifiers_state[0x45] = 1;
1202 press_key(vs, 0xff7f);
1205 if (vs->modifiers_state[0x45]) {
1206 vs->modifiers_state[0x45] = 0;
1207 press_key(vs, 0xff7f);
1212 if (is_graphic_console()) {
1214 kbd_put_keycode(0xe0);
1216 kbd_put_keycode(keycode & 0x7f);
1218 kbd_put_keycode(keycode | 0x80);
1220 /* QEMU console emulation */
1223 case 0x2a: /* Left Shift */
1224 case 0x36: /* Right Shift */
1225 case 0x1d: /* Left CTRL */
1226 case 0x9d: /* Right CTRL */
1227 case 0x38: /* Left ALT */
1228 case 0xb8: /* Right ALT */
1231 kbd_put_keysym(QEMU_KEY_UP);
1234 kbd_put_keysym(QEMU_KEY_DOWN);
1237 kbd_put_keysym(QEMU_KEY_LEFT);
1240 kbd_put_keysym(QEMU_KEY_RIGHT);
1243 kbd_put_keysym(QEMU_KEY_DELETE);
1246 kbd_put_keysym(QEMU_KEY_HOME);
1249 kbd_put_keysym(QEMU_KEY_END);
1252 kbd_put_keysym(QEMU_KEY_PAGEUP);
1255 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1258 kbd_put_keysym(sym);
1265 static void key_event(VncState *vs, int down, uint32_t sym)
1269 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1270 sym = sym - 'A' + 'a';
1272 keycode = keysym2scancode(vs->vd->kbd_layout, sym & 0xFFFF);
1273 do_key_event(vs, down, keycode, sym);
1276 static void ext_key_event(VncState *vs, int down,
1277 uint32_t sym, uint16_t keycode)
1279 /* if the user specifies a keyboard layout, always use it */
1280 if (keyboard_layout)
1281 key_event(vs, down, sym);
1283 do_key_event(vs, down, keycode, sym);
1286 static void framebuffer_update_request(VncState *vs, int incremental,
1287 int x_position, int y_position,
1290 if (x_position > ds_get_width(vs->ds))
1291 x_position = ds_get_width(vs->ds);
1292 if (y_position > ds_get_height(vs->ds))
1293 y_position = ds_get_height(vs->ds);
1294 if (x_position + w >= ds_get_width(vs->ds))
1295 w = ds_get_width(vs->ds) - x_position;
1296 if (y_position + h >= ds_get_height(vs->ds))
1297 h = ds_get_height(vs->ds) - y_position;
1300 vs->need_update = 1;
1302 char *old_row = vs->old_data + y_position * ds_get_linesize(vs->ds);
1304 for (i = 0; i < h; i++) {
1305 vnc_set_bits(vs->dirty_row[y_position + i],
1306 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1307 memset(old_row, 42, ds_get_width(vs->ds) * ds_get_bytes_per_pixel(vs->ds));
1308 old_row += ds_get_linesize(vs->ds);
1313 static void send_ext_key_event_ack(VncState *vs)
1315 vnc_write_u8(vs, 0);
1316 vnc_write_u8(vs, 0);
1317 vnc_write_u16(vs, 1);
1318 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1319 VNC_ENCODING_EXT_KEY_EVENT);
1323 static void send_ext_audio_ack(VncState *vs)
1325 vnc_write_u8(vs, 0);
1326 vnc_write_u8(vs, 0);
1327 vnc_write_u16(vs, 1);
1328 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1329 VNC_ENCODING_AUDIO);
1333 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1336 unsigned int enc = 0;
1340 vs->vnc_encoding = 0;
1341 vs->tight_compression = 9;
1342 vs->tight_quality = 9;
1345 for (i = n_encodings - 1; i >= 0; i--) {
1348 case VNC_ENCODING_RAW:
1349 vs->vnc_encoding = enc;
1351 case VNC_ENCODING_COPYRECT:
1352 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1354 case VNC_ENCODING_HEXTILE:
1355 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1356 vs->vnc_encoding = enc;
1358 case VNC_ENCODING_ZLIB:
1359 vs->features |= VNC_FEATURE_ZLIB_MASK;
1360 vs->vnc_encoding = enc;
1362 case VNC_ENCODING_DESKTOPRESIZE:
1363 vs->features |= VNC_FEATURE_RESIZE_MASK;
1365 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1366 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1368 case VNC_ENCODING_EXT_KEY_EVENT:
1369 send_ext_key_event_ack(vs);
1371 case VNC_ENCODING_AUDIO:
1372 send_ext_audio_ack(vs);
1374 case VNC_ENCODING_WMVi:
1375 vs->features |= VNC_FEATURE_WMVI_MASK;
1377 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1378 vs->tight_compression = (enc & 0x0F);
1380 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1381 vs->tight_quality = (enc & 0x0F);
1384 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1389 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1392 static void set_pixel_conversion(VncState *vs)
1394 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1395 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1396 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1397 vs->write_pixels = vnc_write_pixels_copy;
1398 switch (vs->ds->surface->pf.bits_per_pixel) {
1400 vs->send_hextile_tile = send_hextile_tile_8;
1403 vs->send_hextile_tile = send_hextile_tile_16;
1406 vs->send_hextile_tile = send_hextile_tile_32;
1410 vs->write_pixels = vnc_write_pixels_generic;
1411 switch (vs->ds->surface->pf.bits_per_pixel) {
1413 vs->send_hextile_tile = send_hextile_tile_generic_8;
1416 vs->send_hextile_tile = send_hextile_tile_generic_16;
1419 vs->send_hextile_tile = send_hextile_tile_generic_32;
1425 static void set_pixel_format(VncState *vs,
1426 int bits_per_pixel, int depth,
1427 int big_endian_flag, int true_color_flag,
1428 int red_max, int green_max, int blue_max,
1429 int red_shift, int green_shift, int blue_shift)
1431 if (!true_color_flag) {
1432 vnc_client_error(vs);
1436 vs->clientds = vs->serverds;
1437 vs->clientds.pf.rmax = red_max;
1438 count_bits(vs->clientds.pf.rbits, red_max);
1439 vs->clientds.pf.rshift = red_shift;
1440 vs->clientds.pf.rmask = red_max << red_shift;
1441 vs->clientds.pf.gmax = green_max;
1442 count_bits(vs->clientds.pf.gbits, green_max);
1443 vs->clientds.pf.gshift = green_shift;
1444 vs->clientds.pf.gmask = green_max << green_shift;
1445 vs->clientds.pf.bmax = blue_max;
1446 count_bits(vs->clientds.pf.bbits, blue_max);
1447 vs->clientds.pf.bshift = blue_shift;
1448 vs->clientds.pf.bmask = blue_max << blue_shift;
1449 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1450 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1451 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1452 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1454 set_pixel_conversion(vs);
1456 vga_hw_invalidate();
1460 static void pixel_format_message (VncState *vs) {
1461 char pad[3] = { 0, 0, 0 };
1463 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1464 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1466 #ifdef WORDS_BIGENDIAN
1467 vnc_write_u8(vs, 1); /* big-endian-flag */
1469 vnc_write_u8(vs, 0); /* big-endian-flag */
1471 vnc_write_u8(vs, 1); /* true-color-flag */
1472 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1473 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1474 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1475 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1476 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1477 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1478 if (vs->ds->surface->pf.bits_per_pixel == 32)
1479 vs->send_hextile_tile = send_hextile_tile_32;
1480 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1481 vs->send_hextile_tile = send_hextile_tile_16;
1482 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1483 vs->send_hextile_tile = send_hextile_tile_8;
1484 vs->clientds = *(vs->ds->surface);
1485 vs->clientds.flags |= ~QEMU_ALLOCATED_FLAG;
1486 vs->write_pixels = vnc_write_pixels_copy;
1488 vnc_write(vs, pad, 3); /* padding */
1491 static void vnc_dpy_setdata(DisplayState *ds)
1493 /* We don't have to do anything */
1496 static void vnc_colordepth(VncState *vs)
1498 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1499 /* Sending a WMVi message to notify the client*/
1500 vnc_write_u8(vs, 0); /* msg id */
1501 vnc_write_u8(vs, 0);
1502 vnc_write_u16(vs, 1); /* number of rects */
1503 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1504 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1505 pixel_format_message(vs);
1508 set_pixel_conversion(vs);
1512 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1522 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1523 read_u8(data, 6), read_u8(data, 7),
1524 read_u16(data, 8), read_u16(data, 10),
1525 read_u16(data, 12), read_u8(data, 14),
1526 read_u8(data, 15), read_u8(data, 16));
1533 limit = read_u16(data, 2);
1535 return 4 + (limit * 4);
1537 limit = read_u16(data, 2);
1539 for (i = 0; i < limit; i++) {
1540 int32_t val = read_s32(data, 4 + (i * 4));
1541 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1544 set_encodings(vs, (int32_t *)(data + 4), limit);
1550 framebuffer_update_request(vs,
1551 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1552 read_u16(data, 6), read_u16(data, 8));
1558 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1564 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1571 uint32_t dlen = read_u32(data, 4);
1576 client_cut_text(vs, read_u32(data, 4), data + 8);
1582 switch (read_u8(data, 1)) {
1587 ext_key_event(vs, read_u16(data, 2),
1588 read_u32(data, 4), read_u32(data, 8));
1594 switch (read_u16 (data, 2)) {
1604 switch (read_u8(data, 4)) {
1605 case 0: vs->as.fmt = AUD_FMT_U8; break;
1606 case 1: vs->as.fmt = AUD_FMT_S8; break;
1607 case 2: vs->as.fmt = AUD_FMT_U16; break;
1608 case 3: vs->as.fmt = AUD_FMT_S16; break;
1609 case 4: vs->as.fmt = AUD_FMT_U32; break;
1610 case 5: vs->as.fmt = AUD_FMT_S32; break;
1612 printf("Invalid audio format %d\n", read_u8(data, 4));
1613 vnc_client_error(vs);
1616 vs->as.nchannels = read_u8(data, 5);
1617 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1618 printf("Invalid audio channel coount %d\n",
1620 vnc_client_error(vs);
1623 vs->as.freq = read_u32(data, 6);
1626 printf ("Invalid audio message %d\n", read_u8(data, 4));
1627 vnc_client_error(vs);
1633 printf("Msg: %d\n", read_u16(data, 0));
1634 vnc_client_error(vs);
1639 printf("Msg: %d\n", data[0]);
1640 vnc_client_error(vs);
1644 vnc_read_when(vs, protocol_client_msg, 1);
1648 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1653 vnc_write_u16(vs, ds_get_width(vs->ds));
1654 vnc_write_u16(vs, ds_get_height(vs->ds));
1656 pixel_format_message(vs);
1659 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1661 size = snprintf(buf, sizeof(buf), "QEMU");
1663 vnc_write_u32(vs, size);
1664 vnc_write(vs, buf, size);
1667 vnc_read_when(vs, protocol_client_msg, 1);
1672 static void make_challenge(VncState *vs)
1676 srand(time(NULL)+getpid()+getpid()*987654+rand());
1678 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1679 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1682 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1684 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1686 unsigned char key[8];
1688 if (!vs->vd->password || !vs->vd->password[0]) {
1689 VNC_DEBUG("No password configured on server");
1690 vnc_write_u32(vs, 1); /* Reject auth */
1691 if (vs->minor >= 8) {
1692 static const char err[] = "Authentication failed";
1693 vnc_write_u32(vs, sizeof(err));
1694 vnc_write(vs, err, sizeof(err));
1697 vnc_client_error(vs);
1701 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1703 /* Calculate the expected challenge response */
1704 pwlen = strlen(vs->vd->password);
1705 for (i=0; i<sizeof(key); i++)
1706 key[i] = i<pwlen ? vs->vd->password[i] : 0;
1708 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1709 des(response+j, response+j);
1711 /* Compare expected vs actual challenge response */
1712 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1713 VNC_DEBUG("Client challenge reponse did not match\n");
1714 vnc_write_u32(vs, 1); /* Reject auth */
1715 if (vs->minor >= 8) {
1716 static const char err[] = "Authentication failed";
1717 vnc_write_u32(vs, sizeof(err));
1718 vnc_write(vs, err, sizeof(err));
1721 vnc_client_error(vs);
1723 VNC_DEBUG("Accepting VNC challenge response\n");
1724 vnc_write_u32(vs, 0); /* Accept auth */
1727 vnc_read_when(vs, protocol_client_init, 1);
1732 static int start_auth_vnc(VncState *vs)
1735 /* Send client a 'random' challenge */
1736 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1739 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1744 #ifdef CONFIG_VNC_TLS
1745 #define DH_BITS 1024
1746 static gnutls_dh_params_t dh_params;
1748 static int vnc_tls_initialize(void)
1750 static int tlsinitialized = 0;
1755 if (gnutls_global_init () < 0)
1758 /* XXX ought to re-generate diffie-hellmen params periodically */
1759 if (gnutls_dh_params_init (&dh_params) < 0)
1761 if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1764 #if defined(_VNC_DEBUG) && _VNC_DEBUG >= 2
1765 gnutls_global_set_log_level(10);
1766 gnutls_global_set_log_function(vnc_debug_gnutls_log);
1774 static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1776 gnutls_anon_server_credentials anon_cred;
1779 if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1780 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1784 gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1790 static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1792 gnutls_certificate_credentials_t x509_cred;
1795 if (!vs->vd->x509cacert) {
1796 VNC_DEBUG("No CA x509 certificate specified\n");
1799 if (!vs->vd->x509cert) {
1800 VNC_DEBUG("No server x509 certificate specified\n");
1803 if (!vs->vd->x509key) {
1804 VNC_DEBUG("No server private key specified\n");
1808 if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1809 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1812 if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1814 GNUTLS_X509_FMT_PEM)) < 0) {
1815 VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1816 gnutls_certificate_free_credentials(x509_cred);
1820 if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1823 GNUTLS_X509_FMT_PEM)) < 0) {
1824 VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1825 gnutls_certificate_free_credentials(x509_cred);
1829 if (vs->vd->x509cacrl) {
1830 if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1832 GNUTLS_X509_FMT_PEM)) < 0) {
1833 VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
1834 gnutls_certificate_free_credentials(x509_cred);
1839 gnutls_certificate_set_dh_params (x509_cred, dh_params);
1844 static int vnc_validate_certificate(struct VncState *vs)
1847 unsigned int status;
1848 const gnutls_datum_t *certs;
1849 unsigned int nCerts, i;
1852 VNC_DEBUG("Validating client certificate\n");
1853 if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
1854 VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
1858 if ((now = time(NULL)) == ((time_t)-1)) {
1863 if (status & GNUTLS_CERT_INVALID)
1864 VNC_DEBUG("The certificate is not trusted.\n");
1866 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1867 VNC_DEBUG("The certificate hasn't got a known issuer.\n");
1869 if (status & GNUTLS_CERT_REVOKED)
1870 VNC_DEBUG("The certificate has been revoked.\n");
1872 if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1873 VNC_DEBUG("The certificate uses an insecure algorithm\n");
1877 VNC_DEBUG("Certificate is valid!\n");
1880 /* Only support x509 for now */
1881 if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
1884 if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
1887 for (i = 0 ; i < nCerts ; i++) {
1888 gnutls_x509_crt_t cert;
1889 VNC_DEBUG ("Checking certificate chain %d\n", i);
1890 if (gnutls_x509_crt_init (&cert) < 0)
1893 if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1894 gnutls_x509_crt_deinit (cert);
1898 if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1899 VNC_DEBUG("The certificate has expired\n");
1900 gnutls_x509_crt_deinit (cert);
1904 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1905 VNC_DEBUG("The certificate is not yet activated\n");
1906 gnutls_x509_crt_deinit (cert);
1910 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1911 VNC_DEBUG("The certificate is not yet activated\n");
1912 gnutls_x509_crt_deinit (cert);
1916 gnutls_x509_crt_deinit (cert);
1923 static int start_auth_vencrypt_subauth(VncState *vs)
1925 switch (vs->vd->subauth) {
1926 case VNC_AUTH_VENCRYPT_TLSNONE:
1927 case VNC_AUTH_VENCRYPT_X509NONE:
1928 VNC_DEBUG("Accept TLS auth none\n");
1929 vnc_write_u32(vs, 0); /* Accept auth completion */
1930 vnc_read_when(vs, protocol_client_init, 1);
1933 case VNC_AUTH_VENCRYPT_TLSVNC:
1934 case VNC_AUTH_VENCRYPT_X509VNC:
1935 VNC_DEBUG("Start TLS auth VNC\n");
1936 return start_auth_vnc(vs);
1938 default: /* Should not be possible, but just in case */
1939 VNC_DEBUG("Reject auth %d\n", vs->vd->auth);
1940 vnc_write_u8(vs, 1);
1941 if (vs->minor >= 8) {
1942 static const char err[] = "Unsupported authentication type";
1943 vnc_write_u32(vs, sizeof(err));
1944 vnc_write(vs, err, sizeof(err));
1946 vnc_client_error(vs);
1952 static void vnc_handshake_io(void *opaque);
1954 static int vnc_continue_handshake(struct VncState *vs) {
1957 if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1958 if (!gnutls_error_is_fatal(ret)) {
1959 VNC_DEBUG("Handshake interrupted (blocking)\n");
1960 if (!gnutls_record_get_direction(vs->tls_session))
1961 qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1963 qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1966 VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1967 vnc_client_error(vs);
1971 if (vs->vd->x509verify) {
1972 if (vnc_validate_certificate(vs) < 0) {
1973 VNC_DEBUG("Client verification failed\n");
1974 vnc_client_error(vs);
1977 VNC_DEBUG("Client verification passed\n");
1981 VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1982 vs->wiremode = VNC_WIREMODE_TLS;
1983 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1985 return start_auth_vencrypt_subauth(vs);
1988 static void vnc_handshake_io(void *opaque) {
1989 struct VncState *vs = (struct VncState *)opaque;
1991 VNC_DEBUG("Handshake IO continue\n");
1992 vnc_continue_handshake(vs);
1995 #define NEED_X509_AUTH(vs) \
1996 ((vs)->vd->subauth == VNC_AUTH_VENCRYPT_X509NONE || \
1997 (vs)->vd->subauth == VNC_AUTH_VENCRYPT_X509VNC || \
1998 (vs)->vd->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
2001 static int vnc_start_tls(struct VncState *vs) {
2002 static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
2003 static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
2004 static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
2005 static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
2007 VNC_DEBUG("Do TLS setup\n");
2008 if (vnc_tls_initialize() < 0) {
2009 VNC_DEBUG("Failed to init TLS\n");
2010 vnc_client_error(vs);
2013 if (vs->tls_session == NULL) {
2014 if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
2015 vnc_client_error(vs);
2019 if (gnutls_set_default_priority(vs->tls_session) < 0) {
2020 gnutls_deinit(vs->tls_session);
2021 vs->tls_session = NULL;
2022 vnc_client_error(vs);
2026 if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
2027 gnutls_deinit(vs->tls_session);
2028 vs->tls_session = NULL;
2029 vnc_client_error(vs);
2033 if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
2034 gnutls_deinit(vs->tls_session);
2035 vs->tls_session = NULL;
2036 vnc_client_error(vs);
2040 if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
2041 gnutls_deinit(vs->tls_session);
2042 vs->tls_session = NULL;
2043 vnc_client_error(vs);
2047 if (NEED_X509_AUTH(vs)) {
2048 gnutls_certificate_server_credentials x509_cred = vnc_tls_initialize_x509_cred(vs);
2050 gnutls_deinit(vs->tls_session);
2051 vs->tls_session = NULL;
2052 vnc_client_error(vs);
2055 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {
2056 gnutls_deinit(vs->tls_session);
2057 vs->tls_session = NULL;
2058 gnutls_certificate_free_credentials(x509_cred);
2059 vnc_client_error(vs);
2062 if (vs->vd->x509verify) {
2063 VNC_DEBUG("Requesting a client certificate\n");
2064 gnutls_certificate_server_set_request (vs->tls_session, GNUTLS_CERT_REQUEST);
2068 gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
2070 gnutls_deinit(vs->tls_session);
2071 vs->tls_session = NULL;
2072 vnc_client_error(vs);
2075 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
2076 gnutls_deinit(vs->tls_session);
2077 vs->tls_session = NULL;
2078 gnutls_anon_free_server_credentials(anon_cred);
2079 vnc_client_error(vs);
2084 gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
2085 gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
2086 gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
2089 VNC_DEBUG("Start TLS handshake process\n");
2090 return vnc_continue_handshake(vs);
2093 static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)
2095 int auth = read_u32(data, 0);
2097 if (auth != vs->vd->subauth) {
2098 VNC_DEBUG("Rejecting auth %d\n", auth);
2099 vnc_write_u8(vs, 0); /* Reject auth */
2101 vnc_client_error(vs);
2103 VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
2104 vnc_write_u8(vs, 1); /* Accept auth */
2107 if (vnc_start_tls(vs) < 0) {
2108 VNC_DEBUG("Failed to complete TLS\n");
2115 static int protocol_client_vencrypt_init(VncState *vs, uint8_t *data, size_t len)
2119 VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
2120 vnc_write_u8(vs, 1); /* Reject version */
2122 vnc_client_error(vs);
2124 VNC_DEBUG("Sending allowed auth %d\n", vs->vd->subauth);
2125 vnc_write_u8(vs, 0); /* Accept version */
2126 vnc_write_u8(vs, 1); /* Number of sub-auths */
2127 vnc_write_u32(vs, vs->vd->subauth); /* The supported auth */
2129 vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
2134 static int start_auth_vencrypt(VncState *vs)
2136 /* Send VeNCrypt version 0.2 */
2137 vnc_write_u8(vs, 0);
2138 vnc_write_u8(vs, 2);
2140 vnc_read_when(vs, protocol_client_vencrypt_init, 2);
2143 #endif /* CONFIG_VNC_TLS */
2145 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2147 /* We only advertise 1 auth scheme at a time, so client
2148 * must pick the one we sent. Verify this */
2149 if (data[0] != vs->vd->auth) { /* Reject auth */
2150 VNC_DEBUG("Reject auth %d\n", (int)data[0]);
2151 vnc_write_u32(vs, 1);
2152 if (vs->minor >= 8) {
2153 static const char err[] = "Authentication failed";
2154 vnc_write_u32(vs, sizeof(err));
2155 vnc_write(vs, err, sizeof(err));
2157 vnc_client_error(vs);
2158 } else { /* Accept requested auth */
2159 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2160 switch (vs->vd->auth) {
2162 VNC_DEBUG("Accept auth none\n");
2163 if (vs->minor >= 8) {
2164 vnc_write_u32(vs, 0); /* Accept auth completion */
2167 vnc_read_when(vs, protocol_client_init, 1);
2171 VNC_DEBUG("Start VNC auth\n");
2172 return start_auth_vnc(vs);
2174 #ifdef CONFIG_VNC_TLS
2175 case VNC_AUTH_VENCRYPT:
2176 VNC_DEBUG("Accept VeNCrypt auth\n");;
2177 return start_auth_vencrypt(vs);
2178 #endif /* CONFIG_VNC_TLS */
2180 default: /* Should not be possible, but just in case */
2181 VNC_DEBUG("Reject auth %d\n", vs->vd->auth);
2182 vnc_write_u8(vs, 1);
2183 if (vs->minor >= 8) {
2184 static const char err[] = "Authentication failed";
2185 vnc_write_u32(vs, sizeof(err));
2186 vnc_write(vs, err, sizeof(err));
2188 vnc_client_error(vs);
2194 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2198 memcpy(local, version, 12);
2201 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2202 VNC_DEBUG("Malformed protocol version %s\n", local);
2203 vnc_client_error(vs);
2206 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2207 if (vs->major != 3 ||
2213 VNC_DEBUG("Unsupported client version\n");
2214 vnc_write_u32(vs, VNC_AUTH_INVALID);
2216 vnc_client_error(vs);
2219 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2220 * as equivalent to v3.3 by servers
2222 if (vs->minor == 4 || vs->minor == 5)
2225 if (vs->minor == 3) {
2226 if (vs->vd->auth == VNC_AUTH_NONE) {
2227 VNC_DEBUG("Tell client auth none\n");
2228 vnc_write_u32(vs, vs->vd->auth);
2230 vnc_read_when(vs, protocol_client_init, 1);
2231 } else if (vs->vd->auth == VNC_AUTH_VNC) {
2232 VNC_DEBUG("Tell client VNC auth\n");
2233 vnc_write_u32(vs, vs->vd->auth);
2237 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2238 vnc_write_u32(vs, VNC_AUTH_INVALID);
2240 vnc_client_error(vs);
2243 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2244 vnc_write_u8(vs, 1); /* num auth */
2245 vnc_write_u8(vs, vs->vd->auth);
2246 vnc_read_when(vs, protocol_client_auth, 1);
2253 static void vnc_connect(VncDisplay *vd, int csock)
2255 VncState *vs = qemu_mallocz(sizeof(VncState));
2258 VNC_DEBUG("New client on socket %d\n", csock);
2260 socket_set_nonblock(vs->csock);
2261 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2265 vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
2269 vs->as.freq = 44100;
2270 vs->as.nchannels = 2;
2271 vs->as.fmt = AUD_FMT_S16;
2272 vs->as.endianness = 0;
2275 vnc_write(vs, "RFB 003.008\n", 12);
2277 vnc_read_when(vs, protocol_version, 12);
2278 memset(vs->old_data, 0, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
2279 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
2280 vnc_update_client(vs);
2283 vs->next = vd->clients;
2287 static void vnc_listen_read(void *opaque)
2289 VncDisplay *vs = opaque;
2290 struct sockaddr_in addr;
2291 socklen_t addrlen = sizeof(addr);
2296 int csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2298 vnc_connect(vs, csock);
2302 void vnc_display_init(DisplayState *ds)
2306 vs = qemu_mallocz(sizeof(VncState));
2307 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2317 if (keyboard_layout)
2318 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2320 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2322 if (!vs->kbd_layout)
2325 dcl->dpy_copy = vnc_dpy_copy;
2326 dcl->dpy_update = vnc_dpy_update;
2327 dcl->dpy_resize = vnc_dpy_resize;
2328 dcl->dpy_setdata = vnc_dpy_setdata;
2329 register_displaychangelistener(ds, dcl);
2332 #ifdef CONFIG_VNC_TLS
2333 static int vnc_set_x509_credential(VncDisplay *vs,
2334 const char *certdir,
2335 const char *filename,
2346 *cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2);
2348 strcpy(*cred, certdir);
2350 strcat(*cred, filename);
2352 VNC_DEBUG("Check %s\n", *cred);
2353 if (stat(*cred, &sb) < 0) {
2356 if (ignoreMissing && errno == ENOENT)
2364 static int vnc_set_x509_credential_dir(VncDisplay *vs,
2365 const char *certdir)
2367 if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)
2369 if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)
2371 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)
2373 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)
2379 qemu_free(vs->x509cacert);
2380 qemu_free(vs->x509cacrl);
2381 qemu_free(vs->x509cert);
2382 qemu_free(vs->x509key);
2383 vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2386 #endif /* CONFIG_VNC_TLS */
2388 void vnc_display_close(DisplayState *ds)
2390 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2395 qemu_free(vs->display);
2398 if (vs->lsock != -1) {
2399 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2403 vs->auth = VNC_AUTH_INVALID;
2404 #ifdef CONFIG_VNC_TLS
2405 vs->subauth = VNC_AUTH_INVALID;
2410 int vnc_display_password(DisplayState *ds, const char *password)
2412 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2415 qemu_free(vs->password);
2416 vs->password = NULL;
2418 if (password && password[0]) {
2419 if (!(vs->password = qemu_strdup(password)))
2426 int vnc_display_open(DisplayState *ds, const char *display)
2428 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2429 const char *options;
2433 #ifdef CONFIG_VNC_TLS
2434 int tls = 0, x509 = 0;
2439 vnc_display_close(ds);
2440 if (strcmp(display, "none") == 0)
2443 if (!(vs->display = strdup(display)))
2447 while ((options = strchr(options, ','))) {
2449 if (strncmp(options, "password", 8) == 0) {
2450 password = 1; /* Require password auth */
2451 } else if (strncmp(options, "reverse", 7) == 0) {
2453 } else if (strncmp(options, "to=", 3) == 0) {
2454 to_port = atoi(options+3) + 5900;
2455 #ifdef CONFIG_VNC_TLS
2456 } else if (strncmp(options, "tls", 3) == 0) {
2457 tls = 1; /* Require TLS */
2458 } else if (strncmp(options, "x509", 4) == 0) {
2460 x509 = 1; /* Require x509 certificates */
2461 if (strncmp(options, "x509verify", 10) == 0)
2462 vs->x509verify = 1; /* ...and verify client certs */
2464 /* Now check for 'x509=/some/path' postfix
2465 * and use that to setup x509 certificate/key paths */
2466 start = strchr(options, '=');
2467 end = strchr(options, ',');
2468 if (start && (!end || (start < end))) {
2469 int len = end ? end-(start+1) : strlen(start+1);
2470 char *path = qemu_strndup(start + 1, len);
2472 VNC_DEBUG("Trying certificate path '%s'\n", path);
2473 if (vnc_set_x509_credential_dir(vs, path) < 0) {
2474 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2476 qemu_free(vs->display);
2482 fprintf(stderr, "No certificate path provided\n");
2483 qemu_free(vs->display);
2492 #ifdef CONFIG_VNC_TLS
2494 vs->auth = VNC_AUTH_VENCRYPT;
2496 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2497 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2499 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2500 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2504 VNC_DEBUG("Initializing VNC server with password auth\n");
2505 vs->auth = VNC_AUTH_VNC;
2506 #ifdef CONFIG_VNC_TLS
2507 vs->subauth = VNC_AUTH_INVALID;
2511 #ifdef CONFIG_VNC_TLS
2513 vs->auth = VNC_AUTH_VENCRYPT;
2515 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2516 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2518 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2519 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2523 VNC_DEBUG("Initializing VNC server with no auth\n");
2524 vs->auth = VNC_AUTH_NONE;
2525 #ifdef CONFIG_VNC_TLS
2526 vs->subauth = VNC_AUTH_INVALID;
2532 /* connect to viewer */
2533 if (strncmp(display, "unix:", 5) == 0)
2534 vs->lsock = unix_connect(display+5);
2536 vs->lsock = inet_connect(display, SOCK_STREAM);
2537 if (-1 == vs->lsock) {
2542 int csock = vs->lsock;
2544 vnc_connect(vs, csock);
2549 /* listen for connects */
2551 dpy = qemu_malloc(256);
2552 if (strncmp(display, "unix:", 5) == 0) {
2553 pstrcpy(dpy, 256, "unix:");
2554 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2556 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2558 if (-1 == vs->lsock) {
2566 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);