2 * QEMU VNC display driver
4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5 * Copyright (C) 2006 Fabrice Bellard
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu-common.h"
29 #include "qemu_socket.h"
30 #include "qemu-timer.h"
31 #include "audio/audio.h"
33 #define VNC_REFRESH_INTERVAL (1000 / 30)
36 #include "vnc_keysym.h"
41 #include <gnutls/gnutls.h>
42 #include <gnutls/x509.h>
43 #endif /* CONFIG_VNC_TLS */
45 // #define _VNC_DEBUG 1
48 #define VNC_DEBUG(fmt, ...) do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
50 #if defined(CONFIG_VNC_TLS) && _VNC_DEBUG >= 2
51 /* Very verbose, so only enabled for _VNC_DEBUG >= 2 */
52 static void vnc_debug_gnutls_log(int level, const char* str) {
53 VNC_DEBUG("%d %s", level, str);
55 #endif /* CONFIG_VNC_TLS && _VNC_DEBUG */
57 #define VNC_DEBUG(fmt, ...) do { } while (0)
60 #define count_bits(c, v) { \
61 for (c = 0; v; v >>= 1) \
74 typedef struct VncState VncState;
76 typedef int VncReadEvent(VncState *vs, uint8_t *data, size_t len);
78 typedef void VncWritePixels(VncState *vs, void *data, int size);
80 typedef void VncSendHextileTile(VncState *vs,
81 int x, int y, int w, int h,
84 int *has_bg, int *has_fg);
86 #define VNC_MAX_WIDTH 2048
87 #define VNC_MAX_HEIGHT 2048
88 #define VNC_DIRTY_WORDS (VNC_MAX_WIDTH / (16 * 32))
90 #define VNC_AUTH_CHALLENGE_SIZE 16
99 uint32_t dirty_row[VNC_MAX_HEIGHT][VNC_DIRTY_WORDS];
106 uint32_t vnc_encoding;
107 uint8_t tight_quality;
108 uint8_t tight_compression;
116 #ifdef CONFIG_VNC_TLS
125 char challenge[VNC_AUTH_CHALLENGE_SIZE];
127 #ifdef CONFIG_VNC_TLS
129 gnutls_session_t tls_session;
134 kbd_layout_t *kbd_layout;
135 /* current output mode information */
136 VncWritePixels *write_pixels;
137 VncSendHextileTile *send_hextile_tile;
138 DisplaySurface clientds, serverds;
140 CaptureVoiceOut *audio_cap;
141 struct audsettings as;
143 VncReadEvent *read_handler;
144 size_t read_handler_expect;
146 uint8_t modifiers_state[256];
149 static VncState *vnc_state; /* needed for info vnc */
150 static DisplayChangeListener *dcl;
152 void do_info_vnc(void)
154 if (vnc_state == NULL || vnc_state->display == NULL)
155 term_printf("VNC server disabled\n");
157 term_printf("VNC server active on: ");
158 term_print_filename(vnc_state->display);
161 if (vnc_state->csock == -1)
162 term_printf("No client connected\n");
164 term_printf("Client connected\n");
168 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
169 return (vs->features & (1 << feature));
173 1) Get the queue working for IO.
174 2) there is some weirdness when using the -S option (the screen is grey
175 and not totally invalidated
176 3) resolutions > 1024
179 static void vnc_write(VncState *vs, const void *data, size_t len);
180 static void vnc_write_u32(VncState *vs, uint32_t value);
181 static void vnc_write_s32(VncState *vs, int32_t value);
182 static void vnc_write_u16(VncState *vs, uint16_t value);
183 static void vnc_write_u8(VncState *vs, uint8_t value);
184 static void vnc_flush(VncState *vs);
185 static void vnc_update_client(void *opaque);
186 static void vnc_client_read(void *opaque);
188 static void vnc_colordepth(DisplayState *ds);
190 static inline void vnc_set_bit(uint32_t *d, int k)
192 d[k >> 5] |= 1 << (k & 0x1f);
195 static inline void vnc_clear_bit(uint32_t *d, int k)
197 d[k >> 5] &= ~(1 << (k & 0x1f));
200 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
210 d[j++] = (1 << n) - 1;
215 static inline int vnc_get_bit(const uint32_t *d, int k)
217 return (d[k >> 5] >> (k & 0x1f)) & 1;
220 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
224 for(i = 0; i < nb_words; i++) {
225 if ((d1[i] & d2[i]) != 0)
231 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
233 VncState *vs = ds->opaque;
238 /* round x down to ensure the loop only spans one 16-pixel block per,
239 iteration. otherwise, if (x % 16) != 0, the last iteration may span
240 two 16-pixel blocks but we only mark the first as dirty
245 x = MIN(x, vs->serverds.width);
246 y = MIN(y, vs->serverds.height);
247 w = MIN(x + w, vs->serverds.width) - x;
248 h = MIN(h, vs->serverds.height);
251 for (i = 0; i < w; i += 16)
252 vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
255 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
258 vnc_write_u16(vs, x);
259 vnc_write_u16(vs, y);
260 vnc_write_u16(vs, w);
261 vnc_write_u16(vs, h);
263 vnc_write_s32(vs, encoding);
266 static void buffer_reserve(Buffer *buffer, size_t len)
268 if ((buffer->capacity - buffer->offset) < len) {
269 buffer->capacity += (len + 1024);
270 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
271 if (buffer->buffer == NULL) {
272 fprintf(stderr, "vnc: out of memory\n");
278 static int buffer_empty(Buffer *buffer)
280 return buffer->offset == 0;
283 static uint8_t *buffer_end(Buffer *buffer)
285 return buffer->buffer + buffer->offset;
288 static void buffer_reset(Buffer *buffer)
293 static void buffer_append(Buffer *buffer, const void *data, size_t len)
295 memcpy(buffer->buffer + buffer->offset, data, len);
296 buffer->offset += len;
299 static void vnc_dpy_resize(DisplayState *ds)
302 VncState *vs = ds->opaque;
304 vs->old_data = qemu_realloc(vs->old_data, ds_get_linesize(ds) * ds_get_height(ds));
306 if (vs->old_data == NULL) {
307 fprintf(stderr, "vnc: memory allocation failed\n");
311 if (ds_get_bytes_per_pixel(ds) != vs->serverds.pf.bytes_per_pixel)
312 console_color_init(ds);
314 size_changed = ds_get_width(ds) != vs->serverds.width ||
315 ds_get_height(ds) != vs->serverds.height;
316 vs->serverds = *(ds->surface);
318 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
319 vnc_write_u8(vs, 0); /* msg id */
321 vnc_write_u16(vs, 1); /* number of rects */
322 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
323 VNC_ENCODING_DESKTOPRESIZE);
328 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
329 memset(vs->old_data, 42, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
333 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
335 vnc_write(vs, pixels, size);
338 /* slowest but generic code. */
339 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
343 r = ((((v & vs->serverds.pf.rmask) >> vs->serverds.pf.rshift) << vs->clientds.pf.rbits) >>
344 vs->serverds.pf.rbits);
345 g = ((((v & vs->serverds.pf.gmask) >> vs->serverds.pf.gshift) << vs->clientds.pf.gbits) >>
346 vs->serverds.pf.gbits);
347 b = ((((v & vs->serverds.pf.bmask) >> vs->serverds.pf.bshift) << vs->clientds.pf.bbits) >>
348 vs->serverds.pf.bbits);
349 v = (r << vs->clientds.pf.rshift) |
350 (g << vs->clientds.pf.gshift) |
351 (b << vs->clientds.pf.bshift);
352 switch(vs->clientds.pf.bytes_per_pixel) {
357 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
367 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
382 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
386 if (vs->serverds.pf.bytes_per_pixel == 4) {
387 uint32_t *pixels = pixels1;
390 for(i = 0; i < n; i++) {
391 vnc_convert_pixel(vs, buf, pixels[i]);
392 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
394 } else if (vs->serverds.pf.bytes_per_pixel == 2) {
395 uint16_t *pixels = pixels1;
398 for(i = 0; i < n; i++) {
399 vnc_convert_pixel(vs, buf, pixels[i]);
400 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
402 } else if (vs->serverds.pf.bytes_per_pixel == 1) {
403 uint8_t *pixels = pixels1;
406 for(i = 0; i < n; i++) {
407 vnc_convert_pixel(vs, buf, pixels[i]);
408 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
411 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
415 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
420 row = ds_get_data(vs->ds) + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
421 for (i = 0; i < h; i++) {
422 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
423 row += ds_get_linesize(vs->ds);
427 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
429 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
430 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
434 #include "vnchextile.h"
438 #include "vnchextile.h"
442 #include "vnchextile.h"
447 #include "vnchextile.h"
453 #include "vnchextile.h"
459 #include "vnchextile.h"
463 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
467 uint8_t *last_fg, *last_bg;
469 last_fg = (uint8_t *) malloc(vs->serverds.pf.bytes_per_pixel);
470 last_bg = (uint8_t *) malloc(vs->serverds.pf.bytes_per_pixel);
472 for (j = y; j < (y + h); j += 16) {
473 for (i = x; i < (x + w); i += 16) {
474 vs->send_hextile_tile(vs, i, j,
475 MIN(16, x + w - i), MIN(16, y + h - j),
476 last_bg, last_fg, &has_bg, &has_fg);
484 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
486 switch(vs->vnc_encoding) {
487 case VNC_ENCODING_HEXTILE:
488 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
489 send_framebuffer_update_hextile(vs, x, y, w, h);
492 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
493 send_framebuffer_update_raw(vs, x, y, w, h);
498 static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
500 VncState *vs = ds->opaque;
502 vnc_update_client(vs);
504 vnc_write_u8(vs, 0); /* msg id */
506 vnc_write_u16(vs, 1); /* number of rects */
507 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
508 vnc_write_u16(vs, src_x);
509 vnc_write_u16(vs, src_y);
513 static int find_dirty_height(VncState *vs, int y, int last_x, int x)
517 for (h = 1; h < (vs->serverds.height - y); h++) {
519 if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
521 for (tmp_x = last_x; tmp_x < x; tmp_x++)
522 vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
528 static void vnc_update_client(void *opaque)
530 VncState *vs = opaque;
532 if (vs->need_update && vs->csock != -1) {
536 uint32_t width_mask[VNC_DIRTY_WORDS];
543 vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
545 /* Walk through the dirty map and eliminate tiles that
546 really aren't dirty */
547 row = ds_get_data(vs->ds);
548 old_row = vs->old_data;
550 for (y = 0; y < ds_get_height(vs->ds); y++) {
551 if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
557 old_ptr = (char*)old_row;
559 for (x = 0; x < ds_get_width(vs->ds); x += 16) {
560 if (memcmp(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds)) == 0) {
561 vnc_clear_bit(vs->dirty_row[y], (x / 16));
564 memcpy(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds));
567 ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
568 old_ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
572 row += ds_get_linesize(vs->ds);
573 old_row += ds_get_linesize(vs->ds);
576 if (!has_dirty && !vs->audio_cap) {
577 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
581 /* Count rectangles */
583 vnc_write_u8(vs, 0); /* msg id */
585 saved_offset = vs->output.offset;
586 vnc_write_u16(vs, 0);
588 for (y = 0; y < vs->serverds.height; y++) {
591 for (x = 0; x < vs->serverds.width / 16; x++) {
592 if (vnc_get_bit(vs->dirty_row[y], x)) {
596 vnc_clear_bit(vs->dirty_row[y], x);
599 int h = find_dirty_height(vs, y, last_x, x);
600 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
607 int h = find_dirty_height(vs, y, last_x, x);
608 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
612 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
613 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
618 if (vs->csock != -1) {
619 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
624 static int vnc_listen_poll(void *opaque)
626 VncState *vs = opaque;
633 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
635 VncState *vs = opaque;
638 case AUD_CNOTIFY_DISABLE:
639 vnc_write_u8(vs, 255);
641 vnc_write_u16(vs, 0);
645 case AUD_CNOTIFY_ENABLE:
646 vnc_write_u8(vs, 255);
648 vnc_write_u16(vs, 1);
654 static void audio_capture_destroy(void *opaque)
658 static void audio_capture(void *opaque, void *buf, int size)
660 VncState *vs = opaque;
662 vnc_write_u8(vs, 255);
664 vnc_write_u16(vs, 2);
665 vnc_write_u32(vs, size);
666 vnc_write(vs, buf, size);
670 static void audio_add(VncState *vs)
672 struct audio_capture_ops ops;
675 term_printf ("audio already running\n");
679 ops.notify = audio_capture_notify;
680 ops.destroy = audio_capture_destroy;
681 ops.capture = audio_capture;
683 vs->audio_cap = AUD_add_capture(NULL, &vs->as, &ops, vs);
684 if (!vs->audio_cap) {
685 term_printf ("Failed to add audio capture\n");
689 static void audio_del(VncState *vs)
692 AUD_del_capture(vs->audio_cap, vs);
693 vs->audio_cap = NULL;
697 static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
699 if (ret == 0 || ret == -1) {
701 switch (last_errno) {
713 VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
714 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
715 closesocket(vs->csock);
718 buffer_reset(&vs->input);
719 buffer_reset(&vs->output);
721 #ifdef CONFIG_VNC_TLS
722 if (vs->tls_session) {
723 gnutls_deinit(vs->tls_session);
724 vs->tls_session = NULL;
726 vs->wiremode = VNC_WIREMODE_CLEAR;
727 #endif /* CONFIG_VNC_TLS */
734 static void vnc_client_error(VncState *vs)
736 vnc_client_io_error(vs, -1, EINVAL);
739 static void vnc_client_write(void *opaque)
742 VncState *vs = opaque;
744 #ifdef CONFIG_VNC_TLS
745 if (vs->tls_session) {
746 ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
748 if (ret == GNUTLS_E_AGAIN)
755 #endif /* CONFIG_VNC_TLS */
756 ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
757 ret = vnc_client_io_error(vs, ret, socket_error());
761 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
762 vs->output.offset -= ret;
764 if (vs->output.offset == 0) {
765 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
769 static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
771 vs->read_handler = func;
772 vs->read_handler_expect = expecting;
775 static void vnc_client_read(void *opaque)
777 VncState *vs = opaque;
780 buffer_reserve(&vs->input, 4096);
782 #ifdef CONFIG_VNC_TLS
783 if (vs->tls_session) {
784 ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
786 if (ret == GNUTLS_E_AGAIN)
793 #endif /* CONFIG_VNC_TLS */
794 ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
795 ret = vnc_client_io_error(vs, ret, socket_error());
799 vs->input.offset += ret;
801 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
802 size_t len = vs->read_handler_expect;
805 ret = vs->read_handler(vs, vs->input.buffer, len);
810 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
811 vs->input.offset -= len;
813 vs->read_handler_expect = ret;
818 static void vnc_write(VncState *vs, const void *data, size_t len)
820 buffer_reserve(&vs->output, len);
822 if (buffer_empty(&vs->output)) {
823 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
826 buffer_append(&vs->output, data, len);
829 static void vnc_write_s32(VncState *vs, int32_t value)
831 vnc_write_u32(vs, *(uint32_t *)&value);
834 static void vnc_write_u32(VncState *vs, uint32_t value)
838 buf[0] = (value >> 24) & 0xFF;
839 buf[1] = (value >> 16) & 0xFF;
840 buf[2] = (value >> 8) & 0xFF;
841 buf[3] = value & 0xFF;
843 vnc_write(vs, buf, 4);
846 static void vnc_write_u16(VncState *vs, uint16_t value)
850 buf[0] = (value >> 8) & 0xFF;
851 buf[1] = value & 0xFF;
853 vnc_write(vs, buf, 2);
856 static void vnc_write_u8(VncState *vs, uint8_t value)
858 vnc_write(vs, (char *)&value, 1);
861 static void vnc_flush(VncState *vs)
863 if (vs->output.offset)
864 vnc_client_write(vs);
867 static uint8_t read_u8(uint8_t *data, size_t offset)
872 static uint16_t read_u16(uint8_t *data, size_t offset)
874 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
877 static int32_t read_s32(uint8_t *data, size_t offset)
879 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
880 (data[offset + 2] << 8) | data[offset + 3]);
883 static uint32_t read_u32(uint8_t *data, size_t offset)
885 return ((data[offset] << 24) | (data[offset + 1] << 16) |
886 (data[offset + 2] << 8) | data[offset + 3]);
889 #ifdef CONFIG_VNC_TLS
890 static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
893 struct VncState *vs = (struct VncState *)transport;
897 ret = send(vs->csock, data, len, 0);
907 static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
910 struct VncState *vs = (struct VncState *)transport;
914 ret = recv(vs->csock, data, len, 0);
922 #endif /* CONFIG_VNC_TLS */
924 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
928 static void check_pointer_type_change(VncState *vs, int absolute)
930 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
933 vnc_write_u16(vs, 1);
934 vnc_framebuffer_update(vs, absolute, 0,
935 ds_get_width(vs->ds), ds_get_height(vs->ds),
936 VNC_ENCODING_POINTER_TYPE_CHANGE);
939 vs->absolute = absolute;
942 static void pointer_event(VncState *vs, int button_mask, int x, int y)
947 if (button_mask & 0x01)
948 buttons |= MOUSE_EVENT_LBUTTON;
949 if (button_mask & 0x02)
950 buttons |= MOUSE_EVENT_MBUTTON;
951 if (button_mask & 0x04)
952 buttons |= MOUSE_EVENT_RBUTTON;
953 if (button_mask & 0x08)
955 if (button_mask & 0x10)
959 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
960 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
962 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
966 kbd_mouse_event(x, y, dz, buttons);
968 if (vs->last_x != -1)
969 kbd_mouse_event(x - vs->last_x,
976 check_pointer_type_change(vs, kbd_mouse_is_absolute());
979 static void reset_keys(VncState *vs)
982 for(i = 0; i < 256; i++) {
983 if (vs->modifiers_state[i]) {
985 kbd_put_keycode(0xe0);
986 kbd_put_keycode(i | 0x80);
987 vs->modifiers_state[i] = 0;
992 static void press_key(VncState *vs, int keysym)
994 kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) & 0x7f);
995 kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
998 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1000 /* QEMU console switch */
1002 case 0x2a: /* Left Shift */
1003 case 0x36: /* Right Shift */
1004 case 0x1d: /* Left CTRL */
1005 case 0x9d: /* Right CTRL */
1006 case 0x38: /* Left ALT */
1007 case 0xb8: /* Right ALT */
1009 vs->modifiers_state[keycode] = 1;
1011 vs->modifiers_state[keycode] = 0;
1013 case 0x02 ... 0x0a: /* '1' to '9' keys */
1014 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1015 /* Reset the modifiers sent to the current console */
1017 console_select(keycode - 0x02);
1021 case 0x3a: /* CapsLock */
1022 case 0x45: /* NumLock */
1024 vs->modifiers_state[keycode] ^= 1;
1028 if (keycode_is_keypad(vs->kbd_layout, keycode)) {
1029 /* If the numlock state needs to change then simulate an additional
1030 keypress before sending this one. This will happen if the user
1031 toggles numlock away from the VNC window.
1033 if (keysym_is_numlock(vs->kbd_layout, sym & 0xFFFF)) {
1034 if (!vs->modifiers_state[0x45]) {
1035 vs->modifiers_state[0x45] = 1;
1036 press_key(vs, 0xff7f);
1039 if (vs->modifiers_state[0x45]) {
1040 vs->modifiers_state[0x45] = 0;
1041 press_key(vs, 0xff7f);
1046 if (is_graphic_console()) {
1048 kbd_put_keycode(0xe0);
1050 kbd_put_keycode(keycode & 0x7f);
1052 kbd_put_keycode(keycode | 0x80);
1054 /* QEMU console emulation */
1057 case 0x2a: /* Left Shift */
1058 case 0x36: /* Right Shift */
1059 case 0x1d: /* Left CTRL */
1060 case 0x9d: /* Right CTRL */
1061 case 0x38: /* Left ALT */
1062 case 0xb8: /* Right ALT */
1065 kbd_put_keysym(QEMU_KEY_UP);
1068 kbd_put_keysym(QEMU_KEY_DOWN);
1071 kbd_put_keysym(QEMU_KEY_LEFT);
1074 kbd_put_keysym(QEMU_KEY_RIGHT);
1077 kbd_put_keysym(QEMU_KEY_DELETE);
1080 kbd_put_keysym(QEMU_KEY_HOME);
1083 kbd_put_keysym(QEMU_KEY_END);
1086 kbd_put_keysym(QEMU_KEY_PAGEUP);
1089 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1092 kbd_put_keysym(sym);
1099 static void key_event(VncState *vs, int down, uint32_t sym)
1103 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1104 sym = sym - 'A' + 'a';
1106 keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
1107 do_key_event(vs, down, keycode, sym);
1110 static void ext_key_event(VncState *vs, int down,
1111 uint32_t sym, uint16_t keycode)
1113 /* if the user specifies a keyboard layout, always use it */
1114 if (keyboard_layout)
1115 key_event(vs, down, sym);
1117 do_key_event(vs, down, keycode, sym);
1120 static void framebuffer_update_request(VncState *vs, int incremental,
1121 int x_position, int y_position,
1124 if (x_position > ds_get_width(vs->ds))
1125 x_position = ds_get_width(vs->ds);
1126 if (y_position > ds_get_height(vs->ds))
1127 y_position = ds_get_height(vs->ds);
1128 if (x_position + w >= ds_get_width(vs->ds))
1129 w = ds_get_width(vs->ds) - x_position;
1130 if (y_position + h >= ds_get_height(vs->ds))
1131 h = ds_get_height(vs->ds) - y_position;
1134 vs->need_update = 1;
1136 char *old_row = vs->old_data + y_position * ds_get_linesize(vs->ds);
1138 for (i = 0; i < h; i++) {
1139 vnc_set_bits(vs->dirty_row[y_position + i],
1140 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1141 memset(old_row, 42, ds_get_width(vs->ds) * ds_get_bytes_per_pixel(vs->ds));
1142 old_row += ds_get_linesize(vs->ds);
1147 static void send_ext_key_event_ack(VncState *vs)
1149 vnc_write_u8(vs, 0);
1150 vnc_write_u8(vs, 0);
1151 vnc_write_u16(vs, 1);
1152 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1153 VNC_ENCODING_EXT_KEY_EVENT);
1157 static void send_ext_audio_ack(VncState *vs)
1159 vnc_write_u8(vs, 0);
1160 vnc_write_u8(vs, 0);
1161 vnc_write_u16(vs, 1);
1162 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1163 VNC_ENCODING_AUDIO);
1167 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1170 unsigned int enc = 0;
1173 vs->vnc_encoding = 0;
1174 vs->tight_compression = 9;
1175 vs->tight_quality = 9;
1177 dcl->dpy_copy = NULL;
1179 for (i = n_encodings - 1; i >= 0; i--) {
1182 case VNC_ENCODING_RAW:
1183 vs->vnc_encoding = enc;
1185 case VNC_ENCODING_COPYRECT:
1186 dcl->dpy_copy = vnc_copy;
1188 case VNC_ENCODING_HEXTILE:
1189 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1190 vs->vnc_encoding = enc;
1192 case VNC_ENCODING_DESKTOPRESIZE:
1193 vs->features |= VNC_FEATURE_RESIZE_MASK;
1195 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1196 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1198 case VNC_ENCODING_EXT_KEY_EVENT:
1199 send_ext_key_event_ack(vs);
1201 case VNC_ENCODING_AUDIO:
1202 send_ext_audio_ack(vs);
1204 case VNC_ENCODING_WMVi:
1205 vs->features |= VNC_FEATURE_WMVI_MASK;
1207 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1208 vs->tight_compression = (enc & 0x0F);
1210 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1211 vs->tight_quality = (enc & 0x0F);
1214 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1219 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1222 static void set_pixel_conversion(VncState *vs)
1224 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1225 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1226 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1227 vs->write_pixels = vnc_write_pixels_copy;
1228 switch (vs->ds->surface->pf.bits_per_pixel) {
1230 vs->send_hextile_tile = send_hextile_tile_8;
1233 vs->send_hextile_tile = send_hextile_tile_16;
1236 vs->send_hextile_tile = send_hextile_tile_32;
1240 vs->write_pixels = vnc_write_pixels_generic;
1241 switch (vs->ds->surface->pf.bits_per_pixel) {
1243 vs->send_hextile_tile = send_hextile_tile_generic_8;
1246 vs->send_hextile_tile = send_hextile_tile_generic_16;
1249 vs->send_hextile_tile = send_hextile_tile_generic_32;
1255 static void set_pixel_format(VncState *vs,
1256 int bits_per_pixel, int depth,
1257 int big_endian_flag, int true_color_flag,
1258 int red_max, int green_max, int blue_max,
1259 int red_shift, int green_shift, int blue_shift)
1261 if (!true_color_flag) {
1262 vnc_client_error(vs);
1266 vs->clientds = vs->serverds;
1267 vs->clientds.pf.rmax = red_max;
1268 count_bits(vs->clientds.pf.rbits, red_max);
1269 vs->clientds.pf.rshift = red_shift;
1270 vs->clientds.pf.rmask = red_max << red_shift;
1271 vs->clientds.pf.gmax = green_max;
1272 count_bits(vs->clientds.pf.gbits, green_max);
1273 vs->clientds.pf.gshift = green_shift;
1274 vs->clientds.pf.gmask = green_max << green_shift;
1275 vs->clientds.pf.bmax = blue_max;
1276 count_bits(vs->clientds.pf.bbits, blue_max);
1277 vs->clientds.pf.bshift = blue_shift;
1278 vs->clientds.pf.bmask = blue_max << blue_shift;
1279 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1280 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1281 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1282 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1284 set_pixel_conversion(vs);
1286 vga_hw_invalidate();
1290 static void pixel_format_message (VncState *vs) {
1291 char pad[3] = { 0, 0, 0 };
1293 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1294 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1296 #ifdef WORDS_BIGENDIAN
1297 vnc_write_u8(vs, 1); /* big-endian-flag */
1299 vnc_write_u8(vs, 0); /* big-endian-flag */
1301 vnc_write_u8(vs, 1); /* true-color-flag */
1302 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1303 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1304 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1305 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1306 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1307 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1308 if (vs->ds->surface->pf.bits_per_pixel == 32)
1309 vs->send_hextile_tile = send_hextile_tile_32;
1310 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1311 vs->send_hextile_tile = send_hextile_tile_16;
1312 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1313 vs->send_hextile_tile = send_hextile_tile_8;
1314 vs->clientds = *(vs->ds->surface);
1315 vs->clientds.flags |= ~QEMU_ALLOCATED_FLAG;
1316 vs->write_pixels = vnc_write_pixels_copy;
1318 vnc_write(vs, pad, 3); /* padding */
1321 static void vnc_dpy_setdata(DisplayState *ds)
1323 /* We don't have to do anything */
1326 static void vnc_colordepth(DisplayState *ds)
1328 struct VncState *vs = ds->opaque;
1330 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1331 /* Sending a WMVi message to notify the client*/
1332 vnc_write_u8(vs, 0); /* msg id */
1333 vnc_write_u8(vs, 0);
1334 vnc_write_u16(vs, 1); /* number of rects */
1335 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
1337 pixel_format_message(vs);
1340 set_pixel_conversion(vs);
1344 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1354 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1355 read_u8(data, 6), read_u8(data, 7),
1356 read_u16(data, 8), read_u16(data, 10),
1357 read_u16(data, 12), read_u8(data, 14),
1358 read_u8(data, 15), read_u8(data, 16));
1365 limit = read_u16(data, 2);
1367 return 4 + (limit * 4);
1369 limit = read_u16(data, 2);
1371 for (i = 0; i < limit; i++) {
1372 int32_t val = read_s32(data, 4 + (i * 4));
1373 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1376 set_encodings(vs, (int32_t *)(data + 4), limit);
1382 framebuffer_update_request(vs,
1383 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1384 read_u16(data, 6), read_u16(data, 8));
1390 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1396 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1403 uint32_t dlen = read_u32(data, 4);
1408 client_cut_text(vs, read_u32(data, 4), data + 8);
1414 switch (read_u8(data, 1)) {
1419 ext_key_event(vs, read_u16(data, 2),
1420 read_u32(data, 4), read_u32(data, 8));
1426 switch (read_u16 (data, 2)) {
1436 switch (read_u8(data, 4)) {
1437 case 0: vs->as.fmt = AUD_FMT_U8; break;
1438 case 1: vs->as.fmt = AUD_FMT_S8; break;
1439 case 2: vs->as.fmt = AUD_FMT_U16; break;
1440 case 3: vs->as.fmt = AUD_FMT_S16; break;
1441 case 4: vs->as.fmt = AUD_FMT_U32; break;
1442 case 5: vs->as.fmt = AUD_FMT_S32; break;
1444 printf("Invalid audio format %d\n", read_u8(data, 4));
1445 vnc_client_error(vs);
1448 vs->as.nchannels = read_u8(data, 5);
1449 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1450 printf("Invalid audio channel coount %d\n",
1452 vnc_client_error(vs);
1455 vs->as.freq = read_u32(data, 6);
1458 printf ("Invalid audio message %d\n", read_u8(data, 4));
1459 vnc_client_error(vs);
1465 printf("Msg: %d\n", read_u16(data, 0));
1466 vnc_client_error(vs);
1471 printf("Msg: %d\n", data[0]);
1472 vnc_client_error(vs);
1476 vnc_read_when(vs, protocol_client_msg, 1);
1480 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1485 vnc_write_u16(vs, ds_get_width(vs->ds));
1486 vnc_write_u16(vs, ds_get_height(vs->ds));
1488 pixel_format_message(vs);
1491 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1493 size = snprintf(buf, sizeof(buf), "QEMU");
1495 vnc_write_u32(vs, size);
1496 vnc_write(vs, buf, size);
1499 vnc_read_when(vs, protocol_client_msg, 1);
1504 static void make_challenge(VncState *vs)
1508 srand(time(NULL)+getpid()+getpid()*987654+rand());
1510 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1511 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1514 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1516 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1518 unsigned char key[8];
1520 if (!vs->password || !vs->password[0]) {
1521 VNC_DEBUG("No password configured on server");
1522 vnc_write_u32(vs, 1); /* Reject auth */
1523 if (vs->minor >= 8) {
1524 static const char err[] = "Authentication failed";
1525 vnc_write_u32(vs, sizeof(err));
1526 vnc_write(vs, err, sizeof(err));
1529 vnc_client_error(vs);
1533 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1535 /* Calculate the expected challenge response */
1536 pwlen = strlen(vs->password);
1537 for (i=0; i<sizeof(key); i++)
1538 key[i] = i<pwlen ? vs->password[i] : 0;
1540 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1541 des(response+j, response+j);
1543 /* Compare expected vs actual challenge response */
1544 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1545 VNC_DEBUG("Client challenge reponse did not match\n");
1546 vnc_write_u32(vs, 1); /* Reject auth */
1547 if (vs->minor >= 8) {
1548 static const char err[] = "Authentication failed";
1549 vnc_write_u32(vs, sizeof(err));
1550 vnc_write(vs, err, sizeof(err));
1553 vnc_client_error(vs);
1555 VNC_DEBUG("Accepting VNC challenge response\n");
1556 vnc_write_u32(vs, 0); /* Accept auth */
1559 vnc_read_when(vs, protocol_client_init, 1);
1564 static int start_auth_vnc(VncState *vs)
1567 /* Send client a 'random' challenge */
1568 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1571 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1576 #ifdef CONFIG_VNC_TLS
1577 #define DH_BITS 1024
1578 static gnutls_dh_params_t dh_params;
1580 static int vnc_tls_initialize(void)
1582 static int tlsinitialized = 0;
1587 if (gnutls_global_init () < 0)
1590 /* XXX ought to re-generate diffie-hellmen params periodically */
1591 if (gnutls_dh_params_init (&dh_params) < 0)
1593 if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1596 #if defined(_VNC_DEBUG) && _VNC_DEBUG >= 2
1597 gnutls_global_set_log_level(10);
1598 gnutls_global_set_log_function(vnc_debug_gnutls_log);
1606 static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1608 gnutls_anon_server_credentials anon_cred;
1611 if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1612 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1616 gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1622 static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1624 gnutls_certificate_credentials_t x509_cred;
1627 if (!vs->x509cacert) {
1628 VNC_DEBUG("No CA x509 certificate specified\n");
1631 if (!vs->x509cert) {
1632 VNC_DEBUG("No server x509 certificate specified\n");
1636 VNC_DEBUG("No server private key specified\n");
1640 if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1641 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1644 if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1646 GNUTLS_X509_FMT_PEM)) < 0) {
1647 VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1648 gnutls_certificate_free_credentials(x509_cred);
1652 if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1655 GNUTLS_X509_FMT_PEM)) < 0) {
1656 VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1657 gnutls_certificate_free_credentials(x509_cred);
1661 if (vs->x509cacrl) {
1662 if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1664 GNUTLS_X509_FMT_PEM)) < 0) {
1665 VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
1666 gnutls_certificate_free_credentials(x509_cred);
1671 gnutls_certificate_set_dh_params (x509_cred, dh_params);
1676 static int vnc_validate_certificate(struct VncState *vs)
1679 unsigned int status;
1680 const gnutls_datum_t *certs;
1681 unsigned int nCerts, i;
1684 VNC_DEBUG("Validating client certificate\n");
1685 if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
1686 VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
1690 if ((now = time(NULL)) == ((time_t)-1)) {
1695 if (status & GNUTLS_CERT_INVALID)
1696 VNC_DEBUG("The certificate is not trusted.\n");
1698 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1699 VNC_DEBUG("The certificate hasn't got a known issuer.\n");
1701 if (status & GNUTLS_CERT_REVOKED)
1702 VNC_DEBUG("The certificate has been revoked.\n");
1704 if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1705 VNC_DEBUG("The certificate uses an insecure algorithm\n");
1709 VNC_DEBUG("Certificate is valid!\n");
1712 /* Only support x509 for now */
1713 if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
1716 if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
1719 for (i = 0 ; i < nCerts ; i++) {
1720 gnutls_x509_crt_t cert;
1721 VNC_DEBUG ("Checking certificate chain %d\n", i);
1722 if (gnutls_x509_crt_init (&cert) < 0)
1725 if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1726 gnutls_x509_crt_deinit (cert);
1730 if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1731 VNC_DEBUG("The certificate has expired\n");
1732 gnutls_x509_crt_deinit (cert);
1736 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1737 VNC_DEBUG("The certificate is not yet activated\n");
1738 gnutls_x509_crt_deinit (cert);
1742 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1743 VNC_DEBUG("The certificate is not yet activated\n");
1744 gnutls_x509_crt_deinit (cert);
1748 gnutls_x509_crt_deinit (cert);
1755 static int start_auth_vencrypt_subauth(VncState *vs)
1757 switch (vs->subauth) {
1758 case VNC_AUTH_VENCRYPT_TLSNONE:
1759 case VNC_AUTH_VENCRYPT_X509NONE:
1760 VNC_DEBUG("Accept TLS auth none\n");
1761 vnc_write_u32(vs, 0); /* Accept auth completion */
1762 vnc_read_when(vs, protocol_client_init, 1);
1765 case VNC_AUTH_VENCRYPT_TLSVNC:
1766 case VNC_AUTH_VENCRYPT_X509VNC:
1767 VNC_DEBUG("Start TLS auth VNC\n");
1768 return start_auth_vnc(vs);
1770 default: /* Should not be possible, but just in case */
1771 VNC_DEBUG("Reject auth %d\n", vs->auth);
1772 vnc_write_u8(vs, 1);
1773 if (vs->minor >= 8) {
1774 static const char err[] = "Unsupported authentication type";
1775 vnc_write_u32(vs, sizeof(err));
1776 vnc_write(vs, err, sizeof(err));
1778 vnc_client_error(vs);
1784 static void vnc_handshake_io(void *opaque);
1786 static int vnc_continue_handshake(struct VncState *vs) {
1789 if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1790 if (!gnutls_error_is_fatal(ret)) {
1791 VNC_DEBUG("Handshake interrupted (blocking)\n");
1792 if (!gnutls_record_get_direction(vs->tls_session))
1793 qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1795 qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1798 VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1799 vnc_client_error(vs);
1803 if (vs->x509verify) {
1804 if (vnc_validate_certificate(vs) < 0) {
1805 VNC_DEBUG("Client verification failed\n");
1806 vnc_client_error(vs);
1809 VNC_DEBUG("Client verification passed\n");
1813 VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1814 vs->wiremode = VNC_WIREMODE_TLS;
1815 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1817 return start_auth_vencrypt_subauth(vs);
1820 static void vnc_handshake_io(void *opaque) {
1821 struct VncState *vs = (struct VncState *)opaque;
1823 VNC_DEBUG("Handshake IO continue\n");
1824 vnc_continue_handshake(vs);
1827 #define NEED_X509_AUTH(vs) \
1828 ((vs)->subauth == VNC_AUTH_VENCRYPT_X509NONE || \
1829 (vs)->subauth == VNC_AUTH_VENCRYPT_X509VNC || \
1830 (vs)->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
1833 static int vnc_start_tls(struct VncState *vs) {
1834 static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
1835 static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
1836 static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
1837 static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
1839 VNC_DEBUG("Do TLS setup\n");
1840 if (vnc_tls_initialize() < 0) {
1841 VNC_DEBUG("Failed to init TLS\n");
1842 vnc_client_error(vs);
1845 if (vs->tls_session == NULL) {
1846 if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
1847 vnc_client_error(vs);
1851 if (gnutls_set_default_priority(vs->tls_session) < 0) {
1852 gnutls_deinit(vs->tls_session);
1853 vs->tls_session = NULL;
1854 vnc_client_error(vs);
1858 if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
1859 gnutls_deinit(vs->tls_session);
1860 vs->tls_session = NULL;
1861 vnc_client_error(vs);
1865 if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
1866 gnutls_deinit(vs->tls_session);
1867 vs->tls_session = NULL;
1868 vnc_client_error(vs);
1872 if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
1873 gnutls_deinit(vs->tls_session);
1874 vs->tls_session = NULL;
1875 vnc_client_error(vs);
1879 if (NEED_X509_AUTH(vs)) {
1880 gnutls_certificate_server_credentials x509_cred = vnc_tls_initialize_x509_cred(vs);
1882 gnutls_deinit(vs->tls_session);
1883 vs->tls_session = NULL;
1884 vnc_client_error(vs);
1887 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {
1888 gnutls_deinit(vs->tls_session);
1889 vs->tls_session = NULL;
1890 gnutls_certificate_free_credentials(x509_cred);
1891 vnc_client_error(vs);
1894 if (vs->x509verify) {
1895 VNC_DEBUG("Requesting a client certificate\n");
1896 gnutls_certificate_server_set_request (vs->tls_session, GNUTLS_CERT_REQUEST);
1900 gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
1902 gnutls_deinit(vs->tls_session);
1903 vs->tls_session = NULL;
1904 vnc_client_error(vs);
1907 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
1908 gnutls_deinit(vs->tls_session);
1909 vs->tls_session = NULL;
1910 gnutls_anon_free_server_credentials(anon_cred);
1911 vnc_client_error(vs);
1916 gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
1917 gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
1918 gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
1921 VNC_DEBUG("Start TLS handshake process\n");
1922 return vnc_continue_handshake(vs);
1925 static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)
1927 int auth = read_u32(data, 0);
1929 if (auth != vs->subauth) {
1930 VNC_DEBUG("Rejecting auth %d\n", auth);
1931 vnc_write_u8(vs, 0); /* Reject auth */
1933 vnc_client_error(vs);
1935 VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
1936 vnc_write_u8(vs, 1); /* Accept auth */
1939 if (vnc_start_tls(vs) < 0) {
1940 VNC_DEBUG("Failed to complete TLS\n");
1944 if (vs->wiremode == VNC_WIREMODE_TLS) {
1945 VNC_DEBUG("Starting VeNCrypt subauth\n");
1946 return start_auth_vencrypt_subauth(vs);
1948 VNC_DEBUG("TLS handshake blocked\n");
1955 static int protocol_client_vencrypt_init(VncState *vs, uint8_t *data, size_t len)
1959 VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
1960 vnc_write_u8(vs, 1); /* Reject version */
1962 vnc_client_error(vs);
1964 VNC_DEBUG("Sending allowed auth %d\n", vs->subauth);
1965 vnc_write_u8(vs, 0); /* Accept version */
1966 vnc_write_u8(vs, 1); /* Number of sub-auths */
1967 vnc_write_u32(vs, vs->subauth); /* The supported auth */
1969 vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
1974 static int start_auth_vencrypt(VncState *vs)
1976 /* Send VeNCrypt version 0.2 */
1977 vnc_write_u8(vs, 0);
1978 vnc_write_u8(vs, 2);
1980 vnc_read_when(vs, protocol_client_vencrypt_init, 2);
1983 #endif /* CONFIG_VNC_TLS */
1985 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
1987 /* We only advertise 1 auth scheme at a time, so client
1988 * must pick the one we sent. Verify this */
1989 if (data[0] != vs->auth) { /* Reject auth */
1990 VNC_DEBUG("Reject auth %d\n", (int)data[0]);
1991 vnc_write_u32(vs, 1);
1992 if (vs->minor >= 8) {
1993 static const char err[] = "Authentication failed";
1994 vnc_write_u32(vs, sizeof(err));
1995 vnc_write(vs, err, sizeof(err));
1997 vnc_client_error(vs);
1998 } else { /* Accept requested auth */
1999 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2002 VNC_DEBUG("Accept auth none\n");
2003 if (vs->minor >= 8) {
2004 vnc_write_u32(vs, 0); /* Accept auth completion */
2007 vnc_read_when(vs, protocol_client_init, 1);
2011 VNC_DEBUG("Start VNC auth\n");
2012 return start_auth_vnc(vs);
2014 #ifdef CONFIG_VNC_TLS
2015 case VNC_AUTH_VENCRYPT:
2016 VNC_DEBUG("Accept VeNCrypt auth\n");;
2017 return start_auth_vencrypt(vs);
2018 #endif /* CONFIG_VNC_TLS */
2020 default: /* Should not be possible, but just in case */
2021 VNC_DEBUG("Reject auth %d\n", vs->auth);
2022 vnc_write_u8(vs, 1);
2023 if (vs->minor >= 8) {
2024 static const char err[] = "Authentication failed";
2025 vnc_write_u32(vs, sizeof(err));
2026 vnc_write(vs, err, sizeof(err));
2028 vnc_client_error(vs);
2034 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2038 memcpy(local, version, 12);
2041 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2042 VNC_DEBUG("Malformed protocol version %s\n", local);
2043 vnc_client_error(vs);
2046 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2047 if (vs->major != 3 ||
2053 VNC_DEBUG("Unsupported client version\n");
2054 vnc_write_u32(vs, VNC_AUTH_INVALID);
2056 vnc_client_error(vs);
2059 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2060 * as equivalent to v3.3 by servers
2062 if (vs->minor == 4 || vs->minor == 5)
2065 if (vs->minor == 3) {
2066 if (vs->auth == VNC_AUTH_NONE) {
2067 VNC_DEBUG("Tell client auth none\n");
2068 vnc_write_u32(vs, vs->auth);
2070 vnc_read_when(vs, protocol_client_init, 1);
2071 } else if (vs->auth == VNC_AUTH_VNC) {
2072 VNC_DEBUG("Tell client VNC auth\n");
2073 vnc_write_u32(vs, vs->auth);
2077 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2078 vnc_write_u32(vs, VNC_AUTH_INVALID);
2080 vnc_client_error(vs);
2083 VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2084 vnc_write_u8(vs, 1); /* num auth */
2085 vnc_write_u8(vs, vs->auth);
2086 vnc_read_when(vs, protocol_client_auth, 1);
2093 static void vnc_connect(VncState *vs)
2095 VNC_DEBUG("New client on socket %d\n", vs->csock);
2097 socket_set_nonblock(vs->csock);
2098 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2099 vnc_write(vs, "RFB 003.008\n", 12);
2101 vnc_read_when(vs, protocol_version, 12);
2102 memset(vs->old_data, 0, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
2103 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
2105 dcl->dpy_copy = NULL;
2106 vnc_update_client(vs);
2110 static void vnc_listen_read(void *opaque)
2112 VncState *vs = opaque;
2113 struct sockaddr_in addr;
2114 socklen_t addrlen = sizeof(addr);
2119 vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2120 if (vs->csock != -1) {
2125 void vnc_display_init(DisplayState *ds)
2129 vs = qemu_mallocz(sizeof(VncState));
2130 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2138 vs->password = NULL;
2147 if (keyboard_layout)
2148 vs->kbd_layout = init_keyboard_layout(keyboard_layout);
2150 vs->kbd_layout = init_keyboard_layout("en-us");
2152 if (!vs->kbd_layout)
2155 vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
2157 dcl->dpy_update = vnc_dpy_update;
2158 dcl->dpy_resize = vnc_dpy_resize;
2159 dcl->dpy_setdata = vnc_dpy_setdata;
2160 dcl->dpy_refresh = NULL;
2161 register_displaychangelistener(ds, dcl);
2163 vs->as.freq = 44100;
2164 vs->as.nchannels = 2;
2165 vs->as.fmt = AUD_FMT_S16;
2166 vs->as.endianness = 0;
2169 #ifdef CONFIG_VNC_TLS
2170 static int vnc_set_x509_credential(VncState *vs,
2171 const char *certdir,
2172 const char *filename,
2183 if (!(*cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2)))
2186 strcpy(*cred, certdir);
2188 strcat(*cred, filename);
2190 VNC_DEBUG("Check %s\n", *cred);
2191 if (stat(*cred, &sb) < 0) {
2194 if (ignoreMissing && errno == ENOENT)
2202 static int vnc_set_x509_credential_dir(VncState *vs,
2203 const char *certdir)
2205 if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)
2207 if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)
2209 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)
2211 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)
2217 qemu_free(vs->x509cacert);
2218 qemu_free(vs->x509cacrl);
2219 qemu_free(vs->x509cert);
2220 qemu_free(vs->x509key);
2221 vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2224 #endif /* CONFIG_VNC_TLS */
2226 void vnc_display_close(DisplayState *ds)
2228 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2231 qemu_free(vs->display);
2234 if (vs->lsock != -1) {
2235 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2239 if (vs->csock != -1) {
2240 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
2241 closesocket(vs->csock);
2243 buffer_reset(&vs->input);
2244 buffer_reset(&vs->output);
2245 vs->need_update = 0;
2246 #ifdef CONFIG_VNC_TLS
2247 if (vs->tls_session) {
2248 gnutls_deinit(vs->tls_session);
2249 vs->tls_session = NULL;
2251 vs->wiremode = VNC_WIREMODE_CLEAR;
2252 #endif /* CONFIG_VNC_TLS */
2254 vs->auth = VNC_AUTH_INVALID;
2255 #ifdef CONFIG_VNC_TLS
2256 vs->subauth = VNC_AUTH_INVALID;
2262 int vnc_display_password(DisplayState *ds, const char *password)
2264 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2267 qemu_free(vs->password);
2268 vs->password = NULL;
2270 if (password && password[0]) {
2271 if (!(vs->password = qemu_strdup(password)))
2278 int vnc_display_open(DisplayState *ds, const char *display)
2280 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2281 const char *options;
2285 #ifdef CONFIG_VNC_TLS
2286 int tls = 0, x509 = 0;
2289 vnc_display_close(ds);
2290 if (strcmp(display, "none") == 0)
2293 if (!(vs->display = strdup(display)))
2297 while ((options = strchr(options, ','))) {
2299 if (strncmp(options, "password", 8) == 0) {
2300 password = 1; /* Require password auth */
2301 } else if (strncmp(options, "reverse", 7) == 0) {
2303 } else if (strncmp(options, "to=", 3) == 0) {
2304 to_port = atoi(options+3) + 5900;
2305 #ifdef CONFIG_VNC_TLS
2306 } else if (strncmp(options, "tls", 3) == 0) {
2307 tls = 1; /* Require TLS */
2308 } else if (strncmp(options, "x509", 4) == 0) {
2310 x509 = 1; /* Require x509 certificates */
2311 if (strncmp(options, "x509verify", 10) == 0)
2312 vs->x509verify = 1; /* ...and verify client certs */
2314 /* Now check for 'x509=/some/path' postfix
2315 * and use that to setup x509 certificate/key paths */
2316 start = strchr(options, '=');
2317 end = strchr(options, ',');
2318 if (start && (!end || (start < end))) {
2319 int len = end ? end-(start+1) : strlen(start+1);
2320 char *path = qemu_strndup(start + 1, len);
2322 VNC_DEBUG("Trying certificate path '%s'\n", path);
2323 if (vnc_set_x509_credential_dir(vs, path) < 0) {
2324 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2326 qemu_free(vs->display);
2332 fprintf(stderr, "No certificate path provided\n");
2333 qemu_free(vs->display);
2342 #ifdef CONFIG_VNC_TLS
2344 vs->auth = VNC_AUTH_VENCRYPT;
2346 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2347 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2349 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2350 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2354 VNC_DEBUG("Initializing VNC server with password auth\n");
2355 vs->auth = VNC_AUTH_VNC;
2356 #ifdef CONFIG_VNC_TLS
2357 vs->subauth = VNC_AUTH_INVALID;
2361 #ifdef CONFIG_VNC_TLS
2363 vs->auth = VNC_AUTH_VENCRYPT;
2365 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2366 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2368 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2369 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2373 VNC_DEBUG("Initializing VNC server with no auth\n");
2374 vs->auth = VNC_AUTH_NONE;
2375 #ifdef CONFIG_VNC_TLS
2376 vs->subauth = VNC_AUTH_INVALID;
2382 /* connect to viewer */
2383 if (strncmp(display, "unix:", 5) == 0)
2384 vs->lsock = unix_connect(display+5);
2386 vs->lsock = inet_connect(display, SOCK_STREAM);
2387 if (-1 == vs->lsock) {
2392 vs->csock = vs->lsock;
2399 /* listen for connects */
2401 dpy = qemu_malloc(256);
2402 if (strncmp(display, "unix:", 5) == 0) {
2403 pstrcpy(dpy, 256, "unix:");
2404 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2406 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2408 if (-1 == vs->lsock) {
2417 return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);