Enhance 'info vnc' monitor output ("Daniel P. Berrange")
[qemu-kvm/fedora.git] / vnc.c
blob7853635323a6314b1fa233d96f5e24a9c7b018f4
1 /*
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
23 * THE SOFTWARE.
26 #include "qemu-common.h"
27 #include "console.h"
28 #include "sysemu.h"
29 #include "qemu_socket.h"
30 #include "qemu-timer.h"
31 #include "audio/audio.h"
32 #include <zlib.h>
34 #define VNC_REFRESH_INTERVAL (1000 / 30)
36 #include "vnc.h"
37 #include "vnc_keysym.h"
38 #include "keymaps.c"
39 #include "d3des.h"
41 #ifdef CONFIG_VNC_TLS
42 #include <gnutls/gnutls.h>
43 #include <gnutls/x509.h>
44 #endif /* CONFIG_VNC_TLS */
46 // #define _VNC_DEBUG 1
48 #ifdef _VNC_DEBUG
49 #define VNC_DEBUG(fmt, ...) do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
51 #if defined(CONFIG_VNC_TLS) && _VNC_DEBUG >= 2
52 /* Very verbose, so only enabled for _VNC_DEBUG >= 2 */
53 static void vnc_debug_gnutls_log(int level, const char* str) {
54 VNC_DEBUG("%d %s", level, str);
56 #endif /* CONFIG_VNC_TLS && _VNC_DEBUG */
57 #else
58 #define VNC_DEBUG(fmt, ...) do { } while (0)
59 #endif
61 #define count_bits(c, v) { \
62 for (c = 0; v; v >>= 1) \
63 { \
64 c += v & 1; \
65 } \
68 typedef struct Buffer
70 size_t capacity;
71 size_t offset;
72 uint8_t *buffer;
73 } Buffer;
75 typedef struct VncState VncState;
77 typedef int VncReadEvent(VncState *vs, uint8_t *data, size_t len);
79 typedef void VncWritePixels(VncState *vs, void *data, int size);
81 typedef void VncSendHextileTile(VncState *vs,
82 int x, int y, int w, int h,
83 void *last_bg,
84 void *last_fg,
85 int *has_bg, int *has_fg);
87 #define VNC_MAX_WIDTH 2048
88 #define VNC_MAX_HEIGHT 2048
89 #define VNC_DIRTY_WORDS (VNC_MAX_WIDTH / (16 * 32))
91 #define VNC_AUTH_CHALLENGE_SIZE 16
93 typedef struct VncDisplay VncDisplay;
95 struct VncDisplay
97 int lsock;
98 DisplayState *ds;
99 VncState *clients;
100 kbd_layout_t *kbd_layout;
102 char *display;
103 char *password;
104 int auth;
105 #ifdef CONFIG_VNC_TLS
106 int subauth;
107 int x509verify;
109 char *x509cacert;
110 char *x509cacrl;
111 char *x509cert;
112 char *x509key;
113 #endif
116 struct VncState
118 QEMUTimer *timer;
119 int csock;
120 DisplayState *ds;
121 VncDisplay *vd;
122 int need_update;
123 uint32_t dirty_row[VNC_MAX_HEIGHT][VNC_DIRTY_WORDS];
124 char *old_data;
125 uint32_t features;
126 int absolute;
127 int last_x;
128 int last_y;
130 uint32_t vnc_encoding;
131 uint8_t tight_quality;
132 uint8_t tight_compression;
134 int major;
135 int minor;
137 char challenge[VNC_AUTH_CHALLENGE_SIZE];
139 #ifdef CONFIG_VNC_TLS
140 int wiremode;
141 gnutls_session_t tls_session;
142 #endif
144 Buffer output;
145 Buffer input;
146 /* current output mode information */
147 VncWritePixels *write_pixels;
148 VncSendHextileTile *send_hextile_tile;
149 DisplaySurface clientds, serverds;
151 CaptureVoiceOut *audio_cap;
152 struct audsettings as;
154 VncReadEvent *read_handler;
155 size_t read_handler_expect;
156 /* input */
157 uint8_t modifiers_state[256];
159 Buffer zlib;
160 Buffer zlib_tmp;
161 z_stream zlib_stream[4];
163 VncState *next;
166 static VncDisplay *vnc_display; /* needed for info vnc */
167 static DisplayChangeListener *dcl;
169 static char *addr_to_string(const char *format,
170 struct sockaddr_storage *sa,
171 socklen_t salen) {
172 char *addr;
173 char host[NI_MAXHOST];
174 char serv[NI_MAXSERV];
175 int err;
177 if ((err = getnameinfo((struct sockaddr *)sa, salen,
178 host, sizeof(host),
179 serv, sizeof(serv),
180 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
181 VNC_DEBUG("Cannot resolve address %d: %s\n",
182 err, gai_strerror(err));
183 return NULL;
186 if (asprintf(&addr, format, host, serv) < 0)
187 return NULL;
189 return addr;
192 static char *vnc_socket_local_addr(const char *format, int fd) {
193 struct sockaddr_storage sa;
194 socklen_t salen;
196 salen = sizeof(sa);
197 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
198 return NULL;
200 return addr_to_string(format, &sa, salen);
203 static char *vnc_socket_remote_addr(const char *format, int fd) {
204 struct sockaddr_storage sa;
205 socklen_t salen;
207 salen = sizeof(sa);
208 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
209 return NULL;
211 return addr_to_string(format, &sa, salen);
214 static const char *vnc_auth_name(VncDisplay *vd) {
215 switch (vd->auth) {
216 case VNC_AUTH_INVALID:
217 return "invalid";
218 case VNC_AUTH_NONE:
219 return "none";
220 case VNC_AUTH_VNC:
221 return "vnc";
222 case VNC_AUTH_RA2:
223 return "ra2";
224 case VNC_AUTH_RA2NE:
225 return "ra2ne";
226 case VNC_AUTH_TIGHT:
227 return "tight";
228 case VNC_AUTH_ULTRA:
229 return "ultra";
230 case VNC_AUTH_TLS:
231 return "tls";
232 case VNC_AUTH_VENCRYPT:
233 #ifdef CONFIG_VNC_TLS
234 switch (vd->subauth) {
235 case VNC_AUTH_VENCRYPT_PLAIN:
236 return "vencrypt+plain";
237 case VNC_AUTH_VENCRYPT_TLSNONE:
238 return "vencrypt+tls+none";
239 case VNC_AUTH_VENCRYPT_TLSVNC:
240 return "vencrypt+tls+vnc";
241 case VNC_AUTH_VENCRYPT_TLSPLAIN:
242 return "vencrypt+tls+plain";
243 case VNC_AUTH_VENCRYPT_X509NONE:
244 return "vencrypt+x509+none";
245 case VNC_AUTH_VENCRYPT_X509VNC:
246 return "vencrypt+x509+vnc";
247 case VNC_AUTH_VENCRYPT_X509PLAIN:
248 return "vencrypt+x509+plain";
249 default:
250 return "vencrypt";
252 #else
253 return "vencrypt";
254 #endif
256 return "unknown";
259 #define VNC_SOCKET_FORMAT_PRETTY "local %s:%s"
261 static void do_info_vnc_client(VncState *client)
263 char *clientAddr =
264 vnc_socket_remote_addr(" address: %s:%s\n",
265 client->csock);
266 if (!clientAddr)
267 return;
269 term_puts("Client:\n");
270 term_puts(clientAddr);
271 free(clientAddr);
274 void do_info_vnc(void)
276 if (vnc_display == NULL || vnc_display->display == NULL) {
277 term_printf("Server: disabled\n");
278 } else {
279 char *serverAddr = vnc_socket_local_addr(" address: %s:%s\n",
280 vnc_display->lsock);
282 if (!serverAddr)
283 return;
285 term_puts("Server:\n");
286 term_puts(serverAddr);
287 free(serverAddr);
288 term_printf(" auth: %s\n", vnc_auth_name(vnc_display));
290 if (vnc_display->clients) {
291 VncState *client = vnc_display->clients;
292 while (client) {
293 do_info_vnc_client(client);
294 client = client->next;
296 } else {
297 term_printf("Client: none\n");
302 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
303 return (vs->features & (1 << feature));
306 /* TODO
307 1) Get the queue working for IO.
308 2) there is some weirdness when using the -S option (the screen is grey
309 and not totally invalidated
310 3) resolutions > 1024
313 static void vnc_write(VncState *vs, const void *data, size_t len);
314 static void vnc_write_u32(VncState *vs, uint32_t value);
315 static void vnc_write_s32(VncState *vs, int32_t value);
316 static void vnc_write_u16(VncState *vs, uint16_t value);
317 static void vnc_write_u8(VncState *vs, uint8_t value);
318 static void vnc_flush(VncState *vs);
319 static void vnc_update_client(void *opaque);
320 static void vnc_disconnect_start(VncState *vs);
321 static void vnc_disconnect_finish(VncState *vs);
322 static void vnc_client_read(void *opaque);
324 static void vnc_colordepth(VncState *vs);
326 static inline void vnc_set_bit(uint32_t *d, int k)
328 d[k >> 5] |= 1 << (k & 0x1f);
331 static inline void vnc_clear_bit(uint32_t *d, int k)
333 d[k >> 5] &= ~(1 << (k & 0x1f));
336 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
338 int j;
340 j = 0;
341 while (n >= 32) {
342 d[j++] = -1;
343 n -= 32;
345 if (n > 0)
346 d[j++] = (1 << n) - 1;
347 while (j < nb_words)
348 d[j++] = 0;
351 static inline int vnc_get_bit(const uint32_t *d, int k)
353 return (d[k >> 5] >> (k & 0x1f)) & 1;
356 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
357 int nb_words)
359 int i;
360 for(i = 0; i < nb_words; i++) {
361 if ((d1[i] & d2[i]) != 0)
362 return 1;
364 return 0;
367 static void vnc_update(VncState *vs, int x, int y, int w, int h)
369 int i;
371 h += y;
373 /* round x down to ensure the loop only spans one 16-pixel block per,
374 iteration. otherwise, if (x % 16) != 0, the last iteration may span
375 two 16-pixel blocks but we only mark the first as dirty
377 w += (x % 16);
378 x -= (x % 16);
380 x = MIN(x, vs->serverds.width);
381 y = MIN(y, vs->serverds.height);
382 w = MIN(x + w, vs->serverds.width) - x;
383 h = MIN(h, vs->serverds.height);
385 for (; y < h; y++)
386 for (i = 0; i < w; i += 16)
387 vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
390 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
392 VncDisplay *vd = ds->opaque;
393 VncState *vs = vd->clients;
394 while (vs != NULL) {
395 vnc_update(vs, x, y, w, h);
396 vs = vs->next;
400 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
401 int32_t encoding)
403 vnc_write_u16(vs, x);
404 vnc_write_u16(vs, y);
405 vnc_write_u16(vs, w);
406 vnc_write_u16(vs, h);
408 vnc_write_s32(vs, encoding);
411 static void buffer_reserve(Buffer *buffer, size_t len)
413 if ((buffer->capacity - buffer->offset) < len) {
414 buffer->capacity += (len + 1024);
415 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
416 if (buffer->buffer == NULL) {
417 fprintf(stderr, "vnc: out of memory\n");
418 exit(1);
423 static int buffer_empty(Buffer *buffer)
425 return buffer->offset == 0;
428 static uint8_t *buffer_end(Buffer *buffer)
430 return buffer->buffer + buffer->offset;
433 static void buffer_reset(Buffer *buffer)
435 buffer->offset = 0;
438 static void buffer_append(Buffer *buffer, const void *data, size_t len)
440 memcpy(buffer->buffer + buffer->offset, data, len);
441 buffer->offset += len;
444 static void vnc_resize(VncState *vs)
446 DisplayState *ds = vs->ds;
448 int size_changed;
450 vs->old_data = qemu_realloc(vs->old_data, ds_get_linesize(ds) * ds_get_height(ds));
452 if (vs->old_data == NULL) {
453 fprintf(stderr, "vnc: memory allocation failed\n");
454 exit(1);
457 if (ds_get_bytes_per_pixel(ds) != vs->serverds.pf.bytes_per_pixel)
458 console_color_init(ds);
459 vnc_colordepth(vs);
460 size_changed = ds_get_width(ds) != vs->serverds.width ||
461 ds_get_height(ds) != vs->serverds.height;
462 vs->serverds = *(ds->surface);
463 if (size_changed) {
464 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
465 vnc_write_u8(vs, 0); /* msg id */
466 vnc_write_u8(vs, 0);
467 vnc_write_u16(vs, 1); /* number of rects */
468 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
469 VNC_ENCODING_DESKTOPRESIZE);
470 vnc_flush(vs);
474 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
475 memset(vs->old_data, 42, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
478 static void vnc_dpy_resize(DisplayState *ds)
480 VncDisplay *vd = ds->opaque;
481 VncState *vs = vd->clients;
482 while (vs != NULL) {
483 vnc_resize(vs);
484 vs = vs->next;
488 /* fastest code */
489 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
491 vnc_write(vs, pixels, size);
494 /* slowest but generic code. */
495 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
497 uint8_t r, g, b;
499 r = ((((v & vs->serverds.pf.rmask) >> vs->serverds.pf.rshift) << vs->clientds.pf.rbits) >>
500 vs->serverds.pf.rbits);
501 g = ((((v & vs->serverds.pf.gmask) >> vs->serverds.pf.gshift) << vs->clientds.pf.gbits) >>
502 vs->serverds.pf.gbits);
503 b = ((((v & vs->serverds.pf.bmask) >> vs->serverds.pf.bshift) << vs->clientds.pf.bbits) >>
504 vs->serverds.pf.bbits);
505 v = (r << vs->clientds.pf.rshift) |
506 (g << vs->clientds.pf.gshift) |
507 (b << vs->clientds.pf.bshift);
508 switch(vs->clientds.pf.bytes_per_pixel) {
509 case 1:
510 buf[0] = v;
511 break;
512 case 2:
513 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
514 buf[0] = v >> 8;
515 buf[1] = v;
516 } else {
517 buf[1] = v >> 8;
518 buf[0] = v;
520 break;
521 default:
522 case 4:
523 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
524 buf[0] = v >> 24;
525 buf[1] = v >> 16;
526 buf[2] = v >> 8;
527 buf[3] = v;
528 } else {
529 buf[3] = v >> 24;
530 buf[2] = v >> 16;
531 buf[1] = v >> 8;
532 buf[0] = v;
534 break;
538 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
540 uint8_t buf[4];
542 if (vs->serverds.pf.bytes_per_pixel == 4) {
543 uint32_t *pixels = pixels1;
544 int n, i;
545 n = size >> 2;
546 for(i = 0; i < n; i++) {
547 vnc_convert_pixel(vs, buf, pixels[i]);
548 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
550 } else if (vs->serverds.pf.bytes_per_pixel == 2) {
551 uint16_t *pixels = pixels1;
552 int n, i;
553 n = size >> 1;
554 for(i = 0; i < n; i++) {
555 vnc_convert_pixel(vs, buf, pixels[i]);
556 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
558 } else if (vs->serverds.pf.bytes_per_pixel == 1) {
559 uint8_t *pixels = pixels1;
560 int n, i;
561 n = size;
562 for(i = 0; i < n; i++) {
563 vnc_convert_pixel(vs, buf, pixels[i]);
564 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
566 } else {
567 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
571 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
573 int i;
574 uint8_t *row;
576 row = ds_get_data(vs->ds) + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
577 for (i = 0; i < h; i++) {
578 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
579 row += ds_get_linesize(vs->ds);
583 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
585 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
586 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
589 #define BPP 8
590 #include "vnchextile.h"
591 #undef BPP
593 #define BPP 16
594 #include "vnchextile.h"
595 #undef BPP
597 #define BPP 32
598 #include "vnchextile.h"
599 #undef BPP
601 #define GENERIC
602 #define BPP 8
603 #include "vnchextile.h"
604 #undef BPP
605 #undef GENERIC
607 #define GENERIC
608 #define BPP 16
609 #include "vnchextile.h"
610 #undef BPP
611 #undef GENERIC
613 #define GENERIC
614 #define BPP 32
615 #include "vnchextile.h"
616 #undef BPP
617 #undef GENERIC
619 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
621 int i, j;
622 int has_fg, has_bg;
623 uint8_t *last_fg, *last_bg;
625 last_fg = (uint8_t *) qemu_malloc(vs->serverds.pf.bytes_per_pixel);
626 last_bg = (uint8_t *) qemu_malloc(vs->serverds.pf.bytes_per_pixel);
627 has_fg = has_bg = 0;
628 for (j = y; j < (y + h); j += 16) {
629 for (i = x; i < (x + w); i += 16) {
630 vs->send_hextile_tile(vs, i, j,
631 MIN(16, x + w - i), MIN(16, y + h - j),
632 last_bg, last_fg, &has_bg, &has_fg);
635 free(last_fg);
636 free(last_bg);
640 static void vnc_zlib_init(VncState *vs)
642 int i;
643 for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
644 vs->zlib_stream[i].opaque = NULL;
647 static void vnc_zlib_start(VncState *vs)
649 buffer_reset(&vs->zlib);
651 // make the output buffer be the zlib buffer, so we can compress it later
652 vs->zlib_tmp = vs->output;
653 vs->output = vs->zlib;
656 static int vnc_zlib_stop(VncState *vs, int stream_id)
658 z_streamp zstream = &vs->zlib_stream[stream_id];
659 int previous_out;
661 // switch back to normal output/zlib buffers
662 vs->zlib = vs->output;
663 vs->output = vs->zlib_tmp;
665 // compress the zlib buffer
667 // initialize the stream
668 // XXX need one stream per session
669 if (zstream->opaque != vs) {
670 int err;
672 VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
673 VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
674 zstream->zalloc = Z_NULL;
675 zstream->zfree = Z_NULL;
677 err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
678 MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
680 if (err != Z_OK) {
681 fprintf(stderr, "VNC: error initializing zlib\n");
682 return -1;
685 zstream->opaque = vs;
688 // XXX what to do if tight_compression changed in between?
690 // reserve memory in output buffer
691 buffer_reserve(&vs->output, vs->zlib.offset + 64);
693 // set pointers
694 zstream->next_in = vs->zlib.buffer;
695 zstream->avail_in = vs->zlib.offset;
696 zstream->next_out = vs->output.buffer + vs->output.offset;
697 zstream->avail_out = vs->output.capacity - vs->output.offset;
698 zstream->data_type = Z_BINARY;
699 previous_out = zstream->total_out;
701 // start encoding
702 if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
703 fprintf(stderr, "VNC: error during zlib compression\n");
704 return -1;
707 vs->output.offset = vs->output.capacity - zstream->avail_out;
708 return zstream->total_out - previous_out;
711 static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
713 int old_offset, new_offset, bytes_written;
715 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
717 // remember where we put in the follow-up size
718 old_offset = vs->output.offset;
719 vnc_write_s32(vs, 0);
721 // compress the stream
722 vnc_zlib_start(vs);
723 send_framebuffer_update_raw(vs, x, y, w, h);
724 bytes_written = vnc_zlib_stop(vs, 0);
726 if (bytes_written == -1)
727 return;
729 // hack in the size
730 new_offset = vs->output.offset;
731 vs->output.offset = old_offset;
732 vnc_write_u32(vs, bytes_written);
733 vs->output.offset = new_offset;
736 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
738 switch(vs->vnc_encoding) {
739 case VNC_ENCODING_ZLIB:
740 send_framebuffer_update_zlib(vs, x, y, w, h);
741 break;
742 case VNC_ENCODING_HEXTILE:
743 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
744 send_framebuffer_update_hextile(vs, x, y, w, h);
745 break;
746 default:
747 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
748 send_framebuffer_update_raw(vs, x, y, w, h);
749 break;
753 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
756 uint8_t *src_row;
757 uint8_t *dst_row;
758 int y,pitch,depth;
760 vnc_update_client(vs);
762 /* send bitblit op to the vnc client */
763 vnc_write_u8(vs, 0); /* msg id */
764 vnc_write_u8(vs, 0);
765 vnc_write_u16(vs, 1); /* number of rects */
766 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
767 vnc_write_u16(vs, src_x);
768 vnc_write_u16(vs, src_y);
769 vnc_flush(vs);
771 /* do bitblit op on the local surface too */
772 pitch = ds_get_linesize(vs->ds);
773 depth = ds_get_bytes_per_pixel(vs->ds);
774 src_row = ds_get_data(vs->ds) + pitch * src_y + depth * src_x;
775 dst_row = ds_get_data(vs->ds) + pitch * dst_y + depth * dst_x;
776 if (dst_y > src_y) {
777 /* copy backwards */
778 src_row += pitch * (h-1);
779 dst_row += pitch * (h-1);
780 pitch = -pitch;
782 for (y = 0; y < h; y++) {
783 memmove(dst_row, src_row, w * depth);
784 src_row += pitch;
785 dst_row += pitch;
789 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
791 VncDisplay *vd = ds->opaque;
792 VncState *vs, *vn;
794 for (vs = vd->clients; vs != NULL; vs = vn) {
795 vn = vs->next;
796 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
797 vnc_update_client(vs);
798 /* vs might be free()ed here */
802 for (vs = vd->clients; vs != NULL; vs = vs->next) {
803 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
804 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
805 else /* TODO */
806 vnc_update(vs, dst_x, dst_y, w, h);
810 static int find_dirty_height(VncState *vs, int y, int last_x, int x)
812 int h;
814 for (h = 1; h < (vs->serverds.height - y); h++) {
815 int tmp_x;
816 if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
817 break;
818 for (tmp_x = last_x; tmp_x < x; tmp_x++)
819 vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
822 return h;
825 static void vnc_update_client(void *opaque)
827 VncState *vs = opaque;
828 if (vs->need_update && vs->csock != -1) {
829 int y;
830 uint8_t *row;
831 char *old_row;
832 uint32_t width_mask[VNC_DIRTY_WORDS];
833 int n_rectangles;
834 int saved_offset;
835 int has_dirty = 0;
837 vga_hw_update();
839 vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
841 /* Walk through the dirty map and eliminate tiles that
842 really aren't dirty */
843 row = ds_get_data(vs->ds);
844 old_row = vs->old_data;
846 for (y = 0; y < ds_get_height(vs->ds); y++) {
847 if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
848 int x;
849 uint8_t *ptr;
850 char *old_ptr;
852 ptr = row;
853 old_ptr = (char*)old_row;
855 for (x = 0; x < ds_get_width(vs->ds); x += 16) {
856 if (memcmp(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds)) == 0) {
857 vnc_clear_bit(vs->dirty_row[y], (x / 16));
858 } else {
859 has_dirty = 1;
860 memcpy(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds));
863 ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
864 old_ptr += 16 * ds_get_bytes_per_pixel(vs->ds);
868 row += ds_get_linesize(vs->ds);
869 old_row += ds_get_linesize(vs->ds);
872 if (!has_dirty && !vs->audio_cap) {
873 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
874 return;
877 /* Count rectangles */
878 n_rectangles = 0;
879 vnc_write_u8(vs, 0); /* msg id */
880 vnc_write_u8(vs, 0);
881 saved_offset = vs->output.offset;
882 vnc_write_u16(vs, 0);
884 for (y = 0; y < vs->serverds.height; y++) {
885 int x;
886 int last_x = -1;
887 for (x = 0; x < vs->serverds.width / 16; x++) {
888 if (vnc_get_bit(vs->dirty_row[y], x)) {
889 if (last_x == -1) {
890 last_x = x;
892 vnc_clear_bit(vs->dirty_row[y], x);
893 } else {
894 if (last_x != -1) {
895 int h = find_dirty_height(vs, y, last_x, x);
896 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
897 n_rectangles++;
899 last_x = -1;
902 if (last_x != -1) {
903 int h = find_dirty_height(vs, y, last_x, x);
904 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
905 n_rectangles++;
908 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
909 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
910 vnc_flush(vs);
914 if (vs->csock != -1) {
915 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
916 } else {
917 vnc_disconnect_finish(vs);
922 /* audio */
923 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
925 VncState *vs = opaque;
927 switch (cmd) {
928 case AUD_CNOTIFY_DISABLE:
929 vnc_write_u8(vs, 255);
930 vnc_write_u8(vs, 1);
931 vnc_write_u16(vs, 0);
932 vnc_flush(vs);
933 break;
935 case AUD_CNOTIFY_ENABLE:
936 vnc_write_u8(vs, 255);
937 vnc_write_u8(vs, 1);
938 vnc_write_u16(vs, 1);
939 vnc_flush(vs);
940 break;
944 static void audio_capture_destroy(void *opaque)
948 static void audio_capture(void *opaque, void *buf, int size)
950 VncState *vs = opaque;
952 vnc_write_u8(vs, 255);
953 vnc_write_u8(vs, 1);
954 vnc_write_u16(vs, 2);
955 vnc_write_u32(vs, size);
956 vnc_write(vs, buf, size);
957 vnc_flush(vs);
960 static void audio_add(VncState *vs)
962 struct audio_capture_ops ops;
964 if (vs->audio_cap) {
965 term_printf ("audio already running\n");
966 return;
969 ops.notify = audio_capture_notify;
970 ops.destroy = audio_capture_destroy;
971 ops.capture = audio_capture;
973 vs->audio_cap = AUD_add_capture(NULL, &vs->as, &ops, vs);
974 if (!vs->audio_cap) {
975 term_printf ("Failed to add audio capture\n");
979 static void audio_del(VncState *vs)
981 if (vs->audio_cap) {
982 AUD_del_capture(vs->audio_cap, vs);
983 vs->audio_cap = NULL;
987 static void vnc_disconnect_start(VncState *vs)
989 if (vs->csock == -1)
990 return;
991 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
992 closesocket(vs->csock);
993 vs->csock = -1;
996 static void vnc_disconnect_finish(VncState *vs)
998 qemu_del_timer(vs->timer);
999 qemu_free_timer(vs->timer);
1000 if (vs->input.buffer) qemu_free(vs->input.buffer);
1001 if (vs->output.buffer) qemu_free(vs->output.buffer);
1002 #ifdef CONFIG_VNC_TLS
1003 if (vs->tls_session) {
1004 gnutls_deinit(vs->tls_session);
1005 vs->tls_session = NULL;
1007 #endif /* CONFIG_VNC_TLS */
1008 audio_del(vs);
1010 VncState *p, *parent = NULL;
1011 for (p = vs->vd->clients; p != NULL; p = p->next) {
1012 if (p == vs) {
1013 if (parent)
1014 parent->next = p->next;
1015 else
1016 vs->vd->clients = p->next;
1017 break;
1019 parent = p;
1021 if (!vs->vd->clients)
1022 dcl->idle = 1;
1024 qemu_free(vs->old_data);
1025 qemu_free(vs);
1028 static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1030 if (ret == 0 || ret == -1) {
1031 if (ret == -1) {
1032 switch (last_errno) {
1033 case EINTR:
1034 case EAGAIN:
1035 #ifdef _WIN32
1036 case WSAEWOULDBLOCK:
1037 #endif
1038 return 0;
1039 default:
1040 break;
1044 VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
1045 vnc_disconnect_start(vs);
1047 return 0;
1049 return ret;
1052 static void vnc_client_error(VncState *vs)
1054 VNC_DEBUG("Closing down client sock: protocol error\n");
1055 vnc_disconnect_start(vs);
1058 static void vnc_client_write(void *opaque)
1060 long ret;
1061 VncState *vs = opaque;
1063 #ifdef CONFIG_VNC_TLS
1064 if (vs->tls_session) {
1065 ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
1066 if (ret < 0) {
1067 if (ret == GNUTLS_E_AGAIN)
1068 errno = EAGAIN;
1069 else
1070 errno = EIO;
1071 ret = -1;
1073 } else
1074 #endif /* CONFIG_VNC_TLS */
1075 ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
1076 ret = vnc_client_io_error(vs, ret, socket_error());
1077 if (!ret)
1078 return;
1080 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1081 vs->output.offset -= ret;
1083 if (vs->output.offset == 0) {
1084 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1088 static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1090 vs->read_handler = func;
1091 vs->read_handler_expect = expecting;
1094 static void vnc_client_read(void *opaque)
1096 VncState *vs = opaque;
1097 long ret;
1099 buffer_reserve(&vs->input, 4096);
1101 #ifdef CONFIG_VNC_TLS
1102 if (vs->tls_session) {
1103 ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
1104 if (ret < 0) {
1105 if (ret == GNUTLS_E_AGAIN)
1106 errno = EAGAIN;
1107 else
1108 errno = EIO;
1109 ret = -1;
1111 } else
1112 #endif /* CONFIG_VNC_TLS */
1113 ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
1114 ret = vnc_client_io_error(vs, ret, socket_error());
1115 if (!ret) {
1116 if (vs->csock == -1)
1117 vnc_disconnect_finish(vs);
1118 return;
1121 vs->input.offset += ret;
1123 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1124 size_t len = vs->read_handler_expect;
1125 int ret;
1127 ret = vs->read_handler(vs, vs->input.buffer, len);
1128 if (vs->csock == -1) {
1129 vnc_disconnect_finish(vs);
1130 return;
1133 if (!ret) {
1134 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1135 vs->input.offset -= len;
1136 } else {
1137 vs->read_handler_expect = ret;
1142 static void vnc_write(VncState *vs, const void *data, size_t len)
1144 buffer_reserve(&vs->output, len);
1146 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1147 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1150 buffer_append(&vs->output, data, len);
1153 static void vnc_write_s32(VncState *vs, int32_t value)
1155 vnc_write_u32(vs, *(uint32_t *)&value);
1158 static void vnc_write_u32(VncState *vs, uint32_t value)
1160 uint8_t buf[4];
1162 buf[0] = (value >> 24) & 0xFF;
1163 buf[1] = (value >> 16) & 0xFF;
1164 buf[2] = (value >> 8) & 0xFF;
1165 buf[3] = value & 0xFF;
1167 vnc_write(vs, buf, 4);
1170 static void vnc_write_u16(VncState *vs, uint16_t value)
1172 uint8_t buf[2];
1174 buf[0] = (value >> 8) & 0xFF;
1175 buf[1] = value & 0xFF;
1177 vnc_write(vs, buf, 2);
1180 static void vnc_write_u8(VncState *vs, uint8_t value)
1182 vnc_write(vs, (char *)&value, 1);
1185 static void vnc_flush(VncState *vs)
1187 if (vs->csock != -1 && vs->output.offset)
1188 vnc_client_write(vs);
1191 static uint8_t read_u8(uint8_t *data, size_t offset)
1193 return data[offset];
1196 static uint16_t read_u16(uint8_t *data, size_t offset)
1198 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1201 static int32_t read_s32(uint8_t *data, size_t offset)
1203 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1204 (data[offset + 2] << 8) | data[offset + 3]);
1207 static uint32_t read_u32(uint8_t *data, size_t offset)
1209 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1210 (data[offset + 2] << 8) | data[offset + 3]);
1213 #ifdef CONFIG_VNC_TLS
1214 static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
1215 const void *data,
1216 size_t len) {
1217 struct VncState *vs = (struct VncState *)transport;
1218 int ret;
1220 retry:
1221 ret = send(vs->csock, data, len, 0);
1222 if (ret < 0) {
1223 if (errno == EINTR)
1224 goto retry;
1225 return -1;
1227 return ret;
1231 static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
1232 void *data,
1233 size_t len) {
1234 struct VncState *vs = (struct VncState *)transport;
1235 int ret;
1237 retry:
1238 ret = recv(vs->csock, data, len, 0);
1239 if (ret < 0) {
1240 if (errno == EINTR)
1241 goto retry;
1242 return -1;
1244 return ret;
1246 #endif /* CONFIG_VNC_TLS */
1248 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1252 static void check_pointer_type_change(VncState *vs, int absolute)
1254 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1255 vnc_write_u8(vs, 0);
1256 vnc_write_u8(vs, 0);
1257 vnc_write_u16(vs, 1);
1258 vnc_framebuffer_update(vs, absolute, 0,
1259 ds_get_width(vs->ds), ds_get_height(vs->ds),
1260 VNC_ENCODING_POINTER_TYPE_CHANGE);
1261 vnc_flush(vs);
1263 vs->absolute = absolute;
1266 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1268 int buttons = 0;
1269 int dz = 0;
1271 if (button_mask & 0x01)
1272 buttons |= MOUSE_EVENT_LBUTTON;
1273 if (button_mask & 0x02)
1274 buttons |= MOUSE_EVENT_MBUTTON;
1275 if (button_mask & 0x04)
1276 buttons |= MOUSE_EVENT_RBUTTON;
1277 if (button_mask & 0x08)
1278 dz = -1;
1279 if (button_mask & 0x10)
1280 dz = 1;
1282 if (vs->absolute) {
1283 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1284 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1285 dz, buttons);
1286 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1287 x -= 0x7FFF;
1288 y -= 0x7FFF;
1290 kbd_mouse_event(x, y, dz, buttons);
1291 } else {
1292 if (vs->last_x != -1)
1293 kbd_mouse_event(x - vs->last_x,
1294 y - vs->last_y,
1295 dz, buttons);
1296 vs->last_x = x;
1297 vs->last_y = y;
1300 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1303 static void reset_keys(VncState *vs)
1305 int i;
1306 for(i = 0; i < 256; i++) {
1307 if (vs->modifiers_state[i]) {
1308 if (i & 0x80)
1309 kbd_put_keycode(0xe0);
1310 kbd_put_keycode(i | 0x80);
1311 vs->modifiers_state[i] = 0;
1316 static void press_key(VncState *vs, int keysym)
1318 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1319 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
1322 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1324 /* QEMU console switch */
1325 switch(keycode) {
1326 case 0x2a: /* Left Shift */
1327 case 0x36: /* Right Shift */
1328 case 0x1d: /* Left CTRL */
1329 case 0x9d: /* Right CTRL */
1330 case 0x38: /* Left ALT */
1331 case 0xb8: /* Right ALT */
1332 if (down)
1333 vs->modifiers_state[keycode] = 1;
1334 else
1335 vs->modifiers_state[keycode] = 0;
1336 break;
1337 case 0x02 ... 0x0a: /* '1' to '9' keys */
1338 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1339 /* Reset the modifiers sent to the current console */
1340 reset_keys(vs);
1341 console_select(keycode - 0x02);
1342 return;
1344 break;
1345 case 0x3a: /* CapsLock */
1346 case 0x45: /* NumLock */
1347 if (!down)
1348 vs->modifiers_state[keycode] ^= 1;
1349 break;
1352 if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1353 /* If the numlock state needs to change then simulate an additional
1354 keypress before sending this one. This will happen if the user
1355 toggles numlock away from the VNC window.
1357 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1358 if (!vs->modifiers_state[0x45]) {
1359 vs->modifiers_state[0x45] = 1;
1360 press_key(vs, 0xff7f);
1362 } else {
1363 if (vs->modifiers_state[0x45]) {
1364 vs->modifiers_state[0x45] = 0;
1365 press_key(vs, 0xff7f);
1370 if (is_graphic_console()) {
1371 if (keycode & 0x80)
1372 kbd_put_keycode(0xe0);
1373 if (down)
1374 kbd_put_keycode(keycode & 0x7f);
1375 else
1376 kbd_put_keycode(keycode | 0x80);
1377 } else {
1378 /* QEMU console emulation */
1379 if (down) {
1380 switch (keycode) {
1381 case 0x2a: /* Left Shift */
1382 case 0x36: /* Right Shift */
1383 case 0x1d: /* Left CTRL */
1384 case 0x9d: /* Right CTRL */
1385 case 0x38: /* Left ALT */
1386 case 0xb8: /* Right ALT */
1387 break;
1388 case 0xc8:
1389 case 0x48:
1390 kbd_put_keysym(QEMU_KEY_UP);
1391 break;
1392 case 0xd0:
1393 case 0x50:
1394 kbd_put_keysym(QEMU_KEY_DOWN);
1395 break;
1396 case 0xcb:
1397 case 0x4b:
1398 kbd_put_keysym(QEMU_KEY_LEFT);
1399 break;
1400 case 0xcd:
1401 case 0x4d:
1402 kbd_put_keysym(QEMU_KEY_RIGHT);
1403 break;
1404 case 0xd3:
1405 case 0x53:
1406 kbd_put_keysym(QEMU_KEY_DELETE);
1407 break;
1408 case 0xc7:
1409 case 0x47:
1410 kbd_put_keysym(QEMU_KEY_HOME);
1411 break;
1412 case 0xcf:
1413 case 0x4f:
1414 kbd_put_keysym(QEMU_KEY_END);
1415 break;
1416 case 0xc9:
1417 case 0x49:
1418 kbd_put_keysym(QEMU_KEY_PAGEUP);
1419 break;
1420 case 0xd1:
1421 case 0x51:
1422 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1423 break;
1424 default:
1425 kbd_put_keysym(sym);
1426 break;
1432 static void key_event(VncState *vs, int down, uint32_t sym)
1434 int keycode;
1436 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1437 sym = sym - 'A' + 'a';
1439 keycode = keysym2scancode(vs->vd->kbd_layout, sym & 0xFFFF);
1440 do_key_event(vs, down, keycode, sym);
1443 static void ext_key_event(VncState *vs, int down,
1444 uint32_t sym, uint16_t keycode)
1446 /* if the user specifies a keyboard layout, always use it */
1447 if (keyboard_layout)
1448 key_event(vs, down, sym);
1449 else
1450 do_key_event(vs, down, keycode, sym);
1453 static void framebuffer_update_request(VncState *vs, int incremental,
1454 int x_position, int y_position,
1455 int w, int h)
1457 if (x_position > ds_get_width(vs->ds))
1458 x_position = ds_get_width(vs->ds);
1459 if (y_position > ds_get_height(vs->ds))
1460 y_position = ds_get_height(vs->ds);
1461 if (x_position + w >= ds_get_width(vs->ds))
1462 w = ds_get_width(vs->ds) - x_position;
1463 if (y_position + h >= ds_get_height(vs->ds))
1464 h = ds_get_height(vs->ds) - y_position;
1466 int i;
1467 vs->need_update = 1;
1468 if (!incremental) {
1469 char *old_row = vs->old_data + y_position * ds_get_linesize(vs->ds);
1471 for (i = 0; i < h; i++) {
1472 vnc_set_bits(vs->dirty_row[y_position + i],
1473 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1474 memset(old_row, 42, ds_get_width(vs->ds) * ds_get_bytes_per_pixel(vs->ds));
1475 old_row += ds_get_linesize(vs->ds);
1480 static void send_ext_key_event_ack(VncState *vs)
1482 vnc_write_u8(vs, 0);
1483 vnc_write_u8(vs, 0);
1484 vnc_write_u16(vs, 1);
1485 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1486 VNC_ENCODING_EXT_KEY_EVENT);
1487 vnc_flush(vs);
1490 static void send_ext_audio_ack(VncState *vs)
1492 vnc_write_u8(vs, 0);
1493 vnc_write_u8(vs, 0);
1494 vnc_write_u16(vs, 1);
1495 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1496 VNC_ENCODING_AUDIO);
1497 vnc_flush(vs);
1500 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1502 int i;
1503 unsigned int enc = 0;
1505 vnc_zlib_init(vs);
1506 vs->features = 0;
1507 vs->vnc_encoding = 0;
1508 vs->tight_compression = 9;
1509 vs->tight_quality = 9;
1510 vs->absolute = -1;
1512 for (i = n_encodings - 1; i >= 0; i--) {
1513 enc = encodings[i];
1514 switch (enc) {
1515 case VNC_ENCODING_RAW:
1516 vs->vnc_encoding = enc;
1517 break;
1518 case VNC_ENCODING_COPYRECT:
1519 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1520 break;
1521 case VNC_ENCODING_HEXTILE:
1522 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1523 vs->vnc_encoding = enc;
1524 break;
1525 case VNC_ENCODING_ZLIB:
1526 vs->features |= VNC_FEATURE_ZLIB_MASK;
1527 vs->vnc_encoding = enc;
1528 break;
1529 case VNC_ENCODING_DESKTOPRESIZE:
1530 vs->features |= VNC_FEATURE_RESIZE_MASK;
1531 break;
1532 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1533 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1534 break;
1535 case VNC_ENCODING_EXT_KEY_EVENT:
1536 send_ext_key_event_ack(vs);
1537 break;
1538 case VNC_ENCODING_AUDIO:
1539 send_ext_audio_ack(vs);
1540 break;
1541 case VNC_ENCODING_WMVi:
1542 vs->features |= VNC_FEATURE_WMVI_MASK;
1543 break;
1544 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1545 vs->tight_compression = (enc & 0x0F);
1546 break;
1547 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1548 vs->tight_quality = (enc & 0x0F);
1549 break;
1550 default:
1551 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1552 break;
1556 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1559 static void set_pixel_conversion(VncState *vs)
1561 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1562 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1563 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1564 vs->write_pixels = vnc_write_pixels_copy;
1565 switch (vs->ds->surface->pf.bits_per_pixel) {
1566 case 8:
1567 vs->send_hextile_tile = send_hextile_tile_8;
1568 break;
1569 case 16:
1570 vs->send_hextile_tile = send_hextile_tile_16;
1571 break;
1572 case 32:
1573 vs->send_hextile_tile = send_hextile_tile_32;
1574 break;
1576 } else {
1577 vs->write_pixels = vnc_write_pixels_generic;
1578 switch (vs->ds->surface->pf.bits_per_pixel) {
1579 case 8:
1580 vs->send_hextile_tile = send_hextile_tile_generic_8;
1581 break;
1582 case 16:
1583 vs->send_hextile_tile = send_hextile_tile_generic_16;
1584 break;
1585 case 32:
1586 vs->send_hextile_tile = send_hextile_tile_generic_32;
1587 break;
1592 static void set_pixel_format(VncState *vs,
1593 int bits_per_pixel, int depth,
1594 int big_endian_flag, int true_color_flag,
1595 int red_max, int green_max, int blue_max,
1596 int red_shift, int green_shift, int blue_shift)
1598 if (!true_color_flag) {
1599 vnc_client_error(vs);
1600 return;
1603 vs->clientds = vs->serverds;
1604 vs->clientds.pf.rmax = red_max;
1605 count_bits(vs->clientds.pf.rbits, red_max);
1606 vs->clientds.pf.rshift = red_shift;
1607 vs->clientds.pf.rmask = red_max << red_shift;
1608 vs->clientds.pf.gmax = green_max;
1609 count_bits(vs->clientds.pf.gbits, green_max);
1610 vs->clientds.pf.gshift = green_shift;
1611 vs->clientds.pf.gmask = green_max << green_shift;
1612 vs->clientds.pf.bmax = blue_max;
1613 count_bits(vs->clientds.pf.bbits, blue_max);
1614 vs->clientds.pf.bshift = blue_shift;
1615 vs->clientds.pf.bmask = blue_max << blue_shift;
1616 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1617 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1618 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1619 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1621 set_pixel_conversion(vs);
1623 vga_hw_invalidate();
1624 vga_hw_update();
1627 static void pixel_format_message (VncState *vs) {
1628 char pad[3] = { 0, 0, 0 };
1630 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1631 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1633 #ifdef WORDS_BIGENDIAN
1634 vnc_write_u8(vs, 1); /* big-endian-flag */
1635 #else
1636 vnc_write_u8(vs, 0); /* big-endian-flag */
1637 #endif
1638 vnc_write_u8(vs, 1); /* true-color-flag */
1639 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1640 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1641 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1642 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1643 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1644 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1645 if (vs->ds->surface->pf.bits_per_pixel == 32)
1646 vs->send_hextile_tile = send_hextile_tile_32;
1647 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1648 vs->send_hextile_tile = send_hextile_tile_16;
1649 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1650 vs->send_hextile_tile = send_hextile_tile_8;
1651 vs->clientds = *(vs->ds->surface);
1652 vs->clientds.flags |= ~QEMU_ALLOCATED_FLAG;
1653 vs->write_pixels = vnc_write_pixels_copy;
1655 vnc_write(vs, pad, 3); /* padding */
1658 static void vnc_dpy_setdata(DisplayState *ds)
1660 /* We don't have to do anything */
1663 static void vnc_colordepth(VncState *vs)
1665 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1666 /* Sending a WMVi message to notify the client*/
1667 vnc_write_u8(vs, 0); /* msg id */
1668 vnc_write_u8(vs, 0);
1669 vnc_write_u16(vs, 1); /* number of rects */
1670 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1671 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1672 pixel_format_message(vs);
1673 vnc_flush(vs);
1674 } else {
1675 set_pixel_conversion(vs);
1679 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1681 int i;
1682 uint16_t limit;
1684 switch (data[0]) {
1685 case 0:
1686 if (len == 1)
1687 return 20;
1689 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1690 read_u8(data, 6), read_u8(data, 7),
1691 read_u16(data, 8), read_u16(data, 10),
1692 read_u16(data, 12), read_u8(data, 14),
1693 read_u8(data, 15), read_u8(data, 16));
1694 break;
1695 case 2:
1696 if (len == 1)
1697 return 4;
1699 if (len == 4) {
1700 limit = read_u16(data, 2);
1701 if (limit > 0)
1702 return 4 + (limit * 4);
1703 } else
1704 limit = read_u16(data, 2);
1706 for (i = 0; i < limit; i++) {
1707 int32_t val = read_s32(data, 4 + (i * 4));
1708 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1711 set_encodings(vs, (int32_t *)(data + 4), limit);
1712 break;
1713 case 3:
1714 if (len == 1)
1715 return 10;
1717 framebuffer_update_request(vs,
1718 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1719 read_u16(data, 6), read_u16(data, 8));
1720 break;
1721 case 4:
1722 if (len == 1)
1723 return 8;
1725 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1726 break;
1727 case 5:
1728 if (len == 1)
1729 return 6;
1731 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1732 break;
1733 case 6:
1734 if (len == 1)
1735 return 8;
1737 if (len == 8) {
1738 uint32_t dlen = read_u32(data, 4);
1739 if (dlen > 0)
1740 return 8 + dlen;
1743 client_cut_text(vs, read_u32(data, 4), data + 8);
1744 break;
1745 case 255:
1746 if (len == 1)
1747 return 2;
1749 switch (read_u8(data, 1)) {
1750 case 0:
1751 if (len == 2)
1752 return 12;
1754 ext_key_event(vs, read_u16(data, 2),
1755 read_u32(data, 4), read_u32(data, 8));
1756 break;
1757 case 1:
1758 if (len == 2)
1759 return 4;
1761 switch (read_u16 (data, 2)) {
1762 case 0:
1763 audio_add(vs);
1764 break;
1765 case 1:
1766 audio_del(vs);
1767 break;
1768 case 2:
1769 if (len == 4)
1770 return 10;
1771 switch (read_u8(data, 4)) {
1772 case 0: vs->as.fmt = AUD_FMT_U8; break;
1773 case 1: vs->as.fmt = AUD_FMT_S8; break;
1774 case 2: vs->as.fmt = AUD_FMT_U16; break;
1775 case 3: vs->as.fmt = AUD_FMT_S16; break;
1776 case 4: vs->as.fmt = AUD_FMT_U32; break;
1777 case 5: vs->as.fmt = AUD_FMT_S32; break;
1778 default:
1779 printf("Invalid audio format %d\n", read_u8(data, 4));
1780 vnc_client_error(vs);
1781 break;
1783 vs->as.nchannels = read_u8(data, 5);
1784 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1785 printf("Invalid audio channel coount %d\n",
1786 read_u8(data, 5));
1787 vnc_client_error(vs);
1788 break;
1790 vs->as.freq = read_u32(data, 6);
1791 break;
1792 default:
1793 printf ("Invalid audio message %d\n", read_u8(data, 4));
1794 vnc_client_error(vs);
1795 break;
1797 break;
1799 default:
1800 printf("Msg: %d\n", read_u16(data, 0));
1801 vnc_client_error(vs);
1802 break;
1804 break;
1805 default:
1806 printf("Msg: %d\n", data[0]);
1807 vnc_client_error(vs);
1808 break;
1811 vnc_read_when(vs, protocol_client_msg, 1);
1812 return 0;
1815 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1817 char buf[1024];
1818 int size;
1820 vnc_write_u16(vs, ds_get_width(vs->ds));
1821 vnc_write_u16(vs, ds_get_height(vs->ds));
1823 pixel_format_message(vs);
1825 if (qemu_name)
1826 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1827 else
1828 size = snprintf(buf, sizeof(buf), "QEMU");
1830 vnc_write_u32(vs, size);
1831 vnc_write(vs, buf, size);
1832 vnc_flush(vs);
1834 vnc_read_when(vs, protocol_client_msg, 1);
1836 return 0;
1839 static void make_challenge(VncState *vs)
1841 int i;
1843 srand(time(NULL)+getpid()+getpid()*987654+rand());
1845 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1846 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1849 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1851 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1852 int i, j, pwlen;
1853 unsigned char key[8];
1855 if (!vs->vd->password || !vs->vd->password[0]) {
1856 VNC_DEBUG("No password configured on server");
1857 vnc_write_u32(vs, 1); /* Reject auth */
1858 if (vs->minor >= 8) {
1859 static const char err[] = "Authentication failed";
1860 vnc_write_u32(vs, sizeof(err));
1861 vnc_write(vs, err, sizeof(err));
1863 vnc_flush(vs);
1864 vnc_client_error(vs);
1865 return 0;
1868 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1870 /* Calculate the expected challenge response */
1871 pwlen = strlen(vs->vd->password);
1872 for (i=0; i<sizeof(key); i++)
1873 key[i] = i<pwlen ? vs->vd->password[i] : 0;
1874 deskey(key, EN0);
1875 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1876 des(response+j, response+j);
1878 /* Compare expected vs actual challenge response */
1879 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1880 VNC_DEBUG("Client challenge reponse did not match\n");
1881 vnc_write_u32(vs, 1); /* Reject auth */
1882 if (vs->minor >= 8) {
1883 static const char err[] = "Authentication failed";
1884 vnc_write_u32(vs, sizeof(err));
1885 vnc_write(vs, err, sizeof(err));
1887 vnc_flush(vs);
1888 vnc_client_error(vs);
1889 } else {
1890 VNC_DEBUG("Accepting VNC challenge response\n");
1891 vnc_write_u32(vs, 0); /* Accept auth */
1892 vnc_flush(vs);
1894 vnc_read_when(vs, protocol_client_init, 1);
1896 return 0;
1899 static int start_auth_vnc(VncState *vs)
1901 make_challenge(vs);
1902 /* Send client a 'random' challenge */
1903 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1904 vnc_flush(vs);
1906 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1907 return 0;
1911 #ifdef CONFIG_VNC_TLS
1912 #define DH_BITS 1024
1913 static gnutls_dh_params_t dh_params;
1915 static int vnc_tls_initialize(void)
1917 static int tlsinitialized = 0;
1919 if (tlsinitialized)
1920 return 1;
1922 if (gnutls_global_init () < 0)
1923 return 0;
1925 /* XXX ought to re-generate diffie-hellmen params periodically */
1926 if (gnutls_dh_params_init (&dh_params) < 0)
1927 return 0;
1928 if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1929 return 0;
1931 #if defined(_VNC_DEBUG) && _VNC_DEBUG >= 2
1932 gnutls_global_set_log_level(10);
1933 gnutls_global_set_log_function(vnc_debug_gnutls_log);
1934 #endif
1936 tlsinitialized = 1;
1938 return 1;
1941 static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1943 gnutls_anon_server_credentials anon_cred;
1944 int ret;
1946 if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1947 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1948 return NULL;
1951 gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1953 return anon_cred;
1957 static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1959 gnutls_certificate_credentials_t x509_cred;
1960 int ret;
1962 if (!vs->vd->x509cacert) {
1963 VNC_DEBUG("No CA x509 certificate specified\n");
1964 return NULL;
1966 if (!vs->vd->x509cert) {
1967 VNC_DEBUG("No server x509 certificate specified\n");
1968 return NULL;
1970 if (!vs->vd->x509key) {
1971 VNC_DEBUG("No server private key specified\n");
1972 return NULL;
1975 if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1976 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1977 return NULL;
1979 if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1980 vs->vd->x509cacert,
1981 GNUTLS_X509_FMT_PEM)) < 0) {
1982 VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1983 gnutls_certificate_free_credentials(x509_cred);
1984 return NULL;
1987 if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1988 vs->vd->x509cert,
1989 vs->vd->x509key,
1990 GNUTLS_X509_FMT_PEM)) < 0) {
1991 VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1992 gnutls_certificate_free_credentials(x509_cred);
1993 return NULL;
1996 if (vs->vd->x509cacrl) {
1997 if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1998 vs->vd->x509cacrl,
1999 GNUTLS_X509_FMT_PEM)) < 0) {
2000 VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
2001 gnutls_certificate_free_credentials(x509_cred);
2002 return NULL;
2006 gnutls_certificate_set_dh_params (x509_cred, dh_params);
2008 return x509_cred;
2011 static int vnc_validate_certificate(struct VncState *vs)
2013 int ret;
2014 unsigned int status;
2015 const gnutls_datum_t *certs;
2016 unsigned int nCerts, i;
2017 time_t now;
2019 VNC_DEBUG("Validating client certificate\n");
2020 if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
2021 VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
2022 return -1;
2025 if ((now = time(NULL)) == ((time_t)-1)) {
2026 return -1;
2029 if (status != 0) {
2030 if (status & GNUTLS_CERT_INVALID)
2031 VNC_DEBUG("The certificate is not trusted.\n");
2033 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
2034 VNC_DEBUG("The certificate hasn't got a known issuer.\n");
2036 if (status & GNUTLS_CERT_REVOKED)
2037 VNC_DEBUG("The certificate has been revoked.\n");
2039 if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
2040 VNC_DEBUG("The certificate uses an insecure algorithm\n");
2042 return -1;
2043 } else {
2044 VNC_DEBUG("Certificate is valid!\n");
2047 /* Only support x509 for now */
2048 if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
2049 return -1;
2051 if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
2052 return -1;
2054 for (i = 0 ; i < nCerts ; i++) {
2055 gnutls_x509_crt_t cert;
2056 VNC_DEBUG ("Checking certificate chain %d\n", i);
2057 if (gnutls_x509_crt_init (&cert) < 0)
2058 return -1;
2060 if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
2061 gnutls_x509_crt_deinit (cert);
2062 return -1;
2065 if (gnutls_x509_crt_get_expiration_time (cert) < now) {
2066 VNC_DEBUG("The certificate has expired\n");
2067 gnutls_x509_crt_deinit (cert);
2068 return -1;
2071 if (gnutls_x509_crt_get_activation_time (cert) > now) {
2072 VNC_DEBUG("The certificate is not yet activated\n");
2073 gnutls_x509_crt_deinit (cert);
2074 return -1;
2077 if (gnutls_x509_crt_get_activation_time (cert) > now) {
2078 VNC_DEBUG("The certificate is not yet activated\n");
2079 gnutls_x509_crt_deinit (cert);
2080 return -1;
2083 gnutls_x509_crt_deinit (cert);
2086 return 0;
2090 static int start_auth_vencrypt_subauth(VncState *vs)
2092 switch (vs->vd->subauth) {
2093 case VNC_AUTH_VENCRYPT_TLSNONE:
2094 case VNC_AUTH_VENCRYPT_X509NONE:
2095 VNC_DEBUG("Accept TLS auth none\n");
2096 vnc_write_u32(vs, 0); /* Accept auth completion */
2097 vnc_read_when(vs, protocol_client_init, 1);
2098 break;
2100 case VNC_AUTH_VENCRYPT_TLSVNC:
2101 case VNC_AUTH_VENCRYPT_X509VNC:
2102 VNC_DEBUG("Start TLS auth VNC\n");
2103 return start_auth_vnc(vs);
2105 default: /* Should not be possible, but just in case */
2106 VNC_DEBUG("Reject auth %d\n", vs->vd->auth);
2107 vnc_write_u8(vs, 1);
2108 if (vs->minor >= 8) {
2109 static const char err[] = "Unsupported authentication type";
2110 vnc_write_u32(vs, sizeof(err));
2111 vnc_write(vs, err, sizeof(err));
2113 vnc_client_error(vs);
2116 return 0;
2119 static void vnc_handshake_io(void *opaque);
2121 static int vnc_continue_handshake(struct VncState *vs) {
2122 int ret;
2124 if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
2125 if (!gnutls_error_is_fatal(ret)) {
2126 VNC_DEBUG("Handshake interrupted (blocking)\n");
2127 if (!gnutls_record_get_direction(vs->tls_session))
2128 qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
2129 else
2130 qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
2131 return 0;
2133 VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
2134 vnc_client_error(vs);
2135 return -1;
2138 if (vs->vd->x509verify) {
2139 if (vnc_validate_certificate(vs) < 0) {
2140 VNC_DEBUG("Client verification failed\n");
2141 vnc_client_error(vs);
2142 return -1;
2143 } else {
2144 VNC_DEBUG("Client verification passed\n");
2148 VNC_DEBUG("Handshake done, switching to TLS data mode\n");
2149 vs->wiremode = VNC_WIREMODE_TLS;
2150 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
2152 return start_auth_vencrypt_subauth(vs);
2155 static void vnc_handshake_io(void *opaque) {
2156 struct VncState *vs = (struct VncState *)opaque;
2158 VNC_DEBUG("Handshake IO continue\n");
2159 vnc_continue_handshake(vs);
2162 #define NEED_X509_AUTH(vs) \
2163 ((vs)->vd->subauth == VNC_AUTH_VENCRYPT_X509NONE || \
2164 (vs)->vd->subauth == VNC_AUTH_VENCRYPT_X509VNC || \
2165 (vs)->vd->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
2168 static int vnc_start_tls(struct VncState *vs) {
2169 static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
2170 static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
2171 static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
2172 static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
2174 VNC_DEBUG("Do TLS setup\n");
2175 if (vnc_tls_initialize() < 0) {
2176 VNC_DEBUG("Failed to init TLS\n");
2177 vnc_client_error(vs);
2178 return -1;
2180 if (vs->tls_session == NULL) {
2181 if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
2182 vnc_client_error(vs);
2183 return -1;
2186 if (gnutls_set_default_priority(vs->tls_session) < 0) {
2187 gnutls_deinit(vs->tls_session);
2188 vs->tls_session = NULL;
2189 vnc_client_error(vs);
2190 return -1;
2193 if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
2194 gnutls_deinit(vs->tls_session);
2195 vs->tls_session = NULL;
2196 vnc_client_error(vs);
2197 return -1;
2200 if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
2201 gnutls_deinit(vs->tls_session);
2202 vs->tls_session = NULL;
2203 vnc_client_error(vs);
2204 return -1;
2207 if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
2208 gnutls_deinit(vs->tls_session);
2209 vs->tls_session = NULL;
2210 vnc_client_error(vs);
2211 return -1;
2214 if (NEED_X509_AUTH(vs)) {
2215 gnutls_certificate_server_credentials x509_cred = vnc_tls_initialize_x509_cred(vs);
2216 if (!x509_cred) {
2217 gnutls_deinit(vs->tls_session);
2218 vs->tls_session = NULL;
2219 vnc_client_error(vs);
2220 return -1;
2222 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {
2223 gnutls_deinit(vs->tls_session);
2224 vs->tls_session = NULL;
2225 gnutls_certificate_free_credentials(x509_cred);
2226 vnc_client_error(vs);
2227 return -1;
2229 if (vs->vd->x509verify) {
2230 VNC_DEBUG("Requesting a client certificate\n");
2231 gnutls_certificate_server_set_request (vs->tls_session, GNUTLS_CERT_REQUEST);
2234 } else {
2235 gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
2236 if (!anon_cred) {
2237 gnutls_deinit(vs->tls_session);
2238 vs->tls_session = NULL;
2239 vnc_client_error(vs);
2240 return -1;
2242 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
2243 gnutls_deinit(vs->tls_session);
2244 vs->tls_session = NULL;
2245 gnutls_anon_free_server_credentials(anon_cred);
2246 vnc_client_error(vs);
2247 return -1;
2251 gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
2252 gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
2253 gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
2256 VNC_DEBUG("Start TLS handshake process\n");
2257 return vnc_continue_handshake(vs);
2260 static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)
2262 int auth = read_u32(data, 0);
2264 if (auth != vs->vd->subauth) {
2265 VNC_DEBUG("Rejecting auth %d\n", auth);
2266 vnc_write_u8(vs, 0); /* Reject auth */
2267 vnc_flush(vs);
2268 vnc_client_error(vs);
2269 } else {
2270 VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
2271 vnc_write_u8(vs, 1); /* Accept auth */
2272 vnc_flush(vs);
2274 if (vnc_start_tls(vs) < 0) {
2275 VNC_DEBUG("Failed to complete TLS\n");
2276 return 0;
2279 return 0;
2282 static int protocol_client_vencrypt_init(VncState *vs, uint8_t *data, size_t len)
2284 if (data[0] != 0 ||
2285 data[1] != 2) {
2286 VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
2287 vnc_write_u8(vs, 1); /* Reject version */
2288 vnc_flush(vs);
2289 vnc_client_error(vs);
2290 } else {
2291 VNC_DEBUG("Sending allowed auth %d\n", vs->vd->subauth);
2292 vnc_write_u8(vs, 0); /* Accept version */
2293 vnc_write_u8(vs, 1); /* Number of sub-auths */
2294 vnc_write_u32(vs, vs->vd->subauth); /* The supported auth */
2295 vnc_flush(vs);
2296 vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
2298 return 0;
2301 static int start_auth_vencrypt(VncState *vs)
2303 /* Send VeNCrypt version 0.2 */
2304 vnc_write_u8(vs, 0);
2305 vnc_write_u8(vs, 2);
2307 vnc_read_when(vs, protocol_client_vencrypt_init, 2);
2308 return 0;
2310 #endif /* CONFIG_VNC_TLS */
2312 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2314 /* We only advertise 1 auth scheme at a time, so client
2315 * must pick the one we sent. Verify this */
2316 if (data[0] != vs->vd->auth) { /* Reject auth */
2317 VNC_DEBUG("Reject auth %d\n", (int)data[0]);
2318 vnc_write_u32(vs, 1);
2319 if (vs->minor >= 8) {
2320 static const char err[] = "Authentication failed";
2321 vnc_write_u32(vs, sizeof(err));
2322 vnc_write(vs, err, sizeof(err));
2324 vnc_client_error(vs);
2325 } else { /* Accept requested auth */
2326 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2327 switch (vs->vd->auth) {
2328 case VNC_AUTH_NONE:
2329 VNC_DEBUG("Accept auth none\n");
2330 if (vs->minor >= 8) {
2331 vnc_write_u32(vs, 0); /* Accept auth completion */
2332 vnc_flush(vs);
2334 vnc_read_when(vs, protocol_client_init, 1);
2335 break;
2337 case VNC_AUTH_VNC:
2338 VNC_DEBUG("Start VNC auth\n");
2339 return start_auth_vnc(vs);
2341 #ifdef CONFIG_VNC_TLS
2342 case VNC_AUTH_VENCRYPT:
2343 VNC_DEBUG("Accept VeNCrypt auth\n");;
2344 return start_auth_vencrypt(vs);
2345 #endif /* CONFIG_VNC_TLS */
2347 default: /* Should not be possible, but just in case */
2348 VNC_DEBUG("Reject auth %d\n", vs->vd->auth);
2349 vnc_write_u8(vs, 1);
2350 if (vs->minor >= 8) {
2351 static const char err[] = "Authentication failed";
2352 vnc_write_u32(vs, sizeof(err));
2353 vnc_write(vs, err, sizeof(err));
2355 vnc_client_error(vs);
2358 return 0;
2361 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2363 char local[13];
2365 memcpy(local, version, 12);
2366 local[12] = 0;
2368 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2369 VNC_DEBUG("Malformed protocol version %s\n", local);
2370 vnc_client_error(vs);
2371 return 0;
2373 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2374 if (vs->major != 3 ||
2375 (vs->minor != 3 &&
2376 vs->minor != 4 &&
2377 vs->minor != 5 &&
2378 vs->minor != 7 &&
2379 vs->minor != 8)) {
2380 VNC_DEBUG("Unsupported client version\n");
2381 vnc_write_u32(vs, VNC_AUTH_INVALID);
2382 vnc_flush(vs);
2383 vnc_client_error(vs);
2384 return 0;
2386 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2387 * as equivalent to v3.3 by servers
2389 if (vs->minor == 4 || vs->minor == 5)
2390 vs->minor = 3;
2392 if (vs->minor == 3) {
2393 if (vs->vd->auth == VNC_AUTH_NONE) {
2394 VNC_DEBUG("Tell client auth none\n");
2395 vnc_write_u32(vs, vs->vd->auth);
2396 vnc_flush(vs);
2397 vnc_read_when(vs, protocol_client_init, 1);
2398 } else if (vs->vd->auth == VNC_AUTH_VNC) {
2399 VNC_DEBUG("Tell client VNC auth\n");
2400 vnc_write_u32(vs, vs->vd->auth);
2401 vnc_flush(vs);
2402 start_auth_vnc(vs);
2403 } else {
2404 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2405 vnc_write_u32(vs, VNC_AUTH_INVALID);
2406 vnc_flush(vs);
2407 vnc_client_error(vs);
2409 } else {
2410 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2411 vnc_write_u8(vs, 1); /* num auth */
2412 vnc_write_u8(vs, vs->vd->auth);
2413 vnc_read_when(vs, protocol_client_auth, 1);
2414 vnc_flush(vs);
2417 return 0;
2420 static void vnc_connect(VncDisplay *vd, int csock)
2422 VncState *vs = qemu_mallocz(sizeof(VncState));
2423 vs->csock = csock;
2425 VNC_DEBUG("New client on socket %d\n", csock);
2426 dcl->idle = 0;
2427 socket_set_nonblock(vs->csock);
2428 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2430 vs->vd = vd;
2431 vs->ds = vd->ds;
2432 vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
2433 vs->last_x = -1;
2434 vs->last_y = -1;
2436 vs->as.freq = 44100;
2437 vs->as.nchannels = 2;
2438 vs->as.fmt = AUD_FMT_S16;
2439 vs->as.endianness = 0;
2441 vnc_resize(vs);
2442 vnc_write(vs, "RFB 003.008\n", 12);
2443 vnc_flush(vs);
2444 vnc_read_when(vs, protocol_version, 12);
2445 memset(vs->old_data, 0, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));
2446 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
2447 reset_keys(vs);
2449 vs->next = vd->clients;
2450 vd->clients = vs;
2452 vnc_update_client(vs);
2453 /* vs might be free()ed here */
2456 static void vnc_listen_read(void *opaque)
2458 VncDisplay *vs = opaque;
2459 struct sockaddr_in addr;
2460 socklen_t addrlen = sizeof(addr);
2462 /* Catch-up */
2463 vga_hw_update();
2465 int csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2466 if (csock != -1) {
2467 vnc_connect(vs, csock);
2471 void vnc_display_init(DisplayState *ds)
2473 VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2475 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2477 ds->opaque = vs;
2478 dcl->idle = 1;
2479 vnc_display = vs;
2481 vs->lsock = -1;
2483 vs->ds = ds;
2485 if (keyboard_layout)
2486 vs->kbd_layout = init_keyboard_layout(keyboard_layout);
2487 else
2488 vs->kbd_layout = init_keyboard_layout("en-us");
2490 if (!vs->kbd_layout)
2491 exit(1);
2493 dcl->dpy_copy = vnc_dpy_copy;
2494 dcl->dpy_update = vnc_dpy_update;
2495 dcl->dpy_resize = vnc_dpy_resize;
2496 dcl->dpy_setdata = vnc_dpy_setdata;
2497 register_displaychangelistener(ds, dcl);
2500 #ifdef CONFIG_VNC_TLS
2501 static int vnc_set_x509_credential(VncDisplay *vs,
2502 const char *certdir,
2503 const char *filename,
2504 char **cred,
2505 int ignoreMissing)
2507 struct stat sb;
2509 if (*cred) {
2510 qemu_free(*cred);
2511 *cred = NULL;
2514 *cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2);
2516 strcpy(*cred, certdir);
2517 strcat(*cred, "/");
2518 strcat(*cred, filename);
2520 VNC_DEBUG("Check %s\n", *cred);
2521 if (stat(*cred, &sb) < 0) {
2522 qemu_free(*cred);
2523 *cred = NULL;
2524 if (ignoreMissing && errno == ENOENT)
2525 return 0;
2526 return -1;
2529 return 0;
2532 static int vnc_set_x509_credential_dir(VncDisplay *vs,
2533 const char *certdir)
2535 if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)
2536 goto cleanup;
2537 if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)
2538 goto cleanup;
2539 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)
2540 goto cleanup;
2541 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)
2542 goto cleanup;
2544 return 0;
2546 cleanup:
2547 qemu_free(vs->x509cacert);
2548 qemu_free(vs->x509cacrl);
2549 qemu_free(vs->x509cert);
2550 qemu_free(vs->x509key);
2551 vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2552 return -1;
2554 #endif /* CONFIG_VNC_TLS */
2556 void vnc_display_close(DisplayState *ds)
2558 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2560 if (!vs)
2561 return;
2562 if (vs->display) {
2563 qemu_free(vs->display);
2564 vs->display = NULL;
2566 if (vs->lsock != -1) {
2567 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2568 close(vs->lsock);
2569 vs->lsock = -1;
2571 vs->auth = VNC_AUTH_INVALID;
2572 #ifdef CONFIG_VNC_TLS
2573 vs->subauth = VNC_AUTH_INVALID;
2574 vs->x509verify = 0;
2575 #endif
2578 int vnc_display_password(DisplayState *ds, const char *password)
2580 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2582 if (vs->password) {
2583 qemu_free(vs->password);
2584 vs->password = NULL;
2586 if (password && password[0]) {
2587 if (!(vs->password = qemu_strdup(password)))
2588 return -1;
2591 return 0;
2594 int vnc_display_open(DisplayState *ds, const char *display)
2596 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2597 const char *options;
2598 int password = 0;
2599 int reverse = 0;
2600 int to_port = 0;
2601 #ifdef CONFIG_VNC_TLS
2602 int tls = 0, x509 = 0;
2603 #endif
2605 if (!vnc_display)
2606 return -1;
2607 vnc_display_close(ds);
2608 if (strcmp(display, "none") == 0)
2609 return 0;
2611 if (!(vs->display = strdup(display)))
2612 return -1;
2614 options = display;
2615 while ((options = strchr(options, ','))) {
2616 options++;
2617 if (strncmp(options, "password", 8) == 0) {
2618 password = 1; /* Require password auth */
2619 } else if (strncmp(options, "reverse", 7) == 0) {
2620 reverse = 1;
2621 } else if (strncmp(options, "to=", 3) == 0) {
2622 to_port = atoi(options+3) + 5900;
2623 #ifdef CONFIG_VNC_TLS
2624 } else if (strncmp(options, "tls", 3) == 0) {
2625 tls = 1; /* Require TLS */
2626 } else if (strncmp(options, "x509", 4) == 0) {
2627 char *start, *end;
2628 x509 = 1; /* Require x509 certificates */
2629 if (strncmp(options, "x509verify", 10) == 0)
2630 vs->x509verify = 1; /* ...and verify client certs */
2632 /* Now check for 'x509=/some/path' postfix
2633 * and use that to setup x509 certificate/key paths */
2634 start = strchr(options, '=');
2635 end = strchr(options, ',');
2636 if (start && (!end || (start < end))) {
2637 int len = end ? end-(start+1) : strlen(start+1);
2638 char *path = qemu_strndup(start + 1, len);
2640 VNC_DEBUG("Trying certificate path '%s'\n", path);
2641 if (vnc_set_x509_credential_dir(vs, path) < 0) {
2642 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2643 qemu_free(path);
2644 qemu_free(vs->display);
2645 vs->display = NULL;
2646 return -1;
2648 qemu_free(path);
2649 } else {
2650 fprintf(stderr, "No certificate path provided\n");
2651 qemu_free(vs->display);
2652 vs->display = NULL;
2653 return -1;
2655 #endif
2659 if (password) {
2660 #ifdef CONFIG_VNC_TLS
2661 if (tls) {
2662 vs->auth = VNC_AUTH_VENCRYPT;
2663 if (x509) {
2664 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2665 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2666 } else {
2667 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2668 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2670 } else {
2671 #endif
2672 VNC_DEBUG("Initializing VNC server with password auth\n");
2673 vs->auth = VNC_AUTH_VNC;
2674 #ifdef CONFIG_VNC_TLS
2675 vs->subauth = VNC_AUTH_INVALID;
2677 #endif
2678 } else {
2679 #ifdef CONFIG_VNC_TLS
2680 if (tls) {
2681 vs->auth = VNC_AUTH_VENCRYPT;
2682 if (x509) {
2683 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2684 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2685 } else {
2686 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2687 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2689 } else {
2690 #endif
2691 VNC_DEBUG("Initializing VNC server with no auth\n");
2692 vs->auth = VNC_AUTH_NONE;
2693 #ifdef CONFIG_VNC_TLS
2694 vs->subauth = VNC_AUTH_INVALID;
2696 #endif
2699 if (reverse) {
2700 /* connect to viewer */
2701 if (strncmp(display, "unix:", 5) == 0)
2702 vs->lsock = unix_connect(display+5);
2703 else
2704 vs->lsock = inet_connect(display, SOCK_STREAM);
2705 if (-1 == vs->lsock) {
2706 free(vs->display);
2707 vs->display = NULL;
2708 return -1;
2709 } else {
2710 int csock = vs->lsock;
2711 vs->lsock = -1;
2712 vnc_connect(vs, csock);
2714 return 0;
2716 } else {
2717 /* listen for connects */
2718 char *dpy;
2719 dpy = qemu_malloc(256);
2720 if (strncmp(display, "unix:", 5) == 0) {
2721 pstrcpy(dpy, 256, "unix:");
2722 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2723 } else {
2724 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2726 if (-1 == vs->lsock) {
2727 free(dpy);
2728 return -1;
2729 } else {
2730 free(vs->display);
2731 vs->display = dpy;
2734 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);