blob: 8b7d19f0f499118bfc369a6e09c9a90c267e6db2 [file] [log] [blame]
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -08001/*
2 * QEMU VNC display driver
3 *
4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5 * Copyright (C) 2006 Fabrice Bellard
6 *
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:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
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.
24 */
25
26#include "qemu-common.h"
27#include "console.h"
28#include "sysemu.h"
29#include "qemu_socket.h"
30#include "qemu-timer.h"
31
32#define VNC_REFRESH_INTERVAL (1000 / 30)
33
34#include "vnc_keysym.h"
35#include "keymaps.c"
36#include "d3des.h"
37
38#ifdef CONFIG_VNC_TLS
39#include <gnutls/gnutls.h>
40#include <gnutls/x509.h>
41#endif /* CONFIG_VNC_TLS */
42
43// #define _VNC_DEBUG 1
44
45#ifdef _VNC_DEBUG
46#define VNC_DEBUG(fmt, ...) do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
47
48#if CONFIG_VNC_TLS && _VNC_DEBUG >= 2
49/* Very verbose, so only enabled for _VNC_DEBUG >= 2 */
50static void vnc_debug_gnutls_log(int level, const char* str) {
51 VNC_DEBUG("%d %s", level, str);
52}
53#endif /* CONFIG_VNC_TLS && _VNC_DEBUG */
54#else
55#define VNC_DEBUG(fmt, ...) do { } while (0)
56#endif
57
58
59typedef struct Buffer
60{
61 size_t capacity;
62 size_t offset;
63 uint8_t *buffer;
64} Buffer;
65
66typedef struct VncState VncState;
67
68typedef int VncReadEvent(VncState *vs, uint8_t *data, size_t len);
69
70typedef void VncWritePixels(VncState *vs, void *data, int size);
71
72typedef void VncSendHextileTile(VncState *vs,
73 int x, int y, int w, int h,
74 void *last_bg,
75 void *last_fg,
76 int *has_bg, int *has_fg);
77
78#define VNC_MAX_WIDTH 2048
79#define VNC_MAX_HEIGHT 2048
80#define VNC_DIRTY_WORDS (VNC_MAX_WIDTH / (16 * 32))
81
82#define VNC_AUTH_CHALLENGE_SIZE 16
83
84enum {
85 VNC_AUTH_INVALID = 0,
86 VNC_AUTH_NONE = 1,
87 VNC_AUTH_VNC = 2,
88 VNC_AUTH_RA2 = 5,
89 VNC_AUTH_RA2NE = 6,
90 VNC_AUTH_TIGHT = 16,
91 VNC_AUTH_ULTRA = 17,
92 VNC_AUTH_TLS = 18,
93 VNC_AUTH_VENCRYPT = 19
94};
95
96#ifdef CONFIG_VNC_TLS
97enum {
98 VNC_WIREMODE_CLEAR,
99 VNC_WIREMODE_TLS,
100};
101
102enum {
103 VNC_AUTH_VENCRYPT_PLAIN = 256,
104 VNC_AUTH_VENCRYPT_TLSNONE = 257,
105 VNC_AUTH_VENCRYPT_TLSVNC = 258,
106 VNC_AUTH_VENCRYPT_TLSPLAIN = 259,
107 VNC_AUTH_VENCRYPT_X509NONE = 260,
108 VNC_AUTH_VENCRYPT_X509VNC = 261,
109 VNC_AUTH_VENCRYPT_X509PLAIN = 262,
110};
111
112#define X509_CA_CERT_FILE "ca-cert.pem"
113#define X509_CA_CRL_FILE "ca-crl.pem"
114#define X509_SERVER_KEY_FILE "server-key.pem"
115#define X509_SERVER_CERT_FILE "server-cert.pem"
116
117#endif /* CONFIG_VNC_TLS */
118
119struct VncState
120{
121 QEMUTimer *timer;
122 int lsock;
123 int csock;
124 DisplayState *ds;
125 int need_update;
126 int width;
127 int height;
128 uint32_t dirty_row[VNC_MAX_HEIGHT][VNC_DIRTY_WORDS];
129 char *old_data;
130 int depth; /* internal VNC frame buffer byte per pixel */
131 int has_resize;
132 int has_hextile;
133 int has_pointer_type_change;
134 int has_WMVi;
135 int absolute;
136 int last_x;
137 int last_y;
138
139 int major;
140 int minor;
141
142 char *display;
143 char *password;
144 int auth;
145#ifdef CONFIG_VNC_TLS
146 int subauth;
147 int x509verify;
148
149 char *x509cacert;
150 char *x509cacrl;
151 char *x509cert;
152 char *x509key;
153#endif
154 char challenge[VNC_AUTH_CHALLENGE_SIZE];
155
156#ifdef CONFIG_VNC_TLS
157 int wiremode;
158 gnutls_session_t tls_session;
159#endif
160
161 Buffer output;
162 Buffer input;
163 kbd_layout_t *kbd_layout;
164 /* current output mode information */
165 VncWritePixels *write_pixels;
166 VncSendHextileTile *send_hextile_tile;
167 int pix_bpp, pix_big_endian;
168 int client_red_shift, client_red_max, server_red_shift, server_red_max;
169 int client_green_shift, client_green_max, server_green_shift, server_green_max;
170 int client_blue_shift, client_blue_max, server_blue_shift, server_blue_max;
171
172 VncReadEvent *read_handler;
173 size_t read_handler_expect;
174 /* input */
175 uint8_t modifiers_state[256];
176};
177
178static VncState *vnc_state; /* needed for info vnc */
179
180void do_info_vnc(void)
181{
182 if (vnc_state == NULL)
183 term_printf("VNC server disabled\n");
184 else {
185 term_printf("VNC server active on: ");
186 term_print_filename(vnc_state->display);
187 term_printf("\n");
188
189 if (vnc_state->csock == -1)
190 term_printf("No client connected\n");
191 else
192 term_printf("Client connected\n");
193 }
194}
195
196/* TODO
197 1) Get the queue working for IO.
198 2) there is some weirdness when using the -S option (the screen is grey
199 and not totally invalidated
200 3) resolutions > 1024
201*/
202
203static void vnc_write(VncState *vs, const void *data, size_t len);
204static void vnc_write_u32(VncState *vs, uint32_t value);
205static void vnc_write_s32(VncState *vs, int32_t value);
206static void vnc_write_u16(VncState *vs, uint16_t value);
207static void vnc_write_u8(VncState *vs, uint8_t value);
208static void vnc_flush(VncState *vs);
209static void vnc_update_client(void *opaque);
210static void vnc_client_read(void *opaque);
211
212static void vnc_colordepth(DisplayState *ds, int depth);
213
214static inline void vnc_set_bit(uint32_t *d, int k)
215{
216 d[k >> 5] |= 1 << (k & 0x1f);
217}
218
219static inline void vnc_clear_bit(uint32_t *d, int k)
220{
221 d[k >> 5] &= ~(1 << (k & 0x1f));
222}
223
224static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
225{
226 int j;
227
228 j = 0;
229 while (n >= 32) {
230 d[j++] = -1;
231 n -= 32;
232 }
233 if (n > 0)
234 d[j++] = (1 << n) - 1;
235 while (j < nb_words)
236 d[j++] = 0;
237}
238
239static inline int vnc_get_bit(const uint32_t *d, int k)
240{
241 return (d[k >> 5] >> (k & 0x1f)) & 1;
242}
243
244static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
245 int nb_words)
246{
247 int i;
248 for(i = 0; i < nb_words; i++) {
249 if ((d1[i] & d2[i]) != 0)
250 return 1;
251 }
252 return 0;
253}
254
255static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
256{
257 VncState *vs = ds->opaque;
258 int i;
259
260 h += y;
261
262 /* round x down to ensure the loop only spans one 16-pixel block per,
263 iteration. otherwise, if (x % 16) != 0, the last iteration may span
264 two 16-pixel blocks but we only mark the first as dirty
265 */
266 w += (x % 16);
267 x -= (x % 16);
268
269 x = MIN(x, vs->width);
270 y = MIN(y, vs->height);
271 w = MIN(x + w, vs->width) - x;
272 h = MIN(h, vs->height);
273
274 for (; y < h; y++)
275 for (i = 0; i < w; i += 16)
276 vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
277}
278
279static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
280 int32_t encoding)
281{
282 vnc_write_u16(vs, x);
283 vnc_write_u16(vs, y);
284 vnc_write_u16(vs, w);
285 vnc_write_u16(vs, h);
286
287 vnc_write_s32(vs, encoding);
288}
289
290static void vnc_dpy_resize(DisplayState *ds, int w, int h)
291{
292 int size_changed;
293 VncState *vs = ds->opaque;
294
295 ds->data = qemu_realloc(ds->data, w * h * vs->depth);
296 vs->old_data = qemu_realloc(vs->old_data, w * h * vs->depth);
297
298 if (ds->data == NULL || vs->old_data == NULL) {
299 fprintf(stderr, "vnc: memory allocation failed\n");
300 exit(1);
301 }
302
303 if (ds->depth != vs->depth * 8) {
304 ds->depth = vs->depth * 8;
305 console_color_init(ds);
306 }
307 size_changed = ds->width != w || ds->height != h;
308 ds->width = w;
309 ds->height = h;
310 ds->linesize = w * vs->depth;
311 if (size_changed) {
312 vs->width = ds->width;
313 vs->height = ds->height;
314 if (vs->csock != -1 && vs->has_resize) {
315 vnc_write_u8(vs, 0); /* msg id */
316 vnc_write_u8(vs, 0);
317 vnc_write_u16(vs, 1); /* number of rects */
318 vnc_framebuffer_update(vs, 0, 0, ds->width, ds->height, -223);
319 vnc_flush(vs);
320 }
321 }
322
323 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
324 memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);
325}
326
327/* fastest code */
328static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
329{
330 vnc_write(vs, pixels, size);
331}
332
333/* slowest but generic code. */
334static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
335{
336 uint8_t r, g, b;
337
338 r = ((v >> vs->server_red_shift) & vs->server_red_max) * (vs->client_red_max + 1) /
339 (vs->server_red_max + 1);
340 g = ((v >> vs->server_green_shift) & vs->server_green_max) * (vs->client_green_max + 1) /
341 (vs->server_green_max + 1);
342 b = ((v >> vs->server_blue_shift) & vs->server_blue_max) * (vs->client_blue_max + 1) /
343 (vs->server_blue_max + 1);
344 v = (r << vs->client_red_shift) |
345 (g << vs->client_green_shift) |
346 (b << vs->client_blue_shift);
347 switch(vs->pix_bpp) {
348 case 1:
349 buf[0] = v;
350 break;
351 case 2:
352 if (vs->pix_big_endian) {
353 buf[0] = v >> 8;
354 buf[1] = v;
355 } else {
356 buf[1] = v >> 8;
357 buf[0] = v;
358 }
359 break;
360 default:
361 case 4:
362 if (vs->pix_big_endian) {
363 buf[0] = v >> 24;
364 buf[1] = v >> 16;
365 buf[2] = v >> 8;
366 buf[3] = v;
367 } else {
368 buf[3] = v >> 24;
369 buf[2] = v >> 16;
370 buf[1] = v >> 8;
371 buf[0] = v;
372 }
373 break;
374 }
375}
376
377static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
378{
379 uint8_t buf[4];
380
381 if (vs->depth == 4) {
382 uint32_t *pixels = pixels1;
383 int n, i;
384 n = size >> 2;
385 for(i = 0; i < n; i++) {
386 vnc_convert_pixel(vs, buf, pixels[i]);
387 vnc_write(vs, buf, vs->pix_bpp);
388 }
389 } else if (vs->depth == 2) {
390 uint16_t *pixels = pixels1;
391 int n, i;
392 n = size >> 1;
393 for(i = 0; i < n; i++) {
394 vnc_convert_pixel(vs, buf, pixels[i]);
395 vnc_write(vs, buf, vs->pix_bpp);
396 }
397 } else if (vs->depth == 1) {
398 uint8_t *pixels = pixels1;
399 int n, i;
400 n = size;
401 for(i = 0; i < n; i++) {
402 vnc_convert_pixel(vs, buf, pixels[i]);
403 vnc_write(vs, buf, vs->pix_bpp);
404 }
405 } else {
406 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
407 }
408}
409
410static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
411{
412 int i;
413 uint8_t *row;
414
415 vnc_framebuffer_update(vs, x, y, w, h, 0);
416
417 row = vs->ds->data + y * vs->ds->linesize + x * vs->depth;
418 for (i = 0; i < h; i++) {
419 vs->write_pixels(vs, row, w * vs->depth);
420 row += vs->ds->linesize;
421 }
422}
423
424static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
425{
426 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
427 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
428}
429
430#define BPP 8
431#include "vnchextile.h"
432#undef BPP
433
434#define BPP 16
435#include "vnchextile.h"
436#undef BPP
437
438#define BPP 32
439#include "vnchextile.h"
440#undef BPP
441
442#define GENERIC
443#define BPP 8
444#include "vnchextile.h"
445#undef BPP
446#undef GENERIC
447
448#define GENERIC
449#define BPP 16
450#include "vnchextile.h"
451#undef BPP
452#undef GENERIC
453
454#define GENERIC
455#define BPP 32
456#include "vnchextile.h"
457#undef BPP
458#undef GENERIC
459
460static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
461{
462 int i, j;
463 int has_fg, has_bg;
464 uint8_t *last_fg, *last_bg;
465
466 vnc_framebuffer_update(vs, x, y, w, h, 5);
467
468 last_fg = (uint8_t *) malloc(vs->depth);
469 last_bg = (uint8_t *) malloc(vs->depth);
470 has_fg = has_bg = 0;
471 for (j = y; j < (y + h); j += 16) {
472 for (i = x; i < (x + w); i += 16) {
473 vs->send_hextile_tile(vs, i, j,
474 MIN(16, x + w - i), MIN(16, y + h - j),
475 last_bg, last_fg, &has_bg, &has_fg);
476 }
477 }
478 free(last_fg);
479 free(last_bg);
480
481}
482
483static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
484{
485 if (vs->has_hextile)
486 send_framebuffer_update_hextile(vs, x, y, w, h);
487 else
488 send_framebuffer_update_raw(vs, x, y, w, h);
489}
490
491static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
492{
493 int src, dst;
494 uint8_t *src_row;
495 uint8_t *dst_row;
496 char *old_row;
497 int y = 0;
498 int pitch = ds->linesize;
499 VncState *vs = ds->opaque;
500
501 vnc_update_client(vs);
502
503 if (dst_y > src_y) {
504 y = h - 1;
505 pitch = -pitch;
506 }
507
508 src = (ds->linesize * (src_y + y) + vs->depth * src_x);
509 dst = (ds->linesize * (dst_y + y) + vs->depth * dst_x);
510
511 src_row = ds->data + src;
512 dst_row = ds->data + dst;
513 old_row = vs->old_data + dst;
514
515 for (y = 0; y < h; y++) {
516 memmove(old_row, src_row, w * vs->depth);
517 memmove(dst_row, src_row, w * vs->depth);
518 src_row += pitch;
519 dst_row += pitch;
520 old_row += pitch;
521 }
522
523 vnc_write_u8(vs, 0); /* msg id */
524 vnc_write_u8(vs, 0);
525 vnc_write_u16(vs, 1); /* number of rects */
526 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, 1);
527 vnc_write_u16(vs, src_x);
528 vnc_write_u16(vs, src_y);
529 vnc_flush(vs);
530}
531
532static int find_dirty_height(VncState *vs, int y, int last_x, int x)
533{
534 int h;
535
536 for (h = 1; h < (vs->height - y); h++) {
537 int tmp_x;
538 if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
539 break;
540 for (tmp_x = last_x; tmp_x < x; tmp_x++)
541 vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
542 }
543
544 return h;
545}
546
547static void vnc_update_client(void *opaque)
548{
549 VncState *vs = opaque;
550
551 if (vs->need_update && vs->csock != -1) {
552 int y;
553 uint8_t *row;
554 char *old_row;
555 uint32_t width_mask[VNC_DIRTY_WORDS];
556 int n_rectangles;
557 int saved_offset;
558 int has_dirty = 0;
559
560 vga_hw_update();
561
562 vnc_set_bits(width_mask, (vs->width / 16), VNC_DIRTY_WORDS);
563
564 /* Walk through the dirty map and eliminate tiles that
565 really aren't dirty */
566 row = vs->ds->data;
567 old_row = vs->old_data;
568
569 for (y = 0; y < vs->height; y++) {
570 if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
571 int x;
572 uint8_t *ptr;
573 char *old_ptr;
574
575 ptr = row;
576 old_ptr = (char*)old_row;
577
578 for (x = 0; x < vs->ds->width; x += 16) {
579 if (memcmp(old_ptr, ptr, 16 * vs->depth) == 0) {
580 vnc_clear_bit(vs->dirty_row[y], (x / 16));
581 } else {
582 has_dirty = 1;
583 memcpy(old_ptr, ptr, 16 * vs->depth);
584 }
585
586 ptr += 16 * vs->depth;
587 old_ptr += 16 * vs->depth;
588 }
589 }
590
591 row += vs->ds->linesize;
592 old_row += vs->ds->linesize;
593 }
594
595 if (!has_dirty) {
596 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
597 return;
598 }
599
600 /* Count rectangles */
601 n_rectangles = 0;
602 vnc_write_u8(vs, 0); /* msg id */
603 vnc_write_u8(vs, 0);
604 saved_offset = vs->output.offset;
605 vnc_write_u16(vs, 0);
606
607 for (y = 0; y < vs->height; y++) {
608 int x;
609 int last_x = -1;
610 for (x = 0; x < vs->width / 16; x++) {
611 if (vnc_get_bit(vs->dirty_row[y], x)) {
612 if (last_x == -1) {
613 last_x = x;
614 }
615 vnc_clear_bit(vs->dirty_row[y], x);
616 } else {
617 if (last_x != -1) {
618 int h = find_dirty_height(vs, y, last_x, x);
619 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
620 n_rectangles++;
621 }
622 last_x = -1;
623 }
624 }
625 if (last_x != -1) {
626 int h = find_dirty_height(vs, y, last_x, x);
627 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
628 n_rectangles++;
629 }
630 }
631 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
632 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
633 vnc_flush(vs);
634
635 }
636
637 if (vs->csock != -1) {
638 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
639 }
640
641}
642
643static int vnc_listen_poll(void *opaque)
644{
645 VncState *vs = opaque;
646 if (vs->csock == -1)
647 return 1;
648 return 0;
649}
650
651static void buffer_reserve(Buffer *buffer, size_t len)
652{
653 if ((buffer->capacity - buffer->offset) < len) {
654 buffer->capacity += (len + 1024);
655 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
656 if (buffer->buffer == NULL) {
657 fprintf(stderr, "vnc: out of memory\n");
658 exit(1);
659 }
660 }
661}
662
663static int buffer_empty(Buffer *buffer)
664{
665 return buffer->offset == 0;
666}
667
668static uint8_t *buffer_end(Buffer *buffer)
669{
670 return buffer->buffer + buffer->offset;
671}
672
673static void buffer_reset(Buffer *buffer)
674{
675 buffer->offset = 0;
676}
677
678static void buffer_append(Buffer *buffer, const void *data, size_t len)
679{
680 memcpy(buffer->buffer + buffer->offset, data, len);
681 buffer->offset += len;
682}
683
684static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
685{
686 if (ret == 0 || ret == -1) {
687 if (ret == -1) {
688 switch (last_errno) {
689 case EINTR:
690 case EAGAIN:
691#ifdef _WIN32
692 case EWOULDBLOCK:
693#endif
694 return 0;
695 default:
696 break;
697 }
698 }
699
700 VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
701 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
702 socket_close(vs->csock);
703 vs->csock = -1;
704 vs->ds->idle = 1;
705 buffer_reset(&vs->input);
706 buffer_reset(&vs->output);
707 vs->need_update = 0;
708#ifdef CONFIG_VNC_TLS
709 if (vs->tls_session) {
710 gnutls_deinit(vs->tls_session);
711 vs->tls_session = NULL;
712 }
713 vs->wiremode = VNC_WIREMODE_CLEAR;
714#endif /* CONFIG_VNC_TLS */
715 return 0;
716 }
717 return ret;
718}
719
720static void vnc_client_error(VncState *vs)
721{
722 vnc_client_io_error(vs, -1, EINVAL);
723}
724
725static void vnc_client_write(void *opaque)
726{
727 long ret;
728 VncState *vs = opaque;
729
730#ifdef CONFIG_VNC_TLS
731 if (vs->tls_session) {
732 ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
733 if (ret < 0) {
734 if (ret == GNUTLS_E_AGAIN)
735 errno = EAGAIN;
736 else
737 errno = EIO;
738 ret = -1;
739 }
740 } else
741#endif /* CONFIG_VNC_TLS */
742 ret = socket_send(vs->csock, vs->output.buffer, vs->output.offset);
743 ret = vnc_client_io_error(vs, ret, errno_str);
744 if (!ret)
745 return;
746
747 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
748 vs->output.offset -= ret;
749
750 if (vs->output.offset == 0) {
751 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
752 }
753}
754
755static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
756{
757 vs->read_handler = func;
758 vs->read_handler_expect = expecting;
759}
760
761static void vnc_client_read(void *opaque)
762{
763 VncState *vs = opaque;
764 long ret;
765
766 buffer_reserve(&vs->input, 4096);
767
768#ifdef CONFIG_VNC_TLS
769 if (vs->tls_session) {
770 ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
771 if (ret < 0) {
772 if (ret == GNUTLS_E_AGAIN)
773 errno = EAGAIN;
774 else
775 errno = EIO;
776 ret = -1;
777 }
778 } else
779#endif /* CONFIG_VNC_TLS */
780 ret = socket_recv(vs->csock, buffer_end(&vs->input), 4096);
781 ret = vnc_client_io_error(vs, ret, errno_str);
782 if (!ret)
783 return;
784
785 vs->input.offset += ret;
786
787 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
788 size_t len = vs->read_handler_expect;
789 int ret;
790
791 ret = vs->read_handler(vs, vs->input.buffer, len);
792 if (vs->csock == -1)
793 return;
794
795 if (!ret) {
796 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
797 vs->input.offset -= len;
798 } else {
799 vs->read_handler_expect = ret;
800 }
801 }
802}
803
804static void vnc_write(VncState *vs, const void *data, size_t len)
805{
806 buffer_reserve(&vs->output, len);
807
808 if (buffer_empty(&vs->output)) {
809 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
810 }
811
812 buffer_append(&vs->output, data, len);
813}
814
815static void vnc_write_s32(VncState *vs, int32_t value)
816{
817 vnc_write_u32(vs, *(uint32_t *)&value);
818}
819
820static void vnc_write_u32(VncState *vs, uint32_t value)
821{
822 uint8_t buf[4];
823
824 buf[0] = (value >> 24) & 0xFF;
825 buf[1] = (value >> 16) & 0xFF;
826 buf[2] = (value >> 8) & 0xFF;
827 buf[3] = value & 0xFF;
828
829 vnc_write(vs, buf, 4);
830}
831
832static void vnc_write_u16(VncState *vs, uint16_t value)
833{
834 uint8_t buf[2];
835
836 buf[0] = (value >> 8) & 0xFF;
837 buf[1] = value & 0xFF;
838
839 vnc_write(vs, buf, 2);
840}
841
842static void vnc_write_u8(VncState *vs, uint8_t value)
843{
844 vnc_write(vs, (char *)&value, 1);
845}
846
847static void vnc_flush(VncState *vs)
848{
849 if (vs->output.offset)
850 vnc_client_write(vs);
851}
852
853static uint8_t read_u8(uint8_t *data, size_t offset)
854{
855 return data[offset];
856}
857
858static uint16_t read_u16(uint8_t *data, size_t offset)
859{
860 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
861}
862
863static int32_t read_s32(uint8_t *data, size_t offset)
864{
865 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
866 (data[offset + 2] << 8) | data[offset + 3]);
867}
868
869static uint32_t read_u32(uint8_t *data, size_t offset)
870{
871 return ((data[offset] << 24) | (data[offset + 1] << 16) |
872 (data[offset + 2] << 8) | data[offset + 3]);
873}
874
875#ifdef CONFIG_VNC_TLS
876static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
877 const void *data,
878 size_t len) {
879 struct VncState *vs = (struct VncState *)transport;
880
881 return socket_send(vs->csock, data, len);
882}
883
884
885static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
886 void *data,
887 size_t len) {
888 struct VncState *vs = (struct VncState *)transport;
889
890 return socket_recv(vs->csock, data, len);
891}
892#endif /* CONFIG_VNC_TLS */
893
894static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
895{
896}
897
898static void check_pointer_type_change(VncState *vs, int absolute)
899{
900 if (vs->has_pointer_type_change && vs->absolute != absolute) {
901 vnc_write_u8(vs, 0);
902 vnc_write_u8(vs, 0);
903 vnc_write_u16(vs, 1);
904 vnc_framebuffer_update(vs, absolute, 0,
905 vs->ds->width, vs->ds->height, -257);
906 vnc_flush(vs);
907 }
908 vs->absolute = absolute;
909}
910
911static void pointer_event(VncState *vs, int button_mask, int x, int y)
912{
913 int buttons = 0;
914 int dz = 0;
915
916 if (button_mask & 0x01)
917 buttons |= MOUSE_EVENT_LBUTTON;
918 if (button_mask & 0x02)
919 buttons |= MOUSE_EVENT_MBUTTON;
920 if (button_mask & 0x04)
921 buttons |= MOUSE_EVENT_RBUTTON;
922 if (button_mask & 0x08)
923 dz = -1;
924 if (button_mask & 0x10)
925 dz = 1;
926
927 if (vs->absolute) {
928 kbd_mouse_event(x * 0x7FFF / (vs->ds->width - 1),
929 y * 0x7FFF / (vs->ds->height - 1),
930 dz, buttons);
931 } else if (vs->has_pointer_type_change) {
932 x -= 0x7FFF;
933 y -= 0x7FFF;
934
935 kbd_mouse_event(x, y, dz, buttons);
936 } else {
937 if (vs->last_x != -1)
938 kbd_mouse_event(x - vs->last_x,
939 y - vs->last_y,
940 dz, buttons);
941 vs->last_x = x;
942 vs->last_y = y;
943 }
944
945 check_pointer_type_change(vs, kbd_mouse_is_absolute());
946}
947
948static void reset_keys(VncState *vs)
949{
950 int i;
951 for(i = 0; i < 256; i++) {
952 if (vs->modifiers_state[i]) {
953 if (i & 0x80)
954 kbd_put_keycode(0xe0);
955 kbd_put_keycode(i | 0x80);
956 vs->modifiers_state[i] = 0;
957 }
958 }
959}
960
961static void press_key(VncState *vs, int keysym)
962{
963 kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) & 0x7f);
964 kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
965}
966
967static void do_key_event(VncState *vs, int down, int keycode, int sym)
968{
969 /* QEMU console switch */
970 switch(keycode) {
971 case 0x2a: /* Left Shift */
972 case 0x36: /* Right Shift */
973 case 0x1d: /* Left CTRL */
974 case 0x9d: /* Right CTRL */
975 case 0x38: /* Left ALT */
976 case 0xb8: /* Right ALT */
977 if (down)
978 vs->modifiers_state[keycode] = 1;
979 else
980 vs->modifiers_state[keycode] = 0;
981 break;
982 case 0x02 ... 0x0a: /* '1' to '9' keys */
983 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
984 /* Reset the modifiers sent to the current console */
985 reset_keys(vs);
986 console_select(keycode - 0x02);
987 return;
988 }
989 break;
990 case 0x3a: /* CapsLock */
991 case 0x45: /* NumLock */
992 if (!down)
993 vs->modifiers_state[keycode] ^= 1;
994 break;
995 }
996
997 if (keycode_is_keypad(vs->kbd_layout, keycode)) {
998 /* If the numlock state needs to change then simulate an additional
999 keypress before sending this one. This will happen if the user
1000 toggles numlock away from the VNC window.
1001 */
1002 if (keysym_is_numlock(vs->kbd_layout, sym & 0xFFFF)) {
1003 if (!vs->modifiers_state[0x45]) {
1004 vs->modifiers_state[0x45] = 1;
1005 press_key(vs, 0xff7f);
1006 }
1007 } else {
1008 if (vs->modifiers_state[0x45]) {
1009 vs->modifiers_state[0x45] = 0;
1010 press_key(vs, 0xff7f);
1011 }
1012 }
1013 }
1014
1015 if (is_graphic_console()) {
1016 if (keycode & 0x80)
1017 kbd_put_keycode(0xe0);
1018 if (down)
1019 kbd_put_keycode(keycode & 0x7f);
1020 else
1021 kbd_put_keycode(keycode | 0x80);
1022 } else {
1023 /* QEMU console emulation */
1024 if (down) {
1025 switch (keycode) {
1026 case 0x2a: /* Left Shift */
1027 case 0x36: /* Right Shift */
1028 case 0x1d: /* Left CTRL */
1029 case 0x9d: /* Right CTRL */
1030 case 0x38: /* Left ALT */
1031 case 0xb8: /* Right ALT */
1032 break;
1033 case 0xc8:
1034 kbd_put_keysym(QEMU_KEY_UP);
1035 break;
1036 case 0xd0:
1037 kbd_put_keysym(QEMU_KEY_DOWN);
1038 break;
1039 case 0xcb:
1040 kbd_put_keysym(QEMU_KEY_LEFT);
1041 break;
1042 case 0xcd:
1043 kbd_put_keysym(QEMU_KEY_RIGHT);
1044 break;
1045 case 0xd3:
1046 kbd_put_keysym(QEMU_KEY_DELETE);
1047 break;
1048 case 0xc7:
1049 kbd_put_keysym(QEMU_KEY_HOME);
1050 break;
1051 case 0xcf:
1052 kbd_put_keysym(QEMU_KEY_END);
1053 break;
1054 case 0xc9:
1055 kbd_put_keysym(QEMU_KEY_PAGEUP);
1056 break;
1057 case 0xd1:
1058 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1059 break;
1060 default:
1061 kbd_put_keysym(sym);
1062 break;
1063 }
1064 }
1065 }
1066}
1067
1068static void key_event(VncState *vs, int down, uint32_t sym)
1069{
1070 int keycode;
1071
1072 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1073 sym = sym - 'A' + 'a';
1074
1075 keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
1076 do_key_event(vs, down, keycode, sym);
1077}
1078
1079static void ext_key_event(VncState *vs, int down,
1080 uint32_t sym, uint16_t keycode)
1081{
1082 /* if the user specifies a keyboard layout, always use it */
1083 if (keyboard_layout)
1084 key_event(vs, down, sym);
1085 else
1086 do_key_event(vs, down, keycode, sym);
1087}
1088
1089static void framebuffer_update_request(VncState *vs, int incremental,
1090 int x_position, int y_position,
1091 int w, int h)
1092{
1093 if (x_position > vs->ds->width)
1094 x_position = vs->ds->width;
1095 if (y_position > vs->ds->height)
1096 y_position = vs->ds->height;
1097 if (x_position + w >= vs->ds->width)
1098 w = vs->ds->width - x_position;
1099 if (y_position + h >= vs->ds->height)
1100 h = vs->ds->height - y_position;
1101
1102 int i;
1103 vs->need_update = 1;
1104 if (!incremental) {
1105 char *old_row = vs->old_data + y_position * vs->ds->linesize;
1106
1107 for (i = 0; i < h; i++) {
1108 vnc_set_bits(vs->dirty_row[y_position + i],
1109 (vs->ds->width / 16), VNC_DIRTY_WORDS);
1110 memset(old_row, 42, vs->ds->width * vs->depth);
1111 old_row += vs->ds->linesize;
1112 }
1113 }
1114}
1115
1116static void send_ext_key_event_ack(VncState *vs)
1117{
1118 vnc_write_u8(vs, 0);
1119 vnc_write_u8(vs, 0);
1120 vnc_write_u16(vs, 1);
1121 vnc_framebuffer_update(vs, 0, 0, vs->ds->width, vs->ds->height, -258);
1122 vnc_flush(vs);
1123}
1124
1125static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1126{
1127 int i;
1128
1129 vs->has_hextile = 0;
1130 vs->has_resize = 0;
1131 vs->has_pointer_type_change = 0;
1132 vs->has_WMVi = 0;
1133 vs->absolute = -1;
1134 vs->ds->dpy_copy = NULL;
1135
1136 for (i = n_encodings - 1; i >= 0; i--) {
1137 switch (encodings[i]) {
1138 case 0: /* Raw */
1139 vs->has_hextile = 0;
1140 break;
1141 case 1: /* CopyRect */
1142 vs->ds->dpy_copy = vnc_copy;
1143 break;
1144 case 5: /* Hextile */
1145 vs->has_hextile = 1;
1146 break;
1147 case -223: /* DesktopResize */
1148 vs->has_resize = 1;
1149 break;
1150 case -257:
1151 vs->has_pointer_type_change = 1;
1152 break;
1153 case -258:
1154 send_ext_key_event_ack(vs);
1155 break;
1156 case 0x574D5669:
1157 vs->has_WMVi = 1;
1158 break;
1159 default:
1160 break;
1161 }
1162 }
1163
1164 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1165}
1166
1167static void set_pixel_format(VncState *vs,
1168 int bits_per_pixel, int depth,
1169 int big_endian_flag, int true_color_flag,
1170 int red_max, int green_max, int blue_max,
1171 int red_shift, int green_shift, int blue_shift)
1172{
1173 int host_big_endian_flag;
1174
1175#ifdef WORDS_BIGENDIAN
1176 host_big_endian_flag = 1;
1177#else
1178 host_big_endian_flag = 0;
1179#endif
1180 if (!true_color_flag) {
1181 fail:
1182 vnc_client_error(vs);
1183 return;
1184 }
1185 if (bits_per_pixel == 32 &&
1186 bits_per_pixel == vs->depth * 8 &&
1187 host_big_endian_flag == big_endian_flag &&
1188 red_max == 0xff && green_max == 0xff && blue_max == 0xff &&
1189 red_shift == 16 && green_shift == 8 && blue_shift == 0) {
1190 vs->depth = 4;
1191 vs->write_pixels = vnc_write_pixels_copy;
1192 vs->send_hextile_tile = send_hextile_tile_32;
1193 } else
1194 if (bits_per_pixel == 16 &&
1195 bits_per_pixel == vs->depth * 8 &&
1196 host_big_endian_flag == big_endian_flag &&
1197 red_max == 31 && green_max == 63 && blue_max == 31 &&
1198 red_shift == 11 && green_shift == 5 && blue_shift == 0) {
1199 vs->depth = 2;
1200 vs->write_pixels = vnc_write_pixels_copy;
1201 vs->send_hextile_tile = send_hextile_tile_16;
1202 } else
1203 if (bits_per_pixel == 8 &&
1204 bits_per_pixel == vs->depth * 8 &&
1205 red_max == 7 && green_max == 7 && blue_max == 3 &&
1206 red_shift == 5 && green_shift == 2 && blue_shift == 0) {
1207 vs->depth = 1;
1208 vs->write_pixels = vnc_write_pixels_copy;
1209 vs->send_hextile_tile = send_hextile_tile_8;
1210 } else
1211 {
1212 /* generic and slower case */
1213 if (bits_per_pixel != 8 &&
1214 bits_per_pixel != 16 &&
1215 bits_per_pixel != 32)
1216 goto fail;
1217 if (vs->depth == 4) {
1218 vs->send_hextile_tile = send_hextile_tile_generic_32;
1219 } else if (vs->depth == 2) {
1220 vs->send_hextile_tile = send_hextile_tile_generic_16;
1221 } else {
1222 vs->send_hextile_tile = send_hextile_tile_generic_8;
1223 }
1224
1225 vs->pix_big_endian = big_endian_flag;
1226 vs->write_pixels = vnc_write_pixels_generic;
1227 }
1228
1229 vs->client_red_shift = red_shift;
1230 vs->client_red_max = red_max;
1231 vs->client_green_shift = green_shift;
1232 vs->client_green_max = green_max;
1233 vs->client_blue_shift = blue_shift;
1234 vs->client_blue_max = blue_max;
1235 vs->pix_bpp = bits_per_pixel / 8;
1236
1237 vga_hw_invalidate();
1238 vga_hw_update();
1239}
1240
1241static void pixel_format_message (VncState *vs) {
1242 char pad[3] = { 0, 0, 0 };
1243
1244 vnc_write_u8(vs, vs->depth * 8); /* bits-per-pixel */
1245 if (vs->depth == 4) vnc_write_u8(vs, 24); /* depth */
1246 else vnc_write_u8(vs, vs->depth * 8); /* depth */
1247
1248#ifdef WORDS_BIGENDIAN
1249 vnc_write_u8(vs, 1); /* big-endian-flag */
1250#else
1251 vnc_write_u8(vs, 0); /* big-endian-flag */
1252#endif
1253 vnc_write_u8(vs, 1); /* true-color-flag */
1254 if (vs->depth == 4) {
1255 vnc_write_u16(vs, 0xFF); /* red-max */
1256 vnc_write_u16(vs, 0xFF); /* green-max */
1257 vnc_write_u16(vs, 0xFF); /* blue-max */
1258 vnc_write_u8(vs, 16); /* red-shift */
1259 vnc_write_u8(vs, 8); /* green-shift */
1260 vnc_write_u8(vs, 0); /* blue-shift */
1261 vs->send_hextile_tile = send_hextile_tile_32;
1262 } else if (vs->depth == 2) {
1263 vnc_write_u16(vs, 31); /* red-max */
1264 vnc_write_u16(vs, 63); /* green-max */
1265 vnc_write_u16(vs, 31); /* blue-max */
1266 vnc_write_u8(vs, 11); /* red-shift */
1267 vnc_write_u8(vs, 5); /* green-shift */
1268 vnc_write_u8(vs, 0); /* blue-shift */
1269 vs->send_hextile_tile = send_hextile_tile_16;
1270 } else if (vs->depth == 1) {
1271 /* XXX: change QEMU pixel 8 bit pixel format to match the VNC one ? */
1272 vnc_write_u16(vs, 7); /* red-max */
1273 vnc_write_u16(vs, 7); /* green-max */
1274 vnc_write_u16(vs, 3); /* blue-max */
1275 vnc_write_u8(vs, 5); /* red-shift */
1276 vnc_write_u8(vs, 2); /* green-shift */
1277 vnc_write_u8(vs, 0); /* blue-shift */
1278 vs->send_hextile_tile = send_hextile_tile_8;
1279 }
1280 vs->client_red_max = vs->server_red_max;
1281 vs->client_green_max = vs->server_green_max;
1282 vs->client_blue_max = vs->server_blue_max;
1283 vs->client_red_shift = vs->server_red_shift;
1284 vs->client_green_shift = vs->server_green_shift;
1285 vs->client_blue_shift = vs->server_blue_shift;
1286 vs->pix_bpp = vs->depth * 8;
1287 vs->write_pixels = vnc_write_pixels_copy;
1288
1289 vnc_write(vs, pad, 3); /* padding */
1290}
1291
1292static void vnc_colordepth(DisplayState *ds, int depth)
1293{
1294 int host_big_endian_flag;
1295 struct VncState *vs = ds->opaque;
1296
1297 switch (depth) {
1298 case 24:
1299 if (ds->depth == 32) return;
1300 depth = 32;
1301 break;
1302 case 15:
1303 case 8:
1304 case 0:
1305 return;
1306 default:
1307 break;
1308 }
1309
1310#ifdef WORDS_BIGENDIAN
1311 host_big_endian_flag = 1;
1312#else
1313 host_big_endian_flag = 0;
1314#endif
1315
1316 switch (depth) {
1317 case 8:
1318 vs->depth = depth / 8;
1319 vs->server_red_max = 7;
1320 vs->server_green_max = 7;
1321 vs->server_blue_max = 3;
1322 vs->server_red_shift = 5;
1323 vs->server_green_shift = 2;
1324 vs->server_blue_shift = 0;
1325 break;
1326 case 16:
1327 vs->depth = depth / 8;
1328 vs->server_red_max = 31;
1329 vs->server_green_max = 63;
1330 vs->server_blue_max = 31;
1331 vs->server_red_shift = 11;
1332 vs->server_green_shift = 5;
1333 vs->server_blue_shift = 0;
1334 break;
1335 case 32:
1336 vs->depth = 4;
1337 vs->server_red_max = 255;
1338 vs->server_green_max = 255;
1339 vs->server_blue_max = 255;
1340 vs->server_red_shift = 16;
1341 vs->server_green_shift = 8;
1342 vs->server_blue_shift = 0;
1343 break;
1344 default:
1345 return;
1346 }
1347
1348 if (vs->csock != -1 && vs->has_WMVi) {
1349 /* Sending a WMVi message to notify the client*/
1350 vnc_write_u8(vs, 0); /* msg id */
1351 vnc_write_u8(vs, 0);
1352 vnc_write_u16(vs, 1); /* number of rects */
1353 vnc_framebuffer_update(vs, 0, 0, ds->width, ds->height, 0x574D5669);
1354 pixel_format_message(vs);
1355 vnc_flush(vs);
1356 } else {
1357 if (vs->pix_bpp == 4 && vs->depth == 4 &&
1358 host_big_endian_flag == vs->pix_big_endian &&
1359 vs->client_red_max == 0xff && vs->client_green_max == 0xff && vs->client_blue_max == 0xff &&
1360 vs->client_red_shift == 16 && vs->client_green_shift == 8 && vs->client_blue_shift == 0) {
1361 vs->write_pixels = vnc_write_pixels_copy;
1362 vs->send_hextile_tile = send_hextile_tile_32;
1363 } else if (vs->pix_bpp == 2 && vs->depth == 2 &&
1364 host_big_endian_flag == vs->pix_big_endian &&
1365 vs->client_red_max == 31 && vs->client_green_max == 63 && vs->client_blue_max == 31 &&
1366 vs->client_red_shift == 11 && vs->client_green_shift == 5 && vs->client_blue_shift == 0) {
1367 vs->write_pixels = vnc_write_pixels_copy;
1368 vs->send_hextile_tile = send_hextile_tile_16;
1369 } else if (vs->pix_bpp == 1 && vs->depth == 1 &&
1370 host_big_endian_flag == vs->pix_big_endian &&
1371 vs->client_red_max == 7 && vs->client_green_max == 7 && vs->client_blue_max == 3 &&
1372 vs->client_red_shift == 5 && vs->client_green_shift == 2 && vs->client_blue_shift == 0) {
1373 vs->write_pixels = vnc_write_pixels_copy;
1374 vs->send_hextile_tile = send_hextile_tile_8;
1375 } else {
1376 if (vs->depth == 4) {
1377 vs->send_hextile_tile = send_hextile_tile_generic_32;
1378 } else if (vs->depth == 2) {
1379 vs->send_hextile_tile = send_hextile_tile_generic_16;
1380 } else {
1381 vs->send_hextile_tile = send_hextile_tile_generic_8;
1382 }
1383 vs->write_pixels = vnc_write_pixels_generic;
1384 }
1385 }
1386}
1387
1388static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1389{
1390 int i;
1391 uint16_t limit;
1392
1393 switch (data[0]) {
1394 case 0:
1395 if (len == 1)
1396 return 20;
1397
1398 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1399 read_u8(data, 6), read_u8(data, 7),
1400 read_u16(data, 8), read_u16(data, 10),
1401 read_u16(data, 12), read_u8(data, 14),
1402 read_u8(data, 15), read_u8(data, 16));
1403 break;
1404 case 2:
1405 if (len == 1)
1406 return 4;
1407
1408 if (len == 4)
1409 return 4 + (read_u16(data, 2) * 4);
1410
1411 limit = read_u16(data, 2);
1412 for (i = 0; i < limit; i++) {
1413 int32_t val = read_s32(data, 4 + (i * 4));
1414 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1415 }
1416
1417 set_encodings(vs, (int32_t *)(data + 4), limit);
1418 break;
1419 case 3:
1420 if (len == 1)
1421 return 10;
1422
1423 framebuffer_update_request(vs,
1424 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1425 read_u16(data, 6), read_u16(data, 8));
1426 break;
1427 case 4:
1428 if (len == 1)
1429 return 8;
1430
1431 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1432 break;
1433 case 5:
1434 if (len == 1)
1435 return 6;
1436
1437 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1438 break;
1439 case 6:
1440 if (len == 1)
1441 return 8;
1442
1443 if (len == 8) {
1444 uint32_t dlen = read_u32(data, 4);
1445 if (dlen > 0)
1446 return 8 + dlen;
1447 }
1448
1449 client_cut_text(vs, read_u32(data, 4), data + 8);
1450 break;
1451 case 255:
1452 if (len == 1)
1453 return 2;
1454
1455 switch (read_u8(data, 1)) {
1456 case 0:
1457 if (len == 2)
1458 return 12;
1459
1460 ext_key_event(vs, read_u16(data, 2),
1461 read_u32(data, 4), read_u32(data, 8));
1462 break;
1463 default:
1464 printf("Msg: %d\n", read_u16(data, 0));
1465 vnc_client_error(vs);
1466 break;
1467 }
1468 break;
1469 default:
1470 printf("Msg: %d\n", data[0]);
1471 vnc_client_error(vs);
1472 break;
1473 }
1474
1475 vnc_read_when(vs, protocol_client_msg, 1);
1476 return 0;
1477}
1478
1479static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1480{
1481 char buf[1024];
1482 int size;
1483
1484 vs->width = vs->ds->width;
1485 vs->height = vs->ds->height;
1486 vnc_write_u16(vs, vs->ds->width);
1487 vnc_write_u16(vs, vs->ds->height);
1488
1489 pixel_format_message(vs);
1490
1491 if (qemu_name)
1492 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1493 else
1494 size = snprintf(buf, sizeof(buf), "QEMU");
1495
1496 vnc_write_u32(vs, size);
1497 vnc_write(vs, buf, size);
1498 vnc_flush(vs);
1499
1500 vnc_read_when(vs, protocol_client_msg, 1);
1501
1502 return 0;
1503}
1504
1505static void make_challenge(VncState *vs)
1506{
1507 int i;
1508
1509 srand(time(NULL)+getpid()+getpid()*987654+rand());
1510
1511 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1512 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1513}
1514
1515static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1516{
1517 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1518 int i, j, pwlen;
1519 unsigned char key[8];
1520
1521 if (!vs->password || !vs->password[0]) {
1522 VNC_DEBUG("No password configured on server");
1523 vnc_write_u32(vs, 1); /* Reject auth */
1524 if (vs->minor >= 8) {
1525 static const char err[] = "Authentication failed";
1526 vnc_write_u32(vs, sizeof(err));
1527 vnc_write(vs, err, sizeof(err));
1528 }
1529 vnc_flush(vs);
1530 vnc_client_error(vs);
1531 return 0;
1532 }
1533
1534 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1535
1536 /* Calculate the expected challenge response */
1537 pwlen = strlen(vs->password);
1538 for (i=0; i<sizeof(key); i++)
1539 key[i] = i<pwlen ? vs->password[i] : 0;
1540 deskey(key, EN0);
1541 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1542 des(response+j, response+j);
1543
1544 /* Compare expected vs actual challenge response */
1545 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1546 VNC_DEBUG("Client challenge reponse did not match\n");
1547 vnc_write_u32(vs, 1); /* Reject auth */
1548 if (vs->minor >= 8) {
1549 static const char err[] = "Authentication failed";
1550 vnc_write_u32(vs, sizeof(err));
1551 vnc_write(vs, err, sizeof(err));
1552 }
1553 vnc_flush(vs);
1554 vnc_client_error(vs);
1555 } else {
1556 VNC_DEBUG("Accepting VNC challenge response\n");
1557 vnc_write_u32(vs, 0); /* Accept auth */
1558 vnc_flush(vs);
1559
1560 vnc_read_when(vs, protocol_client_init, 1);
1561 }
1562 return 0;
1563}
1564
1565static int start_auth_vnc(VncState *vs)
1566{
1567 make_challenge(vs);
1568 /* Send client a 'random' challenge */
1569 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1570 vnc_flush(vs);
1571
1572 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1573 return 0;
1574}
1575
1576
1577#ifdef CONFIG_VNC_TLS
1578#define DH_BITS 1024
1579static gnutls_dh_params_t dh_params;
1580
1581static int vnc_tls_initialize(void)
1582{
1583 static int tlsinitialized = 0;
1584
1585 if (tlsinitialized)
1586 return 1;
1587
1588 if (gnutls_global_init () < 0)
1589 return 0;
1590
1591 /* XXX ought to re-generate diffie-hellmen params periodically */
1592 if (gnutls_dh_params_init (&dh_params) < 0)
1593 return 0;
1594 if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1595 return 0;
1596
1597#if _VNC_DEBUG == 2
1598 gnutls_global_set_log_level(10);
1599 gnutls_global_set_log_function(vnc_debug_gnutls_log);
1600#endif
1601
1602 tlsinitialized = 1;
1603
1604 return 1;
1605}
1606
1607static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1608{
1609 gnutls_anon_server_credentials anon_cred;
1610 int ret;
1611
1612 if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1613 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1614 return NULL;
1615 }
1616
1617 gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1618
1619 return anon_cred;
1620}
1621
1622
1623static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1624{
1625 gnutls_certificate_credentials_t x509_cred;
1626 int ret;
1627
1628 if (!vs->x509cacert) {
1629 VNC_DEBUG("No CA x509 certificate specified\n");
1630 return NULL;
1631 }
1632 if (!vs->x509cert) {
1633 VNC_DEBUG("No server x509 certificate specified\n");
1634 return NULL;
1635 }
1636 if (!vs->x509key) {
1637 VNC_DEBUG("No server private key specified\n");
1638 return NULL;
1639 }
1640
1641 if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1642 VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1643 return NULL;
1644 }
1645 if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1646 vs->x509cacert,
1647 GNUTLS_X509_FMT_PEM)) < 0) {
1648 VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1649 gnutls_certificate_free_credentials(x509_cred);
1650 return NULL;
1651 }
1652
1653 if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1654 vs->x509cert,
1655 vs->x509key,
1656 GNUTLS_X509_FMT_PEM)) < 0) {
1657 VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1658 gnutls_certificate_free_credentials(x509_cred);
1659 return NULL;
1660 }
1661
1662 if (vs->x509cacrl) {
1663 if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1664 vs->x509cacrl,
1665 GNUTLS_X509_FMT_PEM)) < 0) {
1666 VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
1667 gnutls_certificate_free_credentials(x509_cred);
1668 return NULL;
1669 }
1670 }
1671
1672 gnutls_certificate_set_dh_params (x509_cred, dh_params);
1673
1674 return x509_cred;
1675}
1676
1677static int vnc_validate_certificate(struct VncState *vs)
1678{
1679 int ret;
1680 unsigned int status;
1681 const gnutls_datum_t *certs;
1682 unsigned int nCerts, i;
1683 time_t now;
1684
1685 VNC_DEBUG("Validating client certificate\n");
1686 if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
1687 VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
1688 return -1;
1689 }
1690
1691 if ((now = time(NULL)) == ((time_t)-1)) {
1692 return -1;
1693 }
1694
1695 if (status != 0) {
1696 if (status & GNUTLS_CERT_INVALID)
1697 VNC_DEBUG("The certificate is not trusted.\n");
1698
1699 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1700 VNC_DEBUG("The certificate hasn't got a known issuer.\n");
1701
1702 if (status & GNUTLS_CERT_REVOKED)
1703 VNC_DEBUG("The certificate has been revoked.\n");
1704
1705 if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1706 VNC_DEBUG("The certificate uses an insecure algorithm\n");
1707
1708 return -1;
1709 } else {
1710 VNC_DEBUG("Certificate is valid!\n");
1711 }
1712
1713 /* Only support x509 for now */
1714 if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
1715 return -1;
1716
1717 if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
1718 return -1;
1719
1720 for (i = 0 ; i < nCerts ; i++) {
1721 gnutls_x509_crt_t cert;
1722 VNC_DEBUG ("Checking certificate chain %d\n", i);
1723 if (gnutls_x509_crt_init (&cert) < 0)
1724 return -1;
1725
1726 if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1727 gnutls_x509_crt_deinit (cert);
1728 return -1;
1729 }
1730
1731 if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1732 VNC_DEBUG("The certificate has expired\n");
1733 gnutls_x509_crt_deinit (cert);
1734 return -1;
1735 }
1736
1737 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1738 VNC_DEBUG("The certificate is not yet activated\n");
1739 gnutls_x509_crt_deinit (cert);
1740 return -1;
1741 }
1742
1743 if (gnutls_x509_crt_get_activation_time (cert) > now) {
1744 VNC_DEBUG("The certificate is not yet activated\n");
1745 gnutls_x509_crt_deinit (cert);
1746 return -1;
1747 }
1748
1749 gnutls_x509_crt_deinit (cert);
1750 }
1751
1752 return 0;
1753}
1754
1755
1756static int start_auth_vencrypt_subauth(VncState *vs)
1757{
1758 switch (vs->subauth) {
1759 case VNC_AUTH_VENCRYPT_TLSNONE:
1760 case VNC_AUTH_VENCRYPT_X509NONE:
1761 VNC_DEBUG("Accept TLS auth none\n");
1762 vnc_write_u32(vs, 0); /* Accept auth completion */
1763 vnc_read_when(vs, protocol_client_init, 1);
1764 break;
1765
1766 case VNC_AUTH_VENCRYPT_TLSVNC:
1767 case VNC_AUTH_VENCRYPT_X509VNC:
1768 VNC_DEBUG("Start TLS auth VNC\n");
1769 return start_auth_vnc(vs);
1770
1771 default: /* Should not be possible, but just in case */
1772 VNC_DEBUG("Reject auth %d\n", vs->auth);
1773 vnc_write_u8(vs, 1);
1774 if (vs->minor >= 8) {
1775 static const char err[] = "Unsupported authentication type";
1776 vnc_write_u32(vs, sizeof(err));
1777 vnc_write(vs, err, sizeof(err));
1778 }
1779 vnc_client_error(vs);
1780 }
1781
1782 return 0;
1783}
1784
1785static void vnc_handshake_io(void *opaque);
1786
1787static int vnc_continue_handshake(struct VncState *vs) {
1788 int ret;
1789
1790 if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1791 if (!gnutls_error_is_fatal(ret)) {
1792 VNC_DEBUG("Handshake interrupted (blocking)\n");
1793 if (!gnutls_record_get_direction(vs->tls_session))
1794 qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1795 else
1796 qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1797 return 0;
1798 }
1799 VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1800 vnc_client_error(vs);
1801 return -1;
1802 }
1803
1804 if (vs->x509verify) {
1805 if (vnc_validate_certificate(vs) < 0) {
1806 VNC_DEBUG("Client verification failed\n");
1807 vnc_client_error(vs);
1808 return -1;
1809 } else {
1810 VNC_DEBUG("Client verification passed\n");
1811 }
1812 }
1813
1814 VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1815 vs->wiremode = VNC_WIREMODE_TLS;
1816 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1817
1818 return start_auth_vencrypt_subauth(vs);
1819}
1820
1821static void vnc_handshake_io(void *opaque) {
1822 struct VncState *vs = (struct VncState *)opaque;
1823
1824 VNC_DEBUG("Handshake IO continue\n");
1825 vnc_continue_handshake(vs);
1826}
1827
1828#define NEED_X509_AUTH(vs) \
1829 ((vs)->subauth == VNC_AUTH_VENCRYPT_X509NONE || \
1830 (vs)->subauth == VNC_AUTH_VENCRYPT_X509VNC || \
1831 (vs)->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
1832
1833
1834static int vnc_start_tls(struct VncState *vs) {
1835 static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
1836 static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
1837 static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
1838 static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
1839
1840 VNC_DEBUG("Do TLS setup\n");
1841 if (vnc_tls_initialize() < 0) {
1842 VNC_DEBUG("Failed to init TLS\n");
1843 vnc_client_error(vs);
1844 return -1;
1845 }
1846 if (vs->tls_session == NULL) {
1847 if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
1848 vnc_client_error(vs);
1849 return -1;
1850 }
1851
1852 if (gnutls_set_default_priority(vs->tls_session) < 0) {
1853 gnutls_deinit(vs->tls_session);
1854 vs->tls_session = NULL;
1855 vnc_client_error(vs);
1856 return -1;
1857 }
1858
1859 if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
1860 gnutls_deinit(vs->tls_session);
1861 vs->tls_session = NULL;
1862 vnc_client_error(vs);
1863 return -1;
1864 }
1865
1866 if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
1867 gnutls_deinit(vs->tls_session);
1868 vs->tls_session = NULL;
1869 vnc_client_error(vs);
1870 return -1;
1871 }
1872
1873 if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
1874 gnutls_deinit(vs->tls_session);
1875 vs->tls_session = NULL;
1876 vnc_client_error(vs);
1877 return -1;
1878 }
1879
1880 if (NEED_X509_AUTH(vs)) {
1881 gnutls_certificate_server_credentials x509_cred = vnc_tls_initialize_x509_cred(vs);
1882 if (!x509_cred) {
1883 gnutls_deinit(vs->tls_session);
1884 vs->tls_session = NULL;
1885 vnc_client_error(vs);
1886 return -1;
1887 }
1888 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {
1889 gnutls_deinit(vs->tls_session);
1890 vs->tls_session = NULL;
1891 gnutls_certificate_free_credentials(x509_cred);
1892 vnc_client_error(vs);
1893 return -1;
1894 }
1895 if (vs->x509verify) {
1896 VNC_DEBUG("Requesting a client certificate\n");
1897 gnutls_certificate_server_set_request (vs->tls_session, GNUTLS_CERT_REQUEST);
1898 }
1899
1900 } else {
1901 gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
1902 if (!anon_cred) {
1903 gnutls_deinit(vs->tls_session);
1904 vs->tls_session = NULL;
1905 vnc_client_error(vs);
1906 return -1;
1907 }
1908 if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
1909 gnutls_deinit(vs->tls_session);
1910 vs->tls_session = NULL;
1911 gnutls_anon_free_server_credentials(anon_cred);
1912 vnc_client_error(vs);
1913 return -1;
1914 }
1915 }
1916
1917 gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
1918 gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
1919 gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
1920 }
1921
1922 VNC_DEBUG("Start TLS handshake process\n");
1923 return vnc_continue_handshake(vs);
1924}
1925
1926static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)
1927{
1928 int auth = read_u32(data, 0);
1929
1930 if (auth != vs->subauth) {
1931 VNC_DEBUG("Rejecting auth %d\n", auth);
1932 vnc_write_u8(vs, 0); /* Reject auth */
1933 vnc_flush(vs);
1934 vnc_client_error(vs);
1935 } else {
1936 VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
1937 vnc_write_u8(vs, 1); /* Accept auth */
1938 vnc_flush(vs);
1939
1940 if (vnc_start_tls(vs) < 0) {
1941 VNC_DEBUG("Failed to complete TLS\n");
1942 return 0;
1943 }
1944
1945 if (vs->wiremode == VNC_WIREMODE_TLS) {
1946 VNC_DEBUG("Starting VeNCrypt subauth\n");
1947 return start_auth_vencrypt_subauth(vs);
1948 } else {
1949 VNC_DEBUG("TLS handshake blocked\n");
1950 return 0;
1951 }
1952 }
1953 return 0;
1954}
1955
1956static int protocol_client_vencrypt_init(VncState *vs, uint8_t *data, size_t len)
1957{
1958 if (data[0] != 0 ||
1959 data[1] != 2) {
1960 VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
1961 vnc_write_u8(vs, 1); /* Reject version */
1962 vnc_flush(vs);
1963 vnc_client_error(vs);
1964 } else {
1965 VNC_DEBUG("Sending allowed auth %d\n", vs->subauth);
1966 vnc_write_u8(vs, 0); /* Accept version */
1967 vnc_write_u8(vs, 1); /* Number of sub-auths */
1968 vnc_write_u32(vs, vs->subauth); /* The supported auth */
1969 vnc_flush(vs);
1970 vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
1971 }
1972 return 0;
1973}
1974
1975static int start_auth_vencrypt(VncState *vs)
1976{
1977 /* Send VeNCrypt version 0.2 */
1978 vnc_write_u8(vs, 0);
1979 vnc_write_u8(vs, 2);
1980
1981 vnc_read_when(vs, protocol_client_vencrypt_init, 2);
1982 return 0;
1983}
1984#endif /* CONFIG_VNC_TLS */
1985
1986static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
1987{
1988 /* We only advertise 1 auth scheme at a time, so client
1989 * must pick the one we sent. Verify this */
1990 if (data[0] != vs->auth) { /* Reject auth */
1991 VNC_DEBUG("Reject auth %d\n", (int)data[0]);
1992 vnc_write_u32(vs, 1);
1993 if (vs->minor >= 8) {
1994 static const char err[] = "Authentication failed";
1995 vnc_write_u32(vs, sizeof(err));
1996 vnc_write(vs, err, sizeof(err));
1997 }
1998 vnc_client_error(vs);
1999 } else { /* Accept requested auth */
2000 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2001 switch (vs->auth) {
2002 case VNC_AUTH_NONE:
2003 VNC_DEBUG("Accept auth none\n");
2004 if (vs->minor >= 8) {
2005 vnc_write_u32(vs, 0); /* Accept auth completion */
2006 vnc_flush(vs);
2007 }
2008 vnc_read_when(vs, protocol_client_init, 1);
2009 break;
2010
2011 case VNC_AUTH_VNC:
2012 VNC_DEBUG("Start VNC auth\n");
2013 return start_auth_vnc(vs);
2014
2015#ifdef CONFIG_VNC_TLS
2016 case VNC_AUTH_VENCRYPT:
2017 VNC_DEBUG("Accept VeNCrypt auth\n");;
2018 return start_auth_vencrypt(vs);
2019#endif /* CONFIG_VNC_TLS */
2020
2021 default: /* Should not be possible, but just in case */
2022 VNC_DEBUG("Reject auth %d\n", vs->auth);
2023 vnc_write_u8(vs, 1);
2024 if (vs->minor >= 8) {
2025 static const char err[] = "Authentication failed";
2026 vnc_write_u32(vs, sizeof(err));
2027 vnc_write(vs, err, sizeof(err));
2028 }
2029 vnc_client_error(vs);
2030 }
2031 }
2032 return 0;
2033}
2034
2035static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2036{
2037 char local[13];
2038
2039 memcpy(local, version, 12);
2040 local[12] = 0;
2041
2042 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2043 VNC_DEBUG("Malformed protocol version %s\n", local);
2044 vnc_client_error(vs);
2045 return 0;
2046 }
2047 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2048 if (vs->major != 3 ||
2049 (vs->minor != 3 &&
2050 vs->minor != 4 &&
2051 vs->minor != 5 &&
2052 vs->minor != 7 &&
2053 vs->minor != 8)) {
2054 VNC_DEBUG("Unsupported client version\n");
2055 vnc_write_u32(vs, VNC_AUTH_INVALID);
2056 vnc_flush(vs);
2057 vnc_client_error(vs);
2058 return 0;
2059 }
2060 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2061 * as equivalent to v3.3 by servers
2062 */
2063 if (vs->minor == 4 || vs->minor == 5)
2064 vs->minor = 3;
2065
2066 if (vs->minor == 3) {
2067 if (vs->auth == VNC_AUTH_NONE) {
2068 VNC_DEBUG("Tell client auth none\n");
2069 vnc_write_u32(vs, vs->auth);
2070 vnc_flush(vs);
2071 vnc_read_when(vs, protocol_client_init, 1);
2072 } else if (vs->auth == VNC_AUTH_VNC) {
2073 VNC_DEBUG("Tell client VNC auth\n");
2074 vnc_write_u32(vs, vs->auth);
2075 vnc_flush(vs);
2076 start_auth_vnc(vs);
2077 } else {
2078 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2079 vnc_write_u32(vs, VNC_AUTH_INVALID);
2080 vnc_flush(vs);
2081 vnc_client_error(vs);
2082 }
2083 } else {
2084 VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2085 vnc_write_u8(vs, 1); /* num auth */
2086 vnc_write_u8(vs, vs->auth);
2087 vnc_read_when(vs, protocol_client_auth, 1);
2088 vnc_flush(vs);
2089 }
2090
2091 return 0;
2092}
2093
2094static void vnc_connect(VncState *vs)
2095{
2096 VNC_DEBUG("New client on socket %d\n", vs->csock);
2097 vs->ds->idle = 0;
2098 socket_set_nonblock(vs->csock);
2099 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2100 vnc_write(vs, "RFB 003.008\n", 12);
2101 vnc_flush(vs);
2102 vnc_read_when(vs, protocol_version, 12);
2103 memset(vs->old_data, 0, vs->ds->linesize * vs->ds->height);
2104 memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
2105 vs->has_resize = 0;
2106 vs->has_hextile = 0;
2107 vs->ds->dpy_copy = NULL;
2108 vnc_update_client(vs);
2109}
2110
2111static void vnc_listen_read(void *opaque)
2112{
2113 VncState *vs = opaque;
2114
2115 /* Catch-up */
2116 vga_hw_update();
2117
2118 vs->csock = socket_accept(vs->lsock, NULL);
2119 if (vs->csock != -1) {
2120 vnc_connect(vs);
2121 }
2122}
2123
2124extern int parse_host_port(SockAddress* saddr, const char *str);
2125
2126void vnc_display_init(DisplayState *ds)
2127{
2128 VncState *vs;
2129
2130 vs = qemu_mallocz(sizeof(VncState));
2131 if (!vs)
2132 exit(1);
2133
2134 ds->opaque = vs;
2135 ds->idle = 1;
2136 vnc_state = vs;
2137 vs->display = NULL;
2138 vs->password = NULL;
2139
2140 vs->lsock = -1;
2141 vs->csock = -1;
2142 vs->last_x = -1;
2143 vs->last_y = -1;
2144
2145 vs->ds = ds;
2146
2147 if (keyboard_layout)
2148 vs->kbd_layout = init_keyboard_layout(keyboard_layout);
2149 else
2150 vs->kbd_layout = init_keyboard_layout("en-us");
2151
2152 if (!vs->kbd_layout)
2153 exit(1);
2154
2155 vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
2156
2157 vs->ds->data = NULL;
2158 vs->ds->dpy_update = vnc_dpy_update;
2159 vs->ds->dpy_resize = vnc_dpy_resize;
2160 vs->ds->dpy_refresh = NULL;
2161
2162 vnc_colordepth(vs->ds, 32);
2163 vnc_dpy_resize(vs->ds, 640, 400);
2164}
2165
2166#ifdef CONFIG_VNC_TLS
2167static int vnc_set_x509_credential(VncState *vs,
2168 const char *certdir,
2169 const char *filename,
2170 char **cred,
2171 int ignoreMissing)
2172{
2173 struct stat sb;
2174
2175 if (*cred) {
2176 qemu_free(*cred);
2177 *cred = NULL;
2178 }
2179
2180 if (!(*cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2)))
2181 return -1;
2182
2183 strcpy(*cred, certdir);
2184 strcat(*cred, "/");
2185 strcat(*cred, filename);
2186
2187 VNC_DEBUG("Check %s\n", *cred);
2188 if (stat(*cred, &sb) < 0) {
2189 qemu_free(*cred);
2190 *cred = NULL;
2191 if (ignoreMissing && errno == ENOENT)
2192 return 0;
2193 return -1;
2194 }
2195
2196 return 0;
2197}
2198
2199static int vnc_set_x509_credential_dir(VncState *vs,
2200 const char *certdir)
2201{
2202 if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)
2203 goto cleanup;
2204 if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)
2205 goto cleanup;
2206 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)
2207 goto cleanup;
2208 if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)
2209 goto cleanup;
2210
2211 return 0;
2212
2213 cleanup:
2214 qemu_free(vs->x509cacert);
2215 qemu_free(vs->x509cacrl);
2216 qemu_free(vs->x509cert);
2217 qemu_free(vs->x509key);
2218 vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2219 return -1;
2220}
2221#endif /* CONFIG_VNC_TLS */
2222
2223void vnc_display_close(DisplayState *ds)
2224{
2225 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2226
2227 if (vs->display) {
2228 qemu_free(vs->display);
2229 vs->display = NULL;
2230 }
2231 if (vs->lsock != -1) {
2232 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2233 close(vs->lsock);
2234 vs->lsock = -1;
2235 }
2236 if (vs->csock != -1) {
2237 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
2238 socket_close(vs->csock);
2239 vs->csock = -1;
2240 buffer_reset(&vs->input);
2241 buffer_reset(&vs->output);
2242 vs->need_update = 0;
2243#ifdef CONFIG_VNC_TLS
2244 if (vs->tls_session) {
2245 gnutls_deinit(vs->tls_session);
2246 vs->tls_session = NULL;
2247 }
2248 vs->wiremode = VNC_WIREMODE_CLEAR;
2249#endif /* CONFIG_VNC_TLS */
2250 }
2251 vs->auth = VNC_AUTH_INVALID;
2252#ifdef CONFIG_VNC_TLS
2253 vs->subauth = VNC_AUTH_INVALID;
2254 vs->x509verify = 0;
2255#endif
2256}
2257
2258int vnc_display_password(DisplayState *ds, const char *password)
2259{
2260 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2261
2262 if (vs->password) {
2263 qemu_free(vs->password);
2264 vs->password = NULL;
2265 }
2266 if (password && password[0]) {
2267 if (!(vs->password = qemu_strdup(password)))
2268 return -1;
2269 }
2270
2271 return 0;
2272}
2273
2274int vnc_display_open(DisplayState *ds, const char *display)
2275{
2276 SockAddress addr;
2277#ifndef _WIN32
2278 const char *p;
2279#endif
2280 int ret;
2281 VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2282 const char *options;
2283 int password = 0;
2284 int reverse = 0;
2285#ifdef CONFIG_VNC_TLS
2286 int tls = 0, x509 = 0;
2287#endif
2288
2289 sock_address_init_inet( &addr, SOCK_ADDRESS_INET_ANY, 0 );
2290 vs->lsock = -1;
2291
2292 vnc_display_close(ds);
2293 if (strcmp(display, "none") == 0)
2294 return 0;
2295
2296 if (!(vs->display = strdup(display)))
2297 return -1;
2298
2299 options = display;
2300 while ((options = strchr(options, ','))) {
2301 options++;
2302 if (strncmp(options, "password", 8) == 0) {
2303 password = 1; /* Require password auth */
2304 } else if (strncmp(options, "reverse", 7) == 0) {
2305 reverse = 1;
2306#ifdef CONFIG_VNC_TLS
2307 } else if (strncmp(options, "tls", 3) == 0) {
2308 tls = 1; /* Require TLS */
2309 } else if (strncmp(options, "x509", 4) == 0) {
2310 char *start, *end;
2311 x509 = 1; /* Require x509 certificates */
2312 if (strncmp(options, "x509verify", 10) == 0)
2313 vs->x509verify = 1; /* ...and verify client certs */
2314
2315 /* Now check for 'x509=/some/path' postfix
2316 * and use that to setup x509 certificate/key paths */
2317 start = strchr(options, '=');
2318 end = strchr(options, ',');
2319 if (start && (!end || (start < end))) {
2320 int len = end ? end-(start+1) : strlen(start+1);
2321 char *path = qemu_malloc(len+1);
2322 strncpy(path, start+1, len);
2323 path[len] = '\0';
2324 VNC_DEBUG("Trying certificate path '%s'\n", path);
2325 ret = vnc_set_x509_credential_dir(vs, path);
2326 qemu_free(path);
2327 if (ret < 0) {
2328 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2329 goto FAIL;
2330 }
2331 } else {
2332 fprintf(stderr, "No certificate path provided\n");
2333 goto FAIL;
2334 }
2335#endif
2336 }
2337 }
2338
2339 if (password) {
2340#ifdef CONFIG_VNC_TLS
2341 if (tls) {
2342 vs->auth = VNC_AUTH_VENCRYPT;
2343 if (x509) {
2344 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2345 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2346 } else {
2347 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2348 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2349 }
2350 } else {
2351#endif
2352 VNC_DEBUG("Initializing VNC server with password auth\n");
2353 vs->auth = VNC_AUTH_VNC;
2354#ifdef CONFIG_VNC_TLS
2355 vs->subauth = VNC_AUTH_INVALID;
2356 }
2357#endif
2358 } else {
2359#ifdef CONFIG_VNC_TLS
2360 if (tls) {
2361 vs->auth = VNC_AUTH_VENCRYPT;
2362 if (x509) {
2363 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2364 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2365 } else {
2366 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2367 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2368 }
2369 } else {
2370#endif
2371 VNC_DEBUG("Initializing VNC server with no auth\n");
2372 vs->auth = VNC_AUTH_NONE;
2373#ifdef CONFIG_VNC_TLS
2374 vs->subauth = VNC_AUTH_INVALID;
2375 }
2376#endif
2377 }
2378#ifndef _WIN32
2379 if (strstart(display, "unix:", &p)) {
2380 sock_address_init_unix( &addr, p);
2381 vs->lsock = socket_create( SOCKET_UNIX, SOCKET_STREAM );
2382 if (vs->lsock == -1) {
2383 fprintf(stderr, "Could not create socket\n");
2384 goto FAIL;
2385 }
2386
2387 if (!reverse) {
2388 unlink(p);
2389 }
2390 } else
2391#endif
2392 {
2393 if (parse_host_port(&addr, display) < 0) {
2394 fprintf(stderr, "Could not parse VNC address\n");
2395 goto FAIL;
2396 }
2397
2398 sock_address_set_port(&addr, reverse ? 0 : 5900);
2399
2400 vs->lsock = socket_create_inet( SOCKET_STREAM );
2401 if (vs->lsock == -1) {
2402 fprintf(stderr, "Could not create socket\n");
2403 goto FAIL;
2404 }
2405
2406 ret = socket_set_xreuseaddr(vs->lsock);
2407 if (ret == -1) {
2408 fprintf(stderr, "setsockopt() failed\n");
2409 goto FAIL;
2410 }
2411 }
2412
2413 if (reverse) {
2414 if (socket_connect(vs->lsock, &addr) == -1) {
2415 fprintf(stderr, "Connection to VNC client failed\n");
2416 goto FAIL;
2417 }
2418 vs->csock = vs->lsock;
2419 vs->lsock = -1;
2420 vnc_connect(vs);
2421 return 0;
2422 }
2423
2424 if (socket_bind(vs->lsock, &addr) == -1) {
2425 fprintf(stderr, "bind() failed\n");
2426 goto FAIL;
2427 }
2428
2429 if (socket_listen(vs->lsock, 1) == -1) {
2430 fprintf(stderr, "listen() failed\n");
2431 goto FAIL;
2432 }
2433
2434 return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);
2435
2436FAIL:
2437 sock_address_done(&addr);
2438
2439 if (vs->lsock >= 0) {
2440 socket_close(vs->lsock);
2441 vs->lsock = -1;
2442 }
2443 free(vs->display);
2444 vs->display = NULL;
2445 return -1;
2446}