2 * QEMU VNC display driver
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];
112 #ifdef CONFIG_VNC_TLS
121 char challenge[VNC_AUTH_CHALLENGE_SIZE];
123 #ifdef CONFIG_VNC_TLS
125 gnutls_session_t tls_session;
130 kbd_layout_t *kbd_layout;
131 /* current output mode information */
132 VncWritePixels *write_pixels;
133 VncSendHextileTile *send_hextile_tile;
134 DisplaySurface clientds, serverds;
136 CaptureVoiceOut *audio_cap;
137 struct audsettings as;
139 VncReadEvent *read_handler;
140 size_t read_handler_expect;
142 uint8_t modifiers_state[256];
145 static VncState *vnc_state; /* needed for info vnc */
146 static DisplayChangeListener *dcl;
148 void do_info_vnc(void)
150 if (vnc_state == NULL || vnc_state->display == NULL)
151 term_printf("VNC server disabled\n");
153 term_printf("VNC server active on: ");
154 term_print_filename(vnc_state->display);
157 if (vnc_state->csock == -1)
158 term_printf("No client connected\n");
160 term_printf("Client connected\n");
164 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
165 return (vs->features & (1 << feature));
169 1) Get the queue working for IO.
170 2) there is some weirdness when using the -S option (the screen is grey
171 and not totally invalidated
172 3) resolutions > 1024
175 static void vnc_write(VncState *vs, const void *data, size_t len);
176 static void vnc_write_u32(VncState *vs, uint32_t value);
177 static void vnc_write_s32(VncState *vs, int32_t value);
178 static void vnc_write_u16(VncState *vs, uint16_t value);
179 static void vnc_write_u8(VncState *vs, uint8_t value);
180 static void vnc_flush(VncState *vs);
181 static void vnc_update_client(void *opaque);
182 static void vnc_client_read(void *opaque);
184 static void vnc_colordepth(DisplayState *ds);
186 static inline void vnc_set_bit(uint32_t *d, int k)
188 d[k >> 5] |= 1 << (k & 0x1f);
191 static inline void vnc_clear_bit(uint32_t *d, int k)
193 d[k >> 5] &= ~(1 << (k & 0x1f));
196 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
206 d[j++] = (1 << n) - 1;
211 static inline int vnc_get_bit(const uint32_t *d, int k)
213 return (d[k >> 5] >> (k & 0x1f)) & 1;
216 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
220 for(i = 0; i < nb_words; i++) {
221 if ((d1[i] & d2[i]) != 0)
227 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
229 VncState *vs = ds->opaque;
234 /* round x down to ensure the loop only spans one 16-pixel block per,
235 iteration. otherwise, if (x % 16) != 0, the last iteration may span
236 two 16-pixel blocks but we only mark the first as dirty
241 x = MIN(x, vs->serverds.width);
242 y = MIN(y, vs->serverds.height);
243 w = MIN(x + w, vs->serverds.width) - x;
244 h = MIN(h, vs->serverds.height);
247 for (i = 0; i < w; i += 16)
248 vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
251 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
254 vnc_write_u16(vs, x);
255 vnc_write_u16(vs, y);
256 vnc_write_u16(vs, w);
257 vnc_write_u16(vs, h);
259 vnc_write_s32(vs, encoding);
262 static void vnc_dpy_resize(DisplayState *ds)
265 VncState *vs = ds->opaque;
267 vs->old_data = qemu_realloc(vs->old_data, ds_get_linesize(ds) * ds_get_height(ds));
269 if (vs->old_data == NULL) {
270 fprintf(stderr, "vnc: memory allocation failed\n");
274 if (ds_get_bytes_per_pixel(ds) != vs->serverds.pf.bytes_per_pixel)
275 console_color_init(ds);
277 size_changed = ds_get_width(ds) != vs->serverds.width ||
278 ds_get_height(ds) != vs->serverds.height;
279 vs->serverds = *(ds->surface);
281 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
282 vnc_write_u8(vs, 0); /* msg id */
284 vnc_write_u16(vs, 1); /* number of rects */
285 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
286 VNC_ENCODING_DESKTOPRESIZE);
291 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
292 memset(vs->old_data, 42, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
296 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
298 vnc_write(vs, pixels, size);
301 /* slowest but generic code. */
302 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
306 r = ((((v & vs->serverds.pf.rmask) >> vs->serverds.pf.rshift) << vs->clientds.pf.rbits) >>
307 vs->serverds.pf.rbits);
308 g = ((((v & vs->serverds.pf.gmask) >> vs->serverds.pf.gshift) << vs->clientds.pf.gbits) >>
309 vs->serverds.pf.gbits);
310 b = ((((v & vs->serverds.pf.bmask) >> vs->serverds.pf.bshift) << vs->clientds.pf.bbits) >>
311 vs->serverds.pf.bbits);
312 v = (r << vs->clientds.pf.rshift) |
313 (g << vs->clientds.pf.gshift) |
314 (b << vs->clientds.pf.bshift);
315 switch(vs->clientds.pf.bytes_per_pixel) {
320 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
330 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
345 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
349 if (vs->serverds.pf.bytes_per_pixel == 4) {
350 uint32_t *pixels = pixels1;
353 for(i = 0; i < n; i++) {
354 vnc_convert_pixel(vs, buf, pixels[i]);
355 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
357 } else if (vs->serverds.pf.bytes_per_pixel == 2) {
358 uint16_t *pixels = pixels1;
361 for(i = 0; i < n; i++) {
362 vnc_convert_pixel(vs, buf, pixels[i]);
363 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
365 } else if (vs->serverds.pf.bytes_per_pixel == 1) {
366 uint8_t *pixels = pixels1;
369 for(i = 0; i < n; i++) {
370 vnc_convert_pixel(vs, buf, pixels[i]);
371 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
374 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
378 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
383 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
385 row = ds_get_data(vs->ds) + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
386 for (i = 0; i < h; i++) {
387 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
388 row += ds_get_linesize(vs->ds);
392 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
394 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
395 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
399 #include "vnchextile.h"
403 #include "vnchextile.h"
407 #include "vnchextile.h"
412 #include "vnchextile.h"
418 #include "vnchextile.h"
424 #include "vnchextile.h"
428 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
432 uint8_t *last_fg, *last_bg;
434 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
436 last_fg = (uint8_t *) malloc(vs->serverds.pf.bytes_per_pixel);
437 last_bg = (uint8_t *) malloc(vs->serverds.pf.bytes_per_pixel);
439 for (j = y; j < (y + h); j += 16) {
440 for (i = x; i < (x + w); i += 16) {
441 vs->send_hextile_tile(vs, i, j,
442 MIN(16, x + w - i), MIN(16, y + h - j),
443 last_bg, last_fg, &has_bg, &has_fg);
451 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
453 if (vnc_has_feature(vs, VNC_FEATURE_HEXTILE))
454 send_framebuffer_update_hextile(vs, x, y, w, h);
456 send_framebuffer_update_raw(vs, x, y, w, h);
459 static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
461 VncState *vs = ds->opaque;
463 vnc_update_client(vs);
465 vnc_write_u8(vs, 0); /* msg id */
467 vnc_write_u16(vs, 1); /* number of rects */
468 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
469 vnc_write_u16(vs, src_x);
470 vnc_write_u16(vs, src_y);
474 static int find_dirty_height(VncState *vs, int y, int last_x, int x)
478 for (h = 1; h < (vs->serverds.height - y); h++) {
480 if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
482 for (tmp_x = last_x; tmp_x < x; tmp_x++)
483 vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
489 static void vnc_update_client(void *opaque)
491 VncState *vs = opaque;
493 if (vs->need_update && vs->csock != -1) {
497 uint32_t width_mask[VNC_DIRTY_WORDS];
504 vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
506 /* Walk through the dirty map and eliminate tiles that
507 really aren't dirty */
508 row = ds_get_data(vs->ds);
509 old_row = vs->old_data;
511 for (y = 0; y < ds_get_height(vs->ds); y++) {
512 if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
518 old_ptr = (char*)old_row;
520 for (x = 0; x < ds_get_width(vs->ds); x += 16) {
521 if (memcmp(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds)) == 0) {
522 vnc_clear_bit(vs->dirty_row[y], (x / 16));
525 memcpy(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds));
528 ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
529 old_ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
533 row += ds_get_linesize(vs->ds);
534 old_row += ds_get_linesize(vs->ds);
537 if (!has_dirty && !vs->audio_cap) {
538 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
542 /* Count rectangles */
544 vnc_write_u8(vs, 0); /* msg id */
546 saved_offset = vs->output.offset;
547 vnc_write_u16(vs, 0);
549 for (y = 0; y < vs->serverds.height; y++) {
552 for (x = 0; x < vs->serverds.width / 16; x++) {
553 if (vnc_get_bit(vs->dirty_row[y], x)) {
557 vnc_clear_bit(vs->dirty_row[y], x);
560 int h = find_dirty_height(vs, y, last_x, x);
561 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
568 int h = find_dirty_height(vs, y, last_x, x);
569 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
573 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
574 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
579 if (vs->csock != -1) {
580 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
585 static int vnc_listen_poll(void *opaque)
587 VncState *vs = opaque;
593 static void buffer_reserve(Buffer *buffer, size_t len)
595 if ((buffer->capacity - buffer->offset) < len) {
596 buffer->capacity += (len + 1024);
597 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
598 if (buffer->buffer == NULL) {
599 fprintf(stderr, "vnc: out of memory\n");
605 static int buffer_empty(Buffer *buffer)
607 return buffer->offset == 0;
610 static uint8_t *buffer_end(Buffer *buffer)
612 return buffer->buffer + buffer->offset;
615 static void buffer_reset(Buffer *buffer)
620 static void buffer_append(Buffer *buffer, const void *data, size_t len)
622 memcpy(buffer->buffer + buffer->offset, data, len);
623 buffer->offset += len;
627 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
629 VncState *vs = opaque;
632 case AUD_CNOTIFY_DISABLE:
633 vnc_write_u8(vs, 255);
635 vnc_write_u16(vs, 0);
639 case AUD_CNOTIFY_ENABLE:
640 vnc_write_u8(vs, 255);
642 vnc_write_u16(vs, 1);
648 static void audio_capture_destroy(void *opaque)
652 static void audio_capture(void *opaque, void *buf, int size)
654 VncState *vs = opaque;
656 vnc_write_u8(vs, 255);
658 vnc_write_u16(vs, 2);
659 vnc_write_u32(vs, size);
660 vnc_write(vs, buf, size);
664 static void audio_add(VncState *vs)
666 struct audio_capture_ops ops;
669 term_printf ("audio already running\n");
673 ops.notify = audio_capture_notify;
674 ops.destroy = audio_capture_destroy;
675 ops.capture = audio_capture;
677 vs->audio_cap = AUD_add_capture(NULL, &vs->as, &ops, vs);
678 if (!vs->audio_cap) {
679 term_printf ("Failed to add audio capture\n");
683 static void audio_del(VncState *vs)
686 AUD_del_capture(vs->audio_cap, vs);
687 vs->audio_cap = NULL;
691 static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
693 if (ret == 0 || ret == -1) {
695 switch (last_errno) {
707 VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
708 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
709 closesocket(vs->csock);
712 buffer_reset(&vs->input);
713 buffer_reset(&vs->output);
715 #ifdef CONFIG_VNC_TLS
716 if (vs->tls_session) {
717 gnutls_deinit(vs->tls_session);
718 vs->tls_session = NULL;
720 vs->wiremode = VNC_WIREMODE_CLEAR;
721 #endif /* CONFIG_VNC_TLS */
728 static void vnc_client_error(VncState *vs)
730 vnc_client_io_error(vs, -1, EINVAL);
733 static void vnc_client_write(void *opaque)
736 VncState *vs = opaque;
738 #ifdef CONFIG_VNC_TLS
739 if (vs->tls_session) {
740 ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
742 if (ret == GNUTLS_E_AGAIN)
749 #endif /* CONFIG_VNC_TLS */
750 ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
751 ret = vnc_client_io_error(vs, ret, socket_error());
755 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
756 vs->output.offset -= ret;
758 if (vs->output.offset == 0) {
759 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
763 static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
765 vs->read_handler = func;
766 vs->read_handler_expect = expecting;
769 static void vnc_client_read(void *opaque)
771 VncState *vs = opaque;
774 buffer_reserve(&vs->input, 4096);
776 #ifdef CONFIG_VNC_TLS
777 if (vs->tls_session) {
778 ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
780 if (ret == GNUTLS_E_AGAIN)
787 #endif /* CONFIG_VNC_TLS */
788 ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
789 ret = vnc_client_io_error(vs, ret, socket_error());
793 vs->input.offset += ret;
795 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
796 size_t len = vs->read_handler_expect;
799 ret = vs->read_handler(vs, vs->input.buffer, len);
804 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
805 vs->input.offset -= len;
807 vs->read_handler_expect = ret;
812 static void vnc_write(VncState *vs, const void *data, size_t len)
814 buffer_reserve(&vs->output, len);
816 if (buffer_empty(&vs->output)) {
817 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
820 buffer_append(&vs->output, data, len);
823 static void vnc_write_s32(VncState *vs, int32_t value)
825 vnc_write_u32(vs, *(uint32_t *)&value);
828 static void vnc_write_u32(VncState *vs, uint32_t value)
832 buf[0] = (value >> 24) & 0xFF;
833 buf[1] = (value >> 16) & 0xFF;
834 buf[2] = (value >> 8) & 0xFF;
835 buf[3] = value & 0xFF;
837 vnc_write(vs, buf, 4);
840 static void vnc_write_u16(VncState *vs, uint16_t value)
844 buf[0] = (value >> 8) & 0xFF;
845 buf[1] = value & 0xFF;
847 vnc_write(vs, buf, 2);
850 static void vnc_write_u8(VncState *vs, uint8_t value)
852 vnc_write(vs, (char *)&value, 1);
855 static void vnc_flush(VncState *vs)
857 if (vs->output.offset)
858 vnc_client_write(vs);
861 static uint8_t read_u8(uint8_t *data, size_t offset)
866 static uint16_t read_u16(uint8_t *data, size_t offset)
868 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
871 static int32_t read_s32(uint8_t *data, size_t offset)
873 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
874 (data[offset + 2] << 8) | data[offset + 3]);
877 static uint32_t read_u32(uint8_t *data, size_t offset)
879 return ((data[offset] << 24) | (data[offset + 1] << 16) |
880 (data[offset + 2] << 8) | data[offset + 3]);
883 #ifdef CONFIG_VNC_TLS
884 static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
887 struct VncState *vs = (struct VncState *)transport;
891 ret = send(vs->csock, data, len, 0);
901 static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
904 struct VncState *vs = (struct VncState *)transport;
908 ret = recv(vs->csock, data, len, 0);
916 #endif /* CONFIG_VNC_TLS */
918 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
922 static void check_pointer_type_change(VncState *vs, int absolute)
924 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
927 vnc_write_u16(vs, 1);
928 vnc_framebuffer_update(vs, absolute, 0,
929 ds_get_width(vs->ds), ds_get_height(vs->ds),
930 VNC_ENCODING_POINTER_TYPE_CHANGE);
933 vs->absolute = absolute;
936 static void pointer_event(VncState *vs, int button_mask, int x, int y)
941 if (button_mask & 0x01)
942 buttons |= MOUSE_EVENT_LBUTTON;
943 if (button_mask & 0x02)
944 buttons |= MOUSE_EVENT_MBUTTON;
945 if (button_mask & 0x04)
946 buttons |= MOUSE_EVENT_RBUTTON;
947 if (button_mask & 0x08)
949 if (button_mask & 0x10)
953 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
954 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
956 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
960 kbd_mouse_event(x, y, dz, buttons);
962 if (vs->last_x != -1)
963 kbd_mouse_event(x - vs->last_x,
970 check_pointer_type_change(vs, kbd_mouse_is_absolute());
973 static void reset_keys(VncState *vs)
976 for(i = 0; i < 256; i++) {
977 if (vs->modifiers_state[i]) {
979 kbd_put_keycode(0xe0);
980 kbd_put_keycode(i | 0x80);
981 vs->modifiers_state[i] = 0;
986 static void press_key(VncState *vs, int keysym)
988 kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) & 0x7f);
989 kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
992 static void do_key_event(VncState *vs, int down, int keycode, int sym)
994 /* QEMU console switch */
996 case 0x2a: /* Left Shift */
997 case 0x36: /* Right Shift */
998 case 0x1d: /* Left CTRL */
999 case 0x9d: /* Right CTRL */
1000 case 0x38: /* Left ALT */
1001 case 0xb8: /* Right ALT */
1003 vs->modifiers_state[keycode] = 1;
1005 vs->modifiers_state[keycode] = 0;
1007 case 0x02 ... 0x0a: /* '1' to '9' keys */
1008 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1009 /* Reset the modifiers sent to the current console */
1011 console_select(keycode - 0x02);
1015 case 0x3a: /* CapsLock */
1016 case 0x45: /* NumLock */
1018 vs->modifiers_state[keycode] ^= 1;
1022 if (keycode_is_keypad(vs->kbd_layout, keycode)) {
1023 /* If the numlock state needs to change then simulate an additional
1024 keypress before sending this one. This will happen if the user
1025 toggles numlock away from the VNC window.
1027 if (keysym_is_numlock(vs->kbd_layout, sym & 0xFFFF)) {
1028 if (!vs->modifiers_state[0x45]) {
1029 vs->modifiers_state[0x45] = 1;
1030 press_key(vs, 0xff7f);
1033 if (vs->modifiers_state[0x45]) {
1034 vs->modifiers_state[0x45] = 0;
1035 press_key(vs, 0xff7f);
1040 if (is_graphic_console()) {
1042 kbd_put_keycode(0xe0);
1044 kbd_put_keycode(keycode & 0x7f);
1046 kbd_put_keycode(keycode | 0x80);
1048 /* QEMU console emulation */
1051 case 0x2a: /* Left Shift */
1052 case 0x36: /* Right Shift */
1053 case 0x1d: /* Left CTRL */
1054 case 0x9d: /* Right CTRL */
1055 case 0x38: /* Left ALT */
1056 case 0xb8: /* Right ALT */
1059 kbd_put_keysym(QEMU_KEY_UP);
1062 kbd_put_keysym(QEMU_KEY_DOWN);
1065 kbd_put_keysym(QEMU_KEY_LEFT);
1068 kbd_put_keysym(QEMU_KEY_RIGHT);
1071 kbd_put_keysym(QEMU_KEY_DELETE);
1074 kbd_put_keysym(QEMU_KEY_HOME);
1077 kbd_put_keysym(QEMU_KEY_END);
1080 kbd_put_keysym(QEMU_KEY_PAGEUP);
1083 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1086 kbd_put_keysym(sym);
1093 static void key_event(VncState *vs, int down, uint32_t sym)
1097 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1098 sym = sym - 'A' + 'a';
1100 keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
1101 do_key_event(vs, down, keycode, sym);
1104 static void ext_key_event(VncState *vs, int down,
1105 uint32_t sym, uint16_t keycode)
1107 /* if the user specifies a keyboard layout, always use it */
1108 if (keyboard_layout)
1109 key_event(vs, down, sym);
1111 do_key_event(vs, down, keycode, sym);
1114 static void framebuffer_update_request(VncState *vs, int incremental,
1115 int x_position, int y_position,
1118 if (x_position > ds_get_width(vs->ds))
1119 x_position = ds_get_width(vs->ds);
1120 if (y_position > ds_get_height(vs->ds))
1121 y_position = ds_get_height(vs->ds);
1122 if (x_position + w >= ds_get_width(vs->ds))
1123 w = ds_get_width(vs->ds) - x_position;
1124 if (y_position + h >= ds_get_height(vs->ds))
1125 h = ds_get_height(vs->ds) - y_position;
1128 vs->need_update = 1;
1130 char *old_row = vs->old_data + y_position * ds_get_linesize(vs->ds);
1132 for (i = 0; i < h; i++) {
1133 vnc_set_bits(vs->dirty_row[y_position + i],
1134 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1135 memset(old_row, 42, ds_get_width(vs->ds) * ds_get_bytes_per_pixel(vs->ds));
1136 old_row += ds_get_linesize(vs->ds);
1141 static void send_ext_key_event_ack(VncState *vs)
1143 vnc_write_u8(vs, 0);
1144 vnc_write_u8(vs, 0);
1145 vnc_write_u16(vs, 1);
1146 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1147 VNC_ENCODING_EXT_KEY_EVENT);
1151 static void send_ext_audio_ack(VncState *vs)
1153 vnc_write_u8(vs, 0);
1154 vnc_write_u8(vs, 0);
1155 vnc_write_u16(vs, 1);
1156 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1157 VNC_ENCODING_AUDIO);
1161 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1164 unsigned int enc = 0;
1168 dcl->dpy_copy = NULL;
1170 for (i = n_encodings - 1; i >= 0; i--) {
1173 case VNC_ENCODING_RAW:
1175 case VNC_ENCODING_COPYRECT:
1176 dcl->dpy_copy = vnc_copy;
1178 case VNC_ENCODING_HEXTILE:
1179 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1181 case VNC_ENCODING_DESKTOPRESIZE:
1182 vs->features |= VNC_FEATURE_RESIZE_MASK;
1184 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1185 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1187 case VNC_ENCODING_EXT_KEY_EVENT:
1188 send_ext_key_event_ack(vs);
1190 case VNC_ENCODING_AUDIO:
1191 send_ext_audio_ack(vs);
1193 case VNC_ENCODING_WMVi:
1194 vs->features |= VNC_FEATURE_WMVI_MASK;
1197 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1202 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1205 static void set_pixel_conversion(VncState *vs)
1207 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1208 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1209 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1210 vs->write_pixels = vnc_write_pixels_copy;
1211 switch (vs->ds->surface->pf.bits_per_pixel) {
1213 vs->send_hextile_tile = send_hextile_tile_8;
1216 vs->send_hextile_tile = send_hextile_tile_16;
1219 vs->send_hextile_tile = send_hextile_tile_32;
1223 vs->write_pixels = vnc_write_pixels_generic;
1224 switch (vs->ds->surface->pf.bits_per_pixel) {
1226 vs->send_hextile_tile = send_hextile_tile_generic_8;
1229 vs->send_hextile_tile = send_hextile_tile_generic_16;
1232 vs->send_hextile_tile = send_hextile_tile_generic_32;
1238 static void set_pixel_format(VncState *vs,
1239 int bits_per_pixel, int depth,
1240 int big_endian_flag, int true_color_flag,
1241 int red_max, int green_max, int blue_max,
1242 int red_shift, int green_shift, int blue_shift)
1244 if (!true_color_flag) {
1245 vnc_client_error(vs);
1249 vs->clientds = vs->serverds;
1250 vs->clientds.pf.rmax = red_max;
1251 count_bits(vs->clientds.pf.rbits, red_max);
1252 vs->clientds.pf.rshift = red_shift;
1253 vs->clientds.pf.rmask = red_max << red_shift;
1254 vs->clientds.pf.gmax = green_max;
1255 count_bits(vs->clientds.pf.gbits, green_max);
1256 vs->clientds.pf.gshift = green_shift;
1257 vs->clientds.pf.gmask = green_max << green_shift;
1258 vs->clientds.pf.bmax = blue_max;
1259 count_bits(vs->clientds.pf.bbits, blue_max);
1260 vs->clientds.pf.bshift = blue_shift;
1261 vs->clientds.pf.bmask = blue_max << blue_shift;
1262 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1263 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1264 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1265 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1267 set_pixel_conversion(vs);
1269 vga_hw_invalidate();
1273 static void pixel_format_message (VncState *vs) {
1274 char pad[3] = { 0, 0, 0 };
1276 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1277 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1279 #ifdef WORDS_BIGENDIAN
1280 vnc_write_u8(vs, 1); /* big-endian-flag */
1282 vnc_write_u8(vs, 0); /* big-endian-flag */
1284 vnc_write_u8(vs, 1); /* true-color-flag */
1285 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1286 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1287 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1288 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1289 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1290 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1291 if (vs->ds->surface->pf.bits_per_pixel == 32)
1292 vs->send_hextile_tile = send_hextile_tile_32;
1293 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1294 vs->send_hextile_tile = send_hextile_tile_16;
1295 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1296 vs->send_hextile_tile = send_hextile_tile_8;
1297 vs->clientds = *(vs->ds->surface);
1298 vs->clientds.flags |= ~QEMU_ALLOCATED_FLAG;
1299 vs->write_pixels = vnc_write_pixels_copy;
1301 vnc_write(vs, pad, 3); /* padding */
1304 static void vnc_dpy_setdata(DisplayState *ds)
1306 /* We don't have to do anything */
1309 static void vnc_colordepth(DisplayState *ds)
1311 struct VncState *vs = ds->opaque;
1313 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1314 /* Sending a WMVi message to notify the client*/
1315 vnc_write_u8(vs, 0); /* msg id */
1316 vnc_write_u8(vs, 0);
1317 vnc_write_u16(vs, 1); /* number of rects */
1318 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
1320 pixel_format_message(vs);
1323 set_pixel_conversion(vs);
1327 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1337 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1338 read_u8(data, 6), read_u8(data, 7),
1339 read_u16(data, 8), read_u16(data, 10),
1340 read_u16(data, 12), read_u8(data, 14),
1341 read_u8(data, 15), read_u8(data, 16));
1348 limit = read_u16(data, 2);
1350 return 4 + (limit * 4);
1352 limit = read_u16(data, 2);
1354 for (i = 0; i < limit; i++) {
1355 int32_t val = read_s32(data, 4 + (i * 4));
1356 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1359 set_encodings(vs, (int32_t *)(data + 4), limit);
1365 framebuffer_update_request(vs,
1366 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1367 read_u16(data, 6), read_u16(data, 8));
1373 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1379 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1386 uint32_t dlen = read_u32(data, 4);
1391 client_cut_text(vs, read_u32(data, 4), data + 8);
1397 switch (read_u8(data, 1)) {
1402 ext_key_event(vs, read_u16(data, 2),
1403 read_u32(data, 4), read_u32(data, 8));
1409 switch (read_u16 (data, 2)) {
1419 switch (read_u8(data, 4)) {
1420 case 0: vs->as.fmt = AUD_FMT_U8; break;
1421 case 1: vs->as.fmt = AUD_FMT_S8; break;
1422 case 2: vs->as.fmt = AUD_FMT_U16; break;
1423 case 3: vs->as.fmt = AUD_FMT_S16; break;
1424 case 4: vs->as.fmt = AUD_FMT_U32; break;
1425 case 5: vs->as.fmt = AUD_FMT_S32; break;
1427 printf("Invalid audio format %d\n", read_u8(data, 4));
1428 vnc_client_error(vs);
1431 vs->as.nchannels = read_u8(data, 5);
1432 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1433 printf("Invalid audio channel coount %d\n",
1435 vnc_client_error(vs);
1438 vs->as.freq = read_u32(data, 6);
1441 printf ("Invalid audio message %d\n", read_u8(data, 4));
1442 vnc_client_error(vs);
1448 printf("Msg: %d\n", read_u16(data, 0));
1449 vnc_client_error(vs);
1454 printf("Msg: %d\n", data[0]);
1455 vnc_client_error(vs);
1459 vnc_read_when(vs, protocol_client_msg, 1);
1463 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1468 vnc_write_u16(vs, ds_get_width(vs->ds));
1469 vnc_write_u16(vs, ds_get_height(vs->ds));
1471 pixel_format_message(vs);
1474 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1476 size = snprintf(buf, sizeof(buf), "QEMU");
1478 vnc_write_u32(vs, size);
1479 vnc_write(vs, buf, size);
1482 vnc_read_when(vs, protocol_client_msg, 1);
1487 static void make_challenge(VncState *vs)
1491 srand(time(NULL)+getpid()+getpid()*987654+rand());
1493 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1494 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1497 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1499 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1501 unsigned char key[8];
1503 if (!vs->password || !vs->password[0]) {
1504 VNC_DEBUG("No password configured on server");
1505 vnc_write_u32(vs, 1); /* Reject auth */
1506 if (vs->minor >= 8) {
1507 static const char err[] = "Authentication failed";
1508 vnc_write_u32(vs, sizeof(err));
1509 vnc_write(vs, err, sizeof(err));
1512 vnc_client_error(vs);
1516 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1518 /* Calculate the expected challenge response */
1519 pwlen = strlen(vs->password);
1520 for (i=0; i<sizeof(key); i++)
1521 key[i] = i<pwlen ? vs->password[i] : 0;
1523 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1524 des(response+j, response+j);
1526 /* Compare expected vs actual challenge response */
1527 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1528 VNC_DEBUG("Client challenge reponse did not match\n");
1529 vnc_write_u32(vs, 1); /* Reject auth */
1530 if (vs->minor >= 8) {
1531 static const char err[] = "Authentication failed";
1532 vnc_write_u32(vs, sizeof(err));
1533 vnc_write(vs, err, sizeof(err));
1536 vnc_client_error(vs);
1538 VNC_DEBUG("Accepting VNC challenge response\n");
1539 vnc_write_u32(vs, 0); /* Accept auth */
1542 vnc_read_when(vs, protocol_client_init, 1);
1547 static int start_auth_vnc(VncState *vs)
1550 /* Send client a 'random' challenge */
1551 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1554 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1559 #ifdef CONFIG_VNC_TLS
1560 #define DH_BITS 1024
1561 static gnutls_dh_params_t dh_params;
1563 static int vnc_tls_initialize(void)
1565 static int tlsinitialized = 0;
1570 if (gnutls_global_init () < 0)
1573 /* XXX ought to re-generate diffie-hellmen params periodically */
1574 if (gnutls_dh_params_init (&dh_params) < 0)
1576 if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1579 #if defined(_VNC_DEBUG) && _VNC_DEBUG >= 2
1580 gnutls_global_set_log_level(10);
1581 gnutls_global_set_log_function(vnc_debug_gnutls_log);
1589 static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1591 gnutls_anon_server_credentials anon_cred;
1594 if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1595 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1599 gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1605 static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1607 gnutls_certificate_credentials_t x509_cred;
1610 if (!vs->x509cacert) {
1611 VNC_DEBUG("No CA x509 certificate specified\n");
1614 if (!vs->x509cert) {
1615 VNC_DEBUG("No server x509 certificate specified\n");
1619 VNC_DEBUG("No server private key specified\n");
1623 if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1624 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1627 if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1629 GNUTLS_X509_FMT_PEM)) < 0) {
1630 VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1631 gnutls_certificate_free_credentials(x509_cred);
1635 if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1638 GNUTLS_X509_FMT_PEM)) < 0) {
1639 VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1640 gnutls_certificate_free_credentials(x509_cred);
1644 if (vs->x509cacrl) {
1645 if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1647 GNUTLS_X509_FMT_PEM)) < 0) {
1648 VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
1649 gnutls_certificate_free_credentials(x509_cred);
1654 gnutls_certificate_set_dh_params (x509_cred, dh_params);
1659 static int vnc_validate_certificate(struct VncState *vs)
1662 unsigned int status;
1663 const gnutls_datum_t *certs;
1664 unsigned int nCerts, i;
1667 VNC_DEBUG("Validating client certificate\n");
1668 if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
1669 VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
1673 if ((now = time(NULL)) == ((time_t)-1)) {
1678 if (status & GNUTLS_CERT_INVALID)
1679 VNC_DEBUG("The certificate is not trusted.\n");
1681 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1682 VNC_DEBUG("The certificate hasn't got a known issuer.\n");
1684 if (status & GNUTLS_CERT_REVOKED)
1685 VNC_DEBUG("The certificate has been revoked.\n");
1687 if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1688 VNC_DEBUG("The certificate uses an insecure algorithm\n");
1692 VNC_DEBUG("Certificate is valid!\n");
1695 /* Only support x509 for now */
1696 if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
1699 if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
1702 for (i = 0 ; i < nCerts ; i++) {
1703 gnutls_x509_crt_t cert;
1704 VNC_DEBUG ("Checking certificate chain %d\n", i);
1705 if (gnutls_x509_crt_init (&cert) < 0)
1708 if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1709 gnutls_x509_crt_deinit (cert);
1713 if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1714 VNC_DEBUG("The certificate has expired\n");
1715 gnutls_x509_crt_deinit (cert);
1719 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1720 VNC_DEBUG("The certificate is not yet activated\n");
1721 gnutls_x509_crt_deinit (cert);
1725 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1726 VNC_DEBUG("The certificate is not yet activated\n");
1727 gnutls_x509_crt_deinit (cert);
1731 gnutls_x509_crt_deinit (cert);
1738 static int start_auth_vencrypt_subauth(VncState *vs)
1740 switch (vs->subauth) {
1741 case VNC_AUTH_VENCRYPT_TLSNONE:
1742 case VNC_AUTH_VENCRYPT_X509NONE:
1743 VNC_DEBUG("Accept TLS auth none\n");
1744 vnc_write_u32(vs, 0); /* Accept auth completion */
1745 vnc_read_when(vs, protocol_client_init, 1);
1748 case VNC_AUTH_VENCRYPT_TLSVNC:
1749 case VNC_AUTH_VENCRYPT_X509VNC:
1750 VNC_DEBUG("Start TLS auth VNC\n");
1751 return start_auth_vnc(vs);
1753 default: /* Should not be possible, but just in case */
1754 VNC_DEBUG("Reject auth %d\n", vs->auth);
1755 vnc_write_u8(vs, 1);
1756 if (vs->minor >= 8) {
1757 static const char err[] = "Unsupported authentication type";
1758 vnc_write_u32(vs, sizeof(err));
1759 vnc_write(vs, err, sizeof(err));
1761 vnc_client_error(vs);
1767 static void vnc_handshake_io(void *opaque);
1769 static int vnc_continue_handshake(struct VncState *vs) {
1772 if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1773 if (!gnutls_error_is_fatal(ret)) {
1774 VNC_DEBUG("Handshake interrupted (blocking)\n");
1775 if (!gnutls_record_get_direction(vs->tls_session))
1776 qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1778 qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1781 VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1782 vnc_client_error(vs);
1786 if (vs->x509verify) {
1787 if (vnc_validate_certificate(vs) < 0) {
1788 VNC_DEBUG("Client verification failed\n");
1789 vnc_client_error(vs);
1792 VNC_DEBUG("Client verification passed\n");
1796 VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1797 vs->wiremode = VNC_WIREMODE_TLS;
1798 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1800 return start_auth_vencrypt_subauth(vs);
1803 static void vnc_handshake_io(void *opaque) {
1804 struct VncState *vs = (struct VncState *)opaque;
1806 VNC_DEBUG("Handshake IO continue\n");
1807 vnc_continue_handshake(vs);
1810 #define NEED_X509_AUTH(vs) \
1811 ((vs)->subauth == VNC_AUTH_VENCRYPT_X509NONE || \
1812 (vs)->subauth == VNC_AUTH_VENCRYPT_X509VNC || \
1813 (vs)->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
1816 static int vnc_start_tls(struct VncState *vs) {
1817 static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
1818 static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
1819 static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
1820 static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
1822 VNC_DEBUG("Do TLS setup\n");
1823 if (vnc_tls_initialize() < 0) {
1824 VNC_DEBUG("Failed to init TLS\n");
1825 vnc_client_error(vs);
1828 if (vs->tls_session == NULL) {
1829 if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
1830 vnc_client_error(vs);
1834 if (gnutls_set_default_priority(vs->tls_session) < 0) {
1835 gnutls_deinit(vs->tls_session);
1836 vs->tls_session = NULL;
1837 vnc_client_error(vs);
1841 if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
1842 gnutls_deinit(vs->tls_session);
1843 vs->tls_session = NULL;
1844 vnc_client_error(vs);
1848 if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
1849 gnutls_deinit(vs->tls_session);
1850 vs->tls_session = NULL;
1851 vnc_client_error(vs);
1855 if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
1856 gnutls_deinit(vs->tls_session);
1857 vs->tls_session = NULL;
1858 vnc_client_error(vs);
1862 if (NEED_X509_AUTH(vs)) {
1863 gnutls_certificate_server_credentials x509_cred = vnc_tls_initialize_x509_cred(vs);
1865 gnutls_deinit(vs->tls_session);
1866 vs->tls_session = NULL;
1867 vnc_client_error(vs);
1870 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {
1871 gnutls_deinit(vs->tls_session);
1872 vs->tls_session = NULL;
1873 gnutls_certificate_free_credentials(x509_cred);
1874 vnc_client_error(vs);
1877 if (vs->x509verify) {
1878 VNC_DEBUG("Requesting a client certificate\n");
1879 gnutls_certificate_server_set_request (vs->tls_session, GNUTLS_CERT_REQUEST);
1883 gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
1885 gnutls_deinit(vs->tls_session);
1886 vs->tls_session = NULL;
1887 vnc_client_error(vs);
1890 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
1891 gnutls_deinit(vs->tls_session);
1892 vs->tls_session = NULL;
1893 gnutls_anon_free_server_credentials(anon_cred);
1894 vnc_client_error(vs);
1899 gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
1900 gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
1901 gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
1904 VNC_DEBUG("Start TLS handshake process\n");
1905 return vnc_continue_handshake(vs);
1908 static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)
1910 int auth = read_u32(data, 0);
1912 if (auth != vs->subauth) {
1913 VNC_DEBUG("Rejecting auth %d\n", auth);
1914 vnc_write_u8(vs, 0); /* Reject auth */
1916 vnc_client_error(vs);
1918 VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
1919 vnc_write_u8(vs, 1); /* Accept auth */
1922 if (vnc_start_tls(vs) < 0) {
1923 VNC_DEBUG("Failed to complete TLS\n");
1927 if (vs->wiremode == VNC_WIREMODE_TLS) {
1928 VNC_DEBUG("Starting VeNCrypt subauth\n");
1929 return start_auth_vencrypt_subauth(vs);
1931 VNC_DEBUG("TLS handshake blocked\n");
1938 static int protocol_client_vencrypt_init(VncState *vs, uint8_t *data, size_t len)
1942 VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
1943 vnc_write_u8(vs, 1); /* Reject version */
1945 vnc_client_error(vs);
1947 VNC_DEBUG("Sending allowed auth %d\n", vs->subauth);
1948 vnc_write_u8(vs, 0); /* Accept version */
1949 vnc_write_u8(vs, 1); /* Number of sub-auths */
1950 vnc_write_u32(vs, vs->subauth); /* The supported auth */
1952 vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
1957 static int start_auth_vencrypt(VncState *vs)
1959 /* Send VeNCrypt version 0.2 */
1960 vnc_write_u8(vs, 0);
1961 vnc_write_u8(vs, 2);
1963 vnc_read_when(vs, protocol_client_vencrypt_init, 2);
1966 #endif /* CONFIG_VNC_TLS */
1968 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
1970 /* We only advertise 1 auth scheme at a time, so client
1971 * must pick the one we sent. Verify this */
1972 if (data[0] != vs->auth) { /* Reject auth */
1973 VNC_DEBUG("Reject auth %d\n", (int)data[0]);
1974 vnc_write_u32(vs, 1);
1975 if (vs->minor >= 8) {
1976 static const char err[] = "Authentication failed";
1977 vnc_write_u32(vs, sizeof(err));
1978 vnc_write(vs, err, sizeof(err));
1980 vnc_client_error(vs);
1981 } else { /* Accept requested auth */
1982 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
1985 VNC_DEBUG("Accept auth none\n");
1986 if (vs->minor >= 8) {
1987 vnc_write_u32(vs, 0); /* Accept auth completion */
1990 vnc_read_when(vs, protocol_client_init, 1);
1994 VNC_DEBUG("Start VNC auth\n");
1995 return start_auth_vnc(vs);
1997 #ifdef CONFIG_VNC_TLS
1998 case VNC_AUTH_VENCRYPT:
1999 VNC_DEBUG("Accept VeNCrypt auth\n");;
2000 return start_auth_vencrypt(vs);
2001 #endif /* CONFIG_VNC_TLS */
2003 default: /* Should not be possible, but just in case */
2004 VNC_DEBUG("Reject auth %d\n", vs->auth);
2005 vnc_write_u8(vs, 1);
2006 if (vs->minor >= 8) {
2007 static const char err[] = "Authentication failed";
2008 vnc_write_u32(vs, sizeof(err));
2009 vnc_write(vs, err, sizeof(err));
2011 vnc_client_error(vs);
2017 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2021 memcpy(local, version, 12);
2024 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2025 VNC_DEBUG("Malformed protocol version %s\n", local);
2026 vnc_client_error(vs);
2029 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2030 if (vs->major != 3 ||
2036 VNC_DEBUG("Unsupported client version\n");
2037 vnc_write_u32(vs, VNC_AUTH_INVALID);
2039 vnc_client_error(vs);
2042 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2043 * as equivalent to v3.3 by servers
2045 if (vs->minor == 4 || vs->minor == 5)
2048 if (vs->minor == 3) {
2049 if (vs->auth == VNC_AUTH_NONE) {
2050 VNC_DEBUG("Tell client auth none\n");
2051 vnc_write_u32(vs, vs->auth);
2053 vnc_read_when(vs, protocol_client_init, 1);
2054 } else if (vs->auth == VNC_AUTH_VNC) {
2055 VNC_DEBUG("Tell client VNC auth\n");
2056 vnc_write_u32(vs, vs->auth);
2060 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2061 vnc_write_u32(vs, VNC_AUTH_INVALID);
2063 vnc_client_error(vs);
2066 VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2067 vnc_write_u8(vs, 1); /* num auth */
2068 vnc_write_u8(vs, vs->auth);
2069 vnc_read_when(vs, protocol_client_auth, 1);
2076 static void vnc_connect(VncState *vs)
2078 VNC_DEBUG("New client on socket %d\n", vs->csock);
2080 socket_set_nonblock(vs->csock);
2081 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2082 vnc_write(vs, "RFB 003.008\n", 12);
2084 vnc_read_when(vs, protocol_version, 12);
2085 memset(vs->old_data, 0, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
2086 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
2088 dcl->dpy_copy = NULL;
2089 vnc_update_client(vs);
2093 static void vnc_listen_read(void *opaque)
2095 VncState *vs = opaque;
2096 struct sockaddr_in addr;
2097 socklen_t addrlen = sizeof(addr);
2102 vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2103 if (vs->csock != -1) {
2108 void vnc_display_init(DisplayState *ds)
2112 vs = qemu_mallocz(sizeof(VncState));
2113 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2121 vs->password = NULL;
2130 if (keyboard_layout)
2131 vs->kbd_layout = init_keyboard_layout(keyboard_layout);
2133 vs->kbd_layout = init_keyboard_layout("en-us");
2135 if (!vs->kbd_layout)
2138 vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
2140 dcl->dpy_update = vnc_dpy_update;
2141 dcl->dpy_resize = vnc_dpy_resize;
2142 dcl->dpy_setdata = vnc_dpy_setdata;
2143 dcl->dpy_refresh = NULL;
2144 register_displaychangelistener(ds, dcl);
2146 vs->as.freq = 44100;
2147 vs->as.nchannels = 2;
2148 vs->as.fmt = AUD_FMT_S16;
2149 vs->as.endianness = 0;
2152 #ifdef CONFIG_VNC_TLS
2153 static int vnc_set_x509_credential(VncState *vs,
2154 const char *certdir,
2155 const char *filename,
2166 if (!(*cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2)))
2169 strcpy(*cred, certdir);
2171 strcat(*cred, filename);
2173 VNC_DEBUG("Check %s\n", *cred);
2174 if (stat(*cred, &sb) < 0) {
2177 if (ignoreMissing && errno == ENOENT)
2185 static int vnc_set_x509_credential_dir(VncState *vs,
2186 const char *certdir)
2188 if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)
2190 if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)
2192 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)
2194 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)
2200 qemu_free(vs->x509cacert);
2201 qemu_free(vs->x509cacrl);
2202 qemu_free(vs->x509cert);
2203 qemu_free(vs->x509key);
2204 vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2207 #endif /* CONFIG_VNC_TLS */
2209 void vnc_display_close(DisplayState *ds)
2211 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2214 qemu_free(vs->display);
2217 if (vs->lsock != -1) {
2218 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2222 if (vs->csock != -1) {
2223 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
2224 closesocket(vs->csock);
2226 buffer_reset(&vs->input);
2227 buffer_reset(&vs->output);
2228 vs->need_update = 0;
2229 #ifdef CONFIG_VNC_TLS
2230 if (vs->tls_session) {
2231 gnutls_deinit(vs->tls_session);
2232 vs->tls_session = NULL;
2234 vs->wiremode = VNC_WIREMODE_CLEAR;
2235 #endif /* CONFIG_VNC_TLS */
2237 vs->auth = VNC_AUTH_INVALID;
2238 #ifdef CONFIG_VNC_TLS
2239 vs->subauth = VNC_AUTH_INVALID;
2245 int vnc_display_password(DisplayState *ds, const char *password)
2247 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2250 qemu_free(vs->password);
2251 vs->password = NULL;
2253 if (password && password[0]) {
2254 if (!(vs->password = qemu_strdup(password)))
2261 int vnc_display_open(DisplayState *ds, const char *display)
2263 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2264 const char *options;
2268 #ifdef CONFIG_VNC_TLS
2269 int tls = 0, x509 = 0;
2272 vnc_display_close(ds);
2273 if (strcmp(display, "none") == 0)
2276 if (!(vs->display = strdup(display)))
2280 while ((options = strchr(options, ','))) {
2282 if (strncmp(options, "password", 8) == 0) {
2283 password = 1; /* Require password auth */
2284 } else if (strncmp(options, "reverse", 7) == 0) {
2286 } else if (strncmp(options, "to=", 3) == 0) {
2287 to_port = atoi(options+3) + 5900;
2288 #ifdef CONFIG_VNC_TLS
2289 } else if (strncmp(options, "tls", 3) == 0) {
2290 tls = 1; /* Require TLS */
2291 } else if (strncmp(options, "x509", 4) == 0) {
2293 x509 = 1; /* Require x509 certificates */
2294 if (strncmp(options, "x509verify", 10) == 0)
2295 vs->x509verify = 1; /* ...and verify client certs */
2297 /* Now check for 'x509=/some/path' postfix
2298 * and use that to setup x509 certificate/key paths */
2299 start = strchr(options, '=');
2300 end = strchr(options, ',');
2301 if (start && (!end || (start < end))) {
2302 int len = end ? end-(start+1) : strlen(start+1);
2303 char *path = qemu_strndup(start + 1, len);
2305 VNC_DEBUG("Trying certificate path '%s'\n", path);
2306 if (vnc_set_x509_credential_dir(vs, path) < 0) {
2307 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2309 qemu_free(vs->display);
2315 fprintf(stderr, "No certificate path provided\n");
2316 qemu_free(vs->display);
2325 #ifdef CONFIG_VNC_TLS
2327 vs->auth = VNC_AUTH_VENCRYPT;
2329 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2330 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2332 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2333 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2337 VNC_DEBUG("Initializing VNC server with password auth\n");
2338 vs->auth = VNC_AUTH_VNC;
2339 #ifdef CONFIG_VNC_TLS
2340 vs->subauth = VNC_AUTH_INVALID;
2344 #ifdef CONFIG_VNC_TLS
2346 vs->auth = VNC_AUTH_VENCRYPT;
2348 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2349 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2351 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2352 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2356 VNC_DEBUG("Initializing VNC server with no auth\n");
2357 vs->auth = VNC_AUTH_NONE;
2358 #ifdef CONFIG_VNC_TLS
2359 vs->subauth = VNC_AUTH_INVALID;
2365 /* connect to viewer */
2366 if (strncmp(display, "unix:", 5) == 0)
2367 vs->lsock = unix_connect(display+5);
2369 vs->lsock = inet_connect(display, SOCK_STREAM);
2370 if (-1 == vs->lsock) {
2375 vs->csock = vs->lsock;
2382 /* listen for connects */
2384 dpy = qemu_malloc(256);
2385 if (strncmp(display, "unix:", 5) == 0) {
2386 pstrcpy(dpy, 256, "unix:");
2387 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2389 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2391 if (-1 == vs->lsock) {
2400 return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);