VeNCrypt basic TLS support, by Daniel P. Berrange.
[qemu] / vnc.c
1 /*
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 "vl.h"
27 #include "qemu_socket.h"
28
29 #define VNC_REFRESH_INTERVAL (1000 / 30)
30
31 #include "vnc_keysym.h"
32 #include "keymaps.c"
33 #include "d3des.h"
34
35 #if CONFIG_VNC_TLS
36 #include <gnutls/gnutls.h>
37 #include <gnutls/x509.h>
38 #endif /* CONFIG_VNC_TLS */
39
40 // #define _VNC_DEBUG 1
41
42 #if _VNC_DEBUG
43 #define VNC_DEBUG(fmt, ...) do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
44
45 #if CONFIG_VNC_TLS && _VNC_DEBUG >= 2
46 /* Very verbose, so only enabled for _VNC_DEBUG >= 2 */
47 static void vnc_debug_gnutls_log(int level, const char* str) {
48     VNC_DEBUG("%d %s", level, str);
49 }
50 #endif /* CONFIG_VNC_TLS && _VNC_DEBUG */
51 #else
52 #define VNC_DEBUG(fmt, ...) do { } while (0)
53 #endif
54
55
56 typedef struct Buffer
57 {
58     size_t capacity;
59     size_t offset;
60     char *buffer;
61 } Buffer;
62
63 typedef struct VncState VncState;
64
65 typedef int VncReadEvent(VncState *vs, char *data, size_t len);
66
67 typedef void VncWritePixels(VncState *vs, void *data, int size);
68
69 typedef void VncSendHextileTile(VncState *vs,
70                                 int x, int y, int w, int h,
71                                 uint32_t *last_bg, 
72                                 uint32_t *last_fg,
73                                 int *has_bg, int *has_fg);
74
75 #define VNC_MAX_WIDTH 2048
76 #define VNC_MAX_HEIGHT 2048
77 #define VNC_DIRTY_WORDS (VNC_MAX_WIDTH / (16 * 32))
78
79 #define VNC_AUTH_CHALLENGE_SIZE 16
80
81 enum {
82     VNC_AUTH_INVALID = 0,
83     VNC_AUTH_NONE = 1,
84     VNC_AUTH_VNC = 2,
85     VNC_AUTH_RA2 = 5,
86     VNC_AUTH_RA2NE = 6,
87     VNC_AUTH_TIGHT = 16,
88     VNC_AUTH_ULTRA = 17,
89     VNC_AUTH_TLS = 18,
90     VNC_AUTH_VENCRYPT = 19
91 };
92
93 #if CONFIG_VNC_TLS
94 enum {
95     VNC_WIREMODE_CLEAR,
96     VNC_WIREMODE_TLS,
97 };
98
99 enum {
100     VNC_AUTH_VENCRYPT_PLAIN = 256,
101     VNC_AUTH_VENCRYPT_TLSNONE = 257,
102     VNC_AUTH_VENCRYPT_TLSVNC = 258,
103     VNC_AUTH_VENCRYPT_TLSPLAIN = 259,
104     VNC_AUTH_VENCRYPT_X509NONE = 260,
105     VNC_AUTH_VENCRYPT_X509VNC = 261,
106     VNC_AUTH_VENCRYPT_X509PLAIN = 262,
107 };
108 #endif /* CONFIG_VNC_TLS */
109
110 struct VncState
111 {
112     QEMUTimer *timer;
113     int lsock;
114     int csock;
115     DisplayState *ds;
116     int need_update;
117     int width;
118     int height;
119     uint32_t dirty_row[VNC_MAX_HEIGHT][VNC_DIRTY_WORDS];
120     char *old_data;
121     int depth; /* internal VNC frame buffer byte per pixel */
122     int has_resize;
123     int has_hextile;
124     int has_pointer_type_change;
125     int absolute;
126     int last_x;
127     int last_y;
128
129     int major;
130     int minor;
131
132     char *display;
133     char *password;
134     int auth;
135 #if CONFIG_VNC_TLS
136     int subauth;
137 #endif
138     char challenge[VNC_AUTH_CHALLENGE_SIZE];
139
140 #if CONFIG_VNC_TLS
141     int wiremode;
142     gnutls_session_t tls_session;
143 #endif
144
145     Buffer output;
146     Buffer input;
147     kbd_layout_t *kbd_layout;
148     /* current output mode information */
149     VncWritePixels *write_pixels;
150     VncSendHextileTile *send_hextile_tile;
151     int pix_bpp, pix_big_endian;
152     int red_shift, red_max, red_shift1;
153     int green_shift, green_max, green_shift1;
154     int blue_shift, blue_max, blue_shift1;
155
156     VncReadEvent *read_handler;
157     size_t read_handler_expect;
158     /* input */
159     uint8_t modifiers_state[256];
160 };
161
162 static VncState *vnc_state; /* needed for info vnc */
163
164 void do_info_vnc(void)
165 {
166     if (vnc_state == NULL)
167         term_printf("VNC server disabled\n");
168     else {
169         term_printf("VNC server active on: ");
170         term_print_filename(vnc_state->display);
171         term_printf("\n");
172
173         if (vnc_state->csock == -1)
174             term_printf("No client connected\n");
175         else
176             term_printf("Client connected\n");
177     }
178 }
179
180 /* TODO
181    1) Get the queue working for IO.
182    2) there is some weirdness when using the -S option (the screen is grey
183       and not totally invalidated
184    3) resolutions > 1024
185 */
186
187 static void vnc_write(VncState *vs, const void *data, size_t len);
188 static void vnc_write_u32(VncState *vs, uint32_t value);
189 static void vnc_write_s32(VncState *vs, int32_t value);
190 static void vnc_write_u16(VncState *vs, uint16_t value);
191 static void vnc_write_u8(VncState *vs, uint8_t value);
192 static void vnc_flush(VncState *vs);
193 static void vnc_update_client(void *opaque);
194 static void vnc_client_read(void *opaque);
195
196 static inline void vnc_set_bit(uint32_t *d, int k)
197 {
198     d[k >> 5] |= 1 << (k & 0x1f);
199 }
200
201 static inline void vnc_clear_bit(uint32_t *d, int k)
202 {
203     d[k >> 5] &= ~(1 << (k & 0x1f));
204 }
205
206 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
207 {
208     int j;
209
210     j = 0;
211     while (n >= 32) {
212         d[j++] = -1;
213         n -= 32;
214     }
215     if (n > 0) 
216         d[j++] = (1 << n) - 1;
217     while (j < nb_words)
218         d[j++] = 0;
219 }
220
221 static inline int vnc_get_bit(const uint32_t *d, int k)
222 {
223     return (d[k >> 5] >> (k & 0x1f)) & 1;
224 }
225
226 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2, 
227                                int nb_words)
228 {
229     int i;
230     for(i = 0; i < nb_words; i++) {
231         if ((d1[i] & d2[i]) != 0)
232             return 1;
233     }
234     return 0;
235 }
236
237 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
238 {
239     VncState *vs = ds->opaque;
240     int i;
241
242     h += y;
243
244     for (; y < h; y++)
245         for (i = 0; i < w; i += 16)
246             vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
247 }
248
249 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
250                                    int32_t encoding)
251 {
252     vnc_write_u16(vs, x);
253     vnc_write_u16(vs, y);
254     vnc_write_u16(vs, w);
255     vnc_write_u16(vs, h);
256
257     vnc_write_s32(vs, encoding);
258 }
259
260 static void vnc_dpy_resize(DisplayState *ds, int w, int h)
261 {
262     int size_changed;
263     VncState *vs = ds->opaque;
264
265     ds->data = realloc(ds->data, w * h * vs->depth);
266     vs->old_data = realloc(vs->old_data, w * h * vs->depth);
267
268     if (ds->data == NULL || vs->old_data == NULL) {
269         fprintf(stderr, "vnc: memory allocation failed\n");
270         exit(1);
271     }
272
273     ds->depth = vs->depth * 8;
274     size_changed = ds->width != w || ds->height != h;
275     ds->width = w;
276     ds->height = h;
277     ds->linesize = w * vs->depth;
278     if (vs->csock != -1 && vs->has_resize && size_changed) {
279         vnc_write_u8(vs, 0);  /* msg id */
280         vnc_write_u8(vs, 0);
281         vnc_write_u16(vs, 1); /* number of rects */
282         vnc_framebuffer_update(vs, 0, 0, ds->width, ds->height, -223);
283         vnc_flush(vs);
284         vs->width = ds->width;
285         vs->height = ds->height;
286     }
287 }
288
289 /* fastest code */
290 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
291 {
292     vnc_write(vs, pixels, size);
293 }
294
295 /* slowest but generic code. */
296 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
297 {
298     unsigned int r, g, b;
299
300     r = (v >> vs->red_shift1) & vs->red_max;
301     g = (v >> vs->green_shift1) & vs->green_max;
302     b = (v >> vs->blue_shift1) & vs->blue_max;
303     v = (r << vs->red_shift) | 
304         (g << vs->green_shift) | 
305         (b << vs->blue_shift);
306     switch(vs->pix_bpp) {
307     case 1:
308         buf[0] = v;
309         break;
310     case 2:
311         if (vs->pix_big_endian) {
312             buf[0] = v >> 8;
313             buf[1] = v;
314         } else {
315             buf[1] = v >> 8;
316             buf[0] = v;
317         }
318         break;
319     default:
320     case 4:
321         if (vs->pix_big_endian) {
322             buf[0] = v >> 24;
323             buf[1] = v >> 16;
324             buf[2] = v >> 8;
325             buf[3] = v;
326         } else {
327             buf[3] = v >> 24;
328             buf[2] = v >> 16;
329             buf[1] = v >> 8;
330             buf[0] = v;
331         }
332         break;
333     }
334 }
335
336 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
337 {
338     uint32_t *pixels = pixels1;
339     uint8_t buf[4];
340     int n, i;
341
342     n = size >> 2;
343     for(i = 0; i < n; i++) {
344         vnc_convert_pixel(vs, buf, pixels[i]);
345         vnc_write(vs, buf, vs->pix_bpp);
346     }
347 }
348
349 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
350 {
351     int i;
352     char *row;
353
354     vnc_framebuffer_update(vs, x, y, w, h, 0);
355
356     row = vs->ds->data + y * vs->ds->linesize + x * vs->depth;
357     for (i = 0; i < h; i++) {
358         vs->write_pixels(vs, row, w * vs->depth);
359         row += vs->ds->linesize;
360     }
361 }
362
363 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
364 {
365     ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
366     ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
367 }
368
369 #define BPP 8
370 #include "vnchextile.h"
371 #undef BPP
372
373 #define BPP 16
374 #include "vnchextile.h"
375 #undef BPP
376
377 #define BPP 32
378 #include "vnchextile.h"
379 #undef BPP
380
381 #define GENERIC
382 #define BPP 32
383 #include "vnchextile.h"
384 #undef BPP
385 #undef GENERIC
386
387 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
388 {
389     int i, j;
390     int has_fg, has_bg;
391     uint32_t last_fg32, last_bg32;
392
393     vnc_framebuffer_update(vs, x, y, w, h, 5);
394
395     has_fg = has_bg = 0;
396     for (j = y; j < (y + h); j += 16) {
397         for (i = x; i < (x + w); i += 16) {
398             vs->send_hextile_tile(vs, i, j, 
399                                   MIN(16, x + w - i), MIN(16, y + h - j),
400                                   &last_bg32, &last_fg32, &has_bg, &has_fg);
401         }
402     }
403 }
404
405 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
406 {
407         if (vs->has_hextile)
408             send_framebuffer_update_hextile(vs, x, y, w, h);
409         else
410             send_framebuffer_update_raw(vs, x, y, w, h);
411 }
412
413 static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
414 {
415     int src, dst;
416     char *src_row;
417     char *dst_row;
418     char *old_row;
419     int y = 0;
420     int pitch = ds->linesize;
421     VncState *vs = ds->opaque;
422
423     vnc_update_client(vs);
424
425     if (dst_y > src_y) {
426         y = h - 1;
427         pitch = -pitch;
428     }
429
430     src = (ds->linesize * (src_y + y) + vs->depth * src_x);
431     dst = (ds->linesize * (dst_y + y) + vs->depth * dst_x);
432
433     src_row = ds->data + src;
434     dst_row = ds->data + dst;
435     old_row = vs->old_data + dst;
436
437     for (y = 0; y < h; y++) {
438         memmove(old_row, src_row, w * vs->depth);
439         memmove(dst_row, src_row, w * vs->depth);
440         src_row += pitch;
441         dst_row += pitch;
442         old_row += pitch;
443     }
444
445     vnc_write_u8(vs, 0);  /* msg id */
446     vnc_write_u8(vs, 0);
447     vnc_write_u16(vs, 1); /* number of rects */
448     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, 1);
449     vnc_write_u16(vs, src_x);
450     vnc_write_u16(vs, src_y);
451     vnc_flush(vs);
452 }
453
454 static int find_dirty_height(VncState *vs, int y, int last_x, int x)
455 {
456     int h;
457
458     for (h = 1; h < (vs->height - y); h++) {
459         int tmp_x;
460         if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
461             break;
462         for (tmp_x = last_x; tmp_x < x; tmp_x++)
463             vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
464     }
465
466     return h;
467 }
468
469 static void vnc_update_client(void *opaque)
470 {
471     VncState *vs = opaque;
472
473     if (vs->need_update && vs->csock != -1) {
474         int y;
475         char *row;
476         char *old_row;
477         uint32_t width_mask[VNC_DIRTY_WORDS];
478         int n_rectangles;
479         int saved_offset;
480         int has_dirty = 0;
481
482         vnc_set_bits(width_mask, (vs->width / 16), VNC_DIRTY_WORDS);
483
484         /* Walk through the dirty map and eliminate tiles that
485            really aren't dirty */
486         row = vs->ds->data;
487         old_row = vs->old_data;
488
489         for (y = 0; y < vs->height; y++) {
490             if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
491                 int x;
492                 char *ptr, *old_ptr;
493
494                 ptr = row;
495                 old_ptr = old_row;
496
497                 for (x = 0; x < vs->ds->width; x += 16) {
498                     if (memcmp(old_ptr, ptr, 16 * vs->depth) == 0) {
499                         vnc_clear_bit(vs->dirty_row[y], (x / 16));
500                     } else {
501                         has_dirty = 1;
502                         memcpy(old_ptr, ptr, 16 * vs->depth);
503                     }
504
505                     ptr += 16 * vs->depth;
506                     old_ptr += 16 * vs->depth;
507                 }
508             }
509
510             row += vs->ds->linesize;
511             old_row += vs->ds->linesize;
512         }
513
514         if (!has_dirty) {
515             qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
516             return;
517         }
518
519         /* Count rectangles */
520         n_rectangles = 0;
521         vnc_write_u8(vs, 0);  /* msg id */
522         vnc_write_u8(vs, 0);
523         saved_offset = vs->output.offset;
524         vnc_write_u16(vs, 0);
525
526         for (y = 0; y < vs->height; y++) {
527             int x;
528             int last_x = -1;
529             for (x = 0; x < vs->width / 16; x++) {
530                 if (vnc_get_bit(vs->dirty_row[y], x)) {
531                     if (last_x == -1) {
532                         last_x = x;
533                     }
534                     vnc_clear_bit(vs->dirty_row[y], x);
535                 } else {
536                     if (last_x != -1) {
537                         int h = find_dirty_height(vs, y, last_x, x);
538                         send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
539                         n_rectangles++;
540                     }
541                     last_x = -1;
542                 }
543             }
544             if (last_x != -1) {
545                 int h = find_dirty_height(vs, y, last_x, x);
546                 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
547                 n_rectangles++;
548             }
549         }
550         vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
551         vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
552         vnc_flush(vs);
553
554     }
555     qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
556 }
557
558 static void vnc_timer_init(VncState *vs)
559 {
560     if (vs->timer == NULL) {
561         vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
562         qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock));
563     }
564 }
565
566 static void vnc_dpy_refresh(DisplayState *ds)
567 {
568     VncState *vs = ds->opaque;
569     vnc_timer_init(vs);
570     vga_hw_update();
571 }
572
573 static int vnc_listen_poll(void *opaque)
574 {
575     VncState *vs = opaque;
576     if (vs->csock == -1)
577         return 1;
578     return 0;
579 }
580
581 static void buffer_reserve(Buffer *buffer, size_t len)
582 {
583     if ((buffer->capacity - buffer->offset) < len) {
584         buffer->capacity += (len + 1024);
585         buffer->buffer = realloc(buffer->buffer, buffer->capacity);
586         if (buffer->buffer == NULL) {
587             fprintf(stderr, "vnc: out of memory\n");
588             exit(1);
589         }
590     }
591 }
592
593 static int buffer_empty(Buffer *buffer)
594 {
595     return buffer->offset == 0;
596 }
597
598 static char *buffer_end(Buffer *buffer)
599 {
600     return buffer->buffer + buffer->offset;
601 }
602
603 static void buffer_reset(Buffer *buffer)
604 {
605         buffer->offset = 0;
606 }
607
608 static void buffer_append(Buffer *buffer, const void *data, size_t len)
609 {
610     memcpy(buffer->buffer + buffer->offset, data, len);
611     buffer->offset += len;
612 }
613
614 static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
615 {
616     if (ret == 0 || ret == -1) {
617         if (ret == -1 && (last_errno == EINTR || last_errno == EAGAIN))
618             return 0;
619
620         VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
621         qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
622         closesocket(vs->csock);
623         vs->csock = -1;
624         buffer_reset(&vs->input);
625         buffer_reset(&vs->output);
626         vs->need_update = 0;
627 #if CONFIG_VNC_TLS
628         if (vs->tls_session) {
629             gnutls_deinit(vs->tls_session);
630             vs->tls_session = NULL;
631         }
632         vs->wiremode = VNC_WIREMODE_CLEAR;
633 #endif /* CONFIG_VNC_TLS */
634         return 0;
635     }
636     return ret;
637 }
638
639 static void vnc_client_error(VncState *vs)
640 {
641     vnc_client_io_error(vs, -1, EINVAL);
642 }
643
644 static void vnc_client_write(void *opaque)
645 {
646     long ret;
647     VncState *vs = opaque;
648
649 #if CONFIG_VNC_TLS
650     if (vs->tls_session) {
651         ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
652         if (ret < 0) {
653             if (ret == GNUTLS_E_AGAIN)
654                 errno = EAGAIN;
655             else
656                 errno = EIO;
657             ret = -1;
658         }
659     } else
660 #endif /* CONFIG_VNC_TLS */
661         ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
662     ret = vnc_client_io_error(vs, ret, socket_error());
663     if (!ret)
664         return;
665
666     memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
667     vs->output.offset -= ret;
668
669     if (vs->output.offset == 0) {
670         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
671     }
672 }
673
674 static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
675 {
676     vs->read_handler = func;
677     vs->read_handler_expect = expecting;
678 }
679
680 static void vnc_client_read(void *opaque)
681 {
682     VncState *vs = opaque;
683     long ret;
684
685     buffer_reserve(&vs->input, 4096);
686
687 #if CONFIG_VNC_TLS
688     if (vs->tls_session) {
689         ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
690         if (ret < 0) {
691             if (ret == GNUTLS_E_AGAIN)
692                 errno = EAGAIN;
693             else
694                 errno = EIO;
695             ret = -1;
696         }
697     } else
698 #endif /* CONFIG_VNC_TLS */
699         ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
700     ret = vnc_client_io_error(vs, ret, socket_error());
701     if (!ret)
702         return;
703
704     vs->input.offset += ret;
705
706     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
707         size_t len = vs->read_handler_expect;
708         int ret;
709
710         ret = vs->read_handler(vs, vs->input.buffer, len);
711         if (vs->csock == -1)
712             return;
713
714         if (!ret) {
715             memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
716             vs->input.offset -= len;
717         } else {
718             vs->read_handler_expect = ret;
719         }
720     }
721 }
722
723 static void vnc_write(VncState *vs, const void *data, size_t len)
724 {
725     buffer_reserve(&vs->output, len);
726
727     if (buffer_empty(&vs->output)) {
728         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
729     }
730
731     buffer_append(&vs->output, data, len);
732 }
733
734 static void vnc_write_s32(VncState *vs, int32_t value)
735 {
736     vnc_write_u32(vs, *(uint32_t *)&value);
737 }
738
739 static void vnc_write_u32(VncState *vs, uint32_t value)
740 {
741     uint8_t buf[4];
742
743     buf[0] = (value >> 24) & 0xFF;
744     buf[1] = (value >> 16) & 0xFF;
745     buf[2] = (value >>  8) & 0xFF;
746     buf[3] = value & 0xFF;
747
748     vnc_write(vs, buf, 4);
749 }
750
751 static void vnc_write_u16(VncState *vs, uint16_t value)
752 {
753     uint8_t buf[2];
754
755     buf[0] = (value >> 8) & 0xFF;
756     buf[1] = value & 0xFF;
757
758     vnc_write(vs, buf, 2);
759 }
760
761 static void vnc_write_u8(VncState *vs, uint8_t value)
762 {
763     vnc_write(vs, (char *)&value, 1);
764 }
765
766 static void vnc_flush(VncState *vs)
767 {
768     if (vs->output.offset)
769         vnc_client_write(vs);
770 }
771
772 static uint8_t read_u8(uint8_t *data, size_t offset)
773 {
774     return data[offset];
775 }
776
777 static uint16_t read_u16(uint8_t *data, size_t offset)
778 {
779     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
780 }
781
782 static int32_t read_s32(uint8_t *data, size_t offset)
783 {
784     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
785                      (data[offset + 2] << 8) | data[offset + 3]);
786 }
787
788 static uint32_t read_u32(uint8_t *data, size_t offset)
789 {
790     return ((data[offset] << 24) | (data[offset + 1] << 16) |
791             (data[offset + 2] << 8) | data[offset + 3]);
792 }
793
794 #if CONFIG_VNC_TLS
795 ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
796                      const void *data,
797                      size_t len) {
798     struct VncState *vs = (struct VncState *)transport;
799     int ret;
800
801  retry:
802     ret = send(vs->csock, data, len, 0);
803     if (ret < 0) {
804         if (errno == EINTR)
805             goto retry;
806         return -1;
807     }
808     return ret;
809 }
810
811
812 ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
813                      void *data,
814                      size_t len) {
815     struct VncState *vs = (struct VncState *)transport;
816     int ret;
817
818  retry:
819     ret = recv(vs->csock, data, len, 0);
820     if (ret < 0) {
821         if (errno == EINTR)
822             goto retry;
823         return -1;
824     }
825     return ret;
826 }
827 #endif /* CONFIG_VNC_TLS */
828
829 static void client_cut_text(VncState *vs, size_t len, char *text)
830 {
831 }
832
833 static void check_pointer_type_change(VncState *vs, int absolute)
834 {
835     if (vs->has_pointer_type_change && vs->absolute != absolute) {
836         vnc_write_u8(vs, 0);
837         vnc_write_u8(vs, 0);
838         vnc_write_u16(vs, 1);
839         vnc_framebuffer_update(vs, absolute, 0,
840                                vs->ds->width, vs->ds->height, -257);
841         vnc_flush(vs);
842     }
843     vs->absolute = absolute;
844 }
845
846 static void pointer_event(VncState *vs, int button_mask, int x, int y)
847 {
848     int buttons = 0;
849     int dz = 0;
850
851     if (button_mask & 0x01)
852         buttons |= MOUSE_EVENT_LBUTTON;
853     if (button_mask & 0x02)
854         buttons |= MOUSE_EVENT_MBUTTON;
855     if (button_mask & 0x04)
856         buttons |= MOUSE_EVENT_RBUTTON;
857     if (button_mask & 0x08)
858         dz = -1;
859     if (button_mask & 0x10)
860         dz = 1;
861
862     if (vs->absolute) {
863         kbd_mouse_event(x * 0x7FFF / vs->ds->width,
864                         y * 0x7FFF / vs->ds->height,
865                         dz, buttons);
866     } else if (vs->has_pointer_type_change) {
867         x -= 0x7FFF;
868         y -= 0x7FFF;
869
870         kbd_mouse_event(x, y, dz, buttons);
871     } else {
872         if (vs->last_x != -1)
873             kbd_mouse_event(x - vs->last_x,
874                             y - vs->last_y,
875                             dz, buttons);
876         vs->last_x = x;
877         vs->last_y = y;
878     }
879
880     check_pointer_type_change(vs, kbd_mouse_is_absolute());
881 }
882
883 static void reset_keys(VncState *vs)
884 {
885     int i;
886     for(i = 0; i < 256; i++) {
887         if (vs->modifiers_state[i]) {
888             if (i & 0x80)
889                 kbd_put_keycode(0xe0);
890             kbd_put_keycode(i | 0x80);
891             vs->modifiers_state[i] = 0;
892         }
893     }
894 }
895
896 static void do_key_event(VncState *vs, int down, uint32_t sym)
897 {
898     int keycode;
899
900     keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
901     
902     /* QEMU console switch */
903     switch(keycode) {
904     case 0x2a:                          /* Left Shift */
905     case 0x36:                          /* Right Shift */
906     case 0x1d:                          /* Left CTRL */
907     case 0x9d:                          /* Right CTRL */
908     case 0x38:                          /* Left ALT */
909     case 0xb8:                          /* Right ALT */
910         if (down)
911             vs->modifiers_state[keycode] = 1;
912         else
913             vs->modifiers_state[keycode] = 0;
914         break;
915     case 0x02 ... 0x0a: /* '1' to '9' keys */ 
916         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
917             /* Reset the modifiers sent to the current console */
918             reset_keys(vs);
919             console_select(keycode - 0x02);
920             return;
921         }
922         break;
923     }
924
925     if (is_graphic_console()) {
926         if (keycode & 0x80)
927             kbd_put_keycode(0xe0);
928         if (down)
929             kbd_put_keycode(keycode & 0x7f);
930         else
931             kbd_put_keycode(keycode | 0x80);
932     } else {
933         /* QEMU console emulation */
934         if (down) {
935             switch (keycode) {
936             case 0x2a:                          /* Left Shift */
937             case 0x36:                          /* Right Shift */
938             case 0x1d:                          /* Left CTRL */
939             case 0x9d:                          /* Right CTRL */
940             case 0x38:                          /* Left ALT */
941             case 0xb8:                          /* Right ALT */
942                 break;
943             case 0xc8:
944                 kbd_put_keysym(QEMU_KEY_UP);
945                 break;
946             case 0xd0:
947                 kbd_put_keysym(QEMU_KEY_DOWN);
948                 break;
949             case 0xcb:
950                 kbd_put_keysym(QEMU_KEY_LEFT);
951                 break;
952             case 0xcd:
953                 kbd_put_keysym(QEMU_KEY_RIGHT);
954                 break;
955             case 0xd3:
956                 kbd_put_keysym(QEMU_KEY_DELETE);
957                 break;
958             case 0xc7:
959                 kbd_put_keysym(QEMU_KEY_HOME);
960                 break;
961             case 0xcf:
962                 kbd_put_keysym(QEMU_KEY_END);
963                 break;
964             case 0xc9:
965                 kbd_put_keysym(QEMU_KEY_PAGEUP);
966                 break;
967             case 0xd1:
968                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
969                 break;
970             default:
971                 kbd_put_keysym(sym);
972                 break;
973             }
974         }
975     }
976 }
977
978 static void key_event(VncState *vs, int down, uint32_t sym)
979 {
980     if (sym >= 'A' && sym <= 'Z')
981         sym = sym - 'A' + 'a';
982     do_key_event(vs, down, sym);
983 }
984
985 static void framebuffer_update_request(VncState *vs, int incremental,
986                                        int x_position, int y_position,
987                                        int w, int h)
988 {
989     if (x_position > vs->ds->width)
990         x_position = vs->ds->width;
991     if (y_position > vs->ds->height)
992         y_position = vs->ds->height;
993     if (x_position + w >= vs->ds->width)
994         w = vs->ds->width  - x_position;
995     if (y_position + h >= vs->ds->height)
996         h = vs->ds->height - y_position;
997
998     int i;
999     vs->need_update = 1;
1000     if (!incremental) {
1001         char *old_row = vs->old_data + y_position * vs->ds->linesize;
1002
1003         for (i = 0; i < h; i++) {
1004             vnc_set_bits(vs->dirty_row[y_position + i], 
1005                          (vs->ds->width / 16), VNC_DIRTY_WORDS);
1006             memset(old_row, 42, vs->ds->width * vs->depth);
1007             old_row += vs->ds->linesize;
1008         }
1009     }
1010 }
1011
1012 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1013 {
1014     int i;
1015
1016     vs->has_hextile = 0;
1017     vs->has_resize = 0;
1018     vs->has_pointer_type_change = 0;
1019     vs->absolute = -1;
1020     vs->ds->dpy_copy = NULL;
1021
1022     for (i = n_encodings - 1; i >= 0; i--) {
1023         switch (encodings[i]) {
1024         case 0: /* Raw */
1025             vs->has_hextile = 0;
1026             break;
1027         case 1: /* CopyRect */
1028             vs->ds->dpy_copy = vnc_copy;
1029             break;
1030         case 5: /* Hextile */
1031             vs->has_hextile = 1;
1032             break;
1033         case -223: /* DesktopResize */
1034             vs->has_resize = 1;
1035             break;
1036         case -257:
1037             vs->has_pointer_type_change = 1;
1038             break;
1039         default:
1040             break;
1041         }
1042     }
1043
1044     check_pointer_type_change(vs, kbd_mouse_is_absolute());
1045 }
1046
1047 static int compute_nbits(unsigned int val)
1048 {
1049     int n;
1050     n = 0;
1051     while (val != 0) {
1052         n++;
1053         val >>= 1;
1054     }
1055     return n;
1056 }
1057
1058 static void set_pixel_format(VncState *vs,
1059                              int bits_per_pixel, int depth,
1060                              int big_endian_flag, int true_color_flag,
1061                              int red_max, int green_max, int blue_max,
1062                              int red_shift, int green_shift, int blue_shift)
1063 {
1064     int host_big_endian_flag;
1065
1066 #ifdef WORDS_BIGENDIAN
1067     host_big_endian_flag = 1;
1068 #else
1069     host_big_endian_flag = 0;
1070 #endif
1071     if (!true_color_flag) {
1072     fail:
1073         vnc_client_error(vs);
1074         return;
1075     }
1076     if (bits_per_pixel == 32 && 
1077         host_big_endian_flag == big_endian_flag &&
1078         red_max == 0xff && green_max == 0xff && blue_max == 0xff &&
1079         red_shift == 16 && green_shift == 8 && blue_shift == 0) {
1080         vs->depth = 4;
1081         vs->write_pixels = vnc_write_pixels_copy;
1082         vs->send_hextile_tile = send_hextile_tile_32;
1083     } else 
1084     if (bits_per_pixel == 16 && 
1085         host_big_endian_flag == big_endian_flag &&
1086         red_max == 31 && green_max == 63 && blue_max == 31 &&
1087         red_shift == 11 && green_shift == 5 && blue_shift == 0) {
1088         vs->depth = 2;
1089         vs->write_pixels = vnc_write_pixels_copy;
1090         vs->send_hextile_tile = send_hextile_tile_16;
1091     } else 
1092     if (bits_per_pixel == 8 && 
1093         red_max == 7 && green_max == 7 && blue_max == 3 &&
1094         red_shift == 5 && green_shift == 2 && blue_shift == 0) {
1095         vs->depth = 1;
1096         vs->write_pixels = vnc_write_pixels_copy;
1097         vs->send_hextile_tile = send_hextile_tile_8;
1098     } else 
1099     {
1100         /* generic and slower case */
1101         if (bits_per_pixel != 8 &&
1102             bits_per_pixel != 16 &&
1103             bits_per_pixel != 32)
1104             goto fail;
1105         vs->depth = 4;
1106         vs->red_shift = red_shift;
1107         vs->red_max = red_max;
1108         vs->red_shift1 = 24 - compute_nbits(red_max);
1109         vs->green_shift = green_shift;
1110         vs->green_max = green_max;
1111         vs->green_shift1 = 16 - compute_nbits(green_max);
1112         vs->blue_shift = blue_shift;
1113         vs->blue_max = blue_max;
1114         vs->blue_shift1 = 8 - compute_nbits(blue_max);
1115         vs->pix_bpp = bits_per_pixel / 8;
1116         vs->pix_big_endian = big_endian_flag;
1117         vs->write_pixels = vnc_write_pixels_generic;
1118         vs->send_hextile_tile = send_hextile_tile_generic;
1119     }
1120
1121     vnc_dpy_resize(vs->ds, vs->ds->width, vs->ds->height);
1122     memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1123     memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);
1124
1125     vga_hw_invalidate();
1126     vga_hw_update();
1127 }
1128
1129 static int protocol_client_msg(VncState *vs, char *data, size_t len)
1130 {
1131     int i;
1132     uint16_t limit;
1133
1134     switch (data[0]) {
1135     case 0:
1136         if (len == 1)
1137             return 20;
1138
1139         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1140                          read_u8(data, 6), read_u8(data, 7),
1141                          read_u16(data, 8), read_u16(data, 10),
1142                          read_u16(data, 12), read_u8(data, 14),
1143                          read_u8(data, 15), read_u8(data, 16));
1144         break;
1145     case 2:
1146         if (len == 1)
1147             return 4;
1148
1149         if (len == 4)
1150             return 4 + (read_u16(data, 2) * 4);
1151
1152         limit = read_u16(data, 2);
1153         for (i = 0; i < limit; i++) {
1154             int32_t val = read_s32(data, 4 + (i * 4));
1155             memcpy(data + 4 + (i * 4), &val, sizeof(val));
1156         }
1157
1158         set_encodings(vs, (int32_t *)(data + 4), limit);
1159         break;
1160     case 3:
1161         if (len == 1)
1162             return 10;
1163
1164         framebuffer_update_request(vs,
1165                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1166                                    read_u16(data, 6), read_u16(data, 8));
1167         break;
1168     case 4:
1169         if (len == 1)
1170             return 8;
1171
1172         key_event(vs, read_u8(data, 1), read_u32(data, 4));
1173         break;
1174     case 5:
1175         if (len == 1)
1176             return 6;
1177
1178         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1179         break;
1180     case 6:
1181         if (len == 1)
1182             return 8;
1183
1184         if (len == 8)
1185             return 8 + read_u32(data, 4);
1186
1187         client_cut_text(vs, read_u32(data, 4), data + 8);
1188         break;
1189     default:
1190         printf("Msg: %d\n", data[0]);
1191         vnc_client_error(vs);
1192         break;
1193     }
1194         
1195     vnc_read_when(vs, protocol_client_msg, 1);
1196     return 0;
1197 }
1198
1199 static int protocol_client_init(VncState *vs, char *data, size_t len)
1200 {
1201     char pad[3] = { 0, 0, 0 };
1202     char buf[1024];
1203     int size;
1204
1205     vs->width = vs->ds->width;
1206     vs->height = vs->ds->height;
1207     vnc_write_u16(vs, vs->ds->width);
1208     vnc_write_u16(vs, vs->ds->height);
1209
1210     vnc_write_u8(vs, vs->depth * 8); /* bits-per-pixel */
1211     vnc_write_u8(vs, vs->depth * 8); /* depth */
1212 #ifdef WORDS_BIGENDIAN
1213     vnc_write_u8(vs, 1);             /* big-endian-flag */
1214 #else
1215     vnc_write_u8(vs, 0);             /* big-endian-flag */
1216 #endif
1217     vnc_write_u8(vs, 1);             /* true-color-flag */
1218     if (vs->depth == 4) {
1219         vnc_write_u16(vs, 0xFF);     /* red-max */
1220         vnc_write_u16(vs, 0xFF);     /* green-max */
1221         vnc_write_u16(vs, 0xFF);     /* blue-max */
1222         vnc_write_u8(vs, 16);        /* red-shift */
1223         vnc_write_u8(vs, 8);         /* green-shift */
1224         vnc_write_u8(vs, 0);         /* blue-shift */
1225         vs->send_hextile_tile = send_hextile_tile_32;
1226     } else if (vs->depth == 2) {
1227         vnc_write_u16(vs, 31);       /* red-max */
1228         vnc_write_u16(vs, 63);       /* green-max */
1229         vnc_write_u16(vs, 31);       /* blue-max */
1230         vnc_write_u8(vs, 11);        /* red-shift */
1231         vnc_write_u8(vs, 5);         /* green-shift */
1232         vnc_write_u8(vs, 0);         /* blue-shift */
1233         vs->send_hextile_tile = send_hextile_tile_16;
1234     } else if (vs->depth == 1) {
1235         /* XXX: change QEMU pixel 8 bit pixel format to match the VNC one ? */
1236         vnc_write_u16(vs, 7);        /* red-max */
1237         vnc_write_u16(vs, 7);        /* green-max */
1238         vnc_write_u16(vs, 3);        /* blue-max */
1239         vnc_write_u8(vs, 5);         /* red-shift */
1240         vnc_write_u8(vs, 2);         /* green-shift */
1241         vnc_write_u8(vs, 0);         /* blue-shift */
1242         vs->send_hextile_tile = send_hextile_tile_8;
1243     }
1244     vs->write_pixels = vnc_write_pixels_copy;
1245         
1246     vnc_write(vs, pad, 3);           /* padding */
1247
1248     if (qemu_name)
1249         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1250     else
1251         size = snprintf(buf, sizeof(buf), "QEMU");
1252
1253     vnc_write_u32(vs, size);
1254     vnc_write(vs, buf, size);
1255     vnc_flush(vs);
1256
1257     vnc_read_when(vs, protocol_client_msg, 1);
1258
1259     return 0;
1260 }
1261
1262 static void make_challenge(VncState *vs)
1263 {
1264     int i;
1265
1266     srand(time(NULL)+getpid()+getpid()*987654+rand());
1267
1268     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1269         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1270 }
1271
1272 static int protocol_client_auth_vnc(VncState *vs, char *data, size_t len)
1273 {
1274     char response[VNC_AUTH_CHALLENGE_SIZE];
1275     int i, j, pwlen;
1276     char key[8];
1277
1278     if (!vs->password || !vs->password[0]) {
1279         VNC_DEBUG("No password configured on server");
1280         vnc_write_u32(vs, 1); /* Reject auth */
1281         if (vs->minor >= 8) {
1282             static const char err[] = "Authentication failed";
1283             vnc_write_u32(vs, sizeof(err));
1284             vnc_write(vs, err, sizeof(err));
1285         }
1286         vnc_flush(vs);
1287         vnc_client_error(vs);
1288         return 0;
1289     }
1290
1291     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1292
1293     /* Calculate the expected challenge response */
1294     pwlen = strlen(vs->password);
1295     for (i=0; i<sizeof(key); i++)
1296         key[i] = i<pwlen ? vs->password[i] : 0;
1297     deskey(key, EN0);
1298     for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1299         des(response+j, response+j);
1300
1301     /* Compare expected vs actual challenge response */
1302     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1303         VNC_DEBUG("Client challenge reponse did not match\n");
1304         vnc_write_u32(vs, 1); /* Reject auth */
1305         if (vs->minor >= 8) {
1306             static const char err[] = "Authentication failed";
1307             vnc_write_u32(vs, sizeof(err));
1308             vnc_write(vs, err, sizeof(err));
1309         }
1310         vnc_flush(vs);
1311         vnc_client_error(vs);
1312     } else {
1313         VNC_DEBUG("Accepting VNC challenge response\n");
1314         vnc_write_u32(vs, 0); /* Accept auth */
1315         vnc_flush(vs);
1316
1317         vnc_read_when(vs, protocol_client_init, 1);
1318     }
1319     return 0;
1320 }
1321
1322 static int start_auth_vnc(VncState *vs)
1323 {
1324     make_challenge(vs);
1325     /* Send client a 'random' challenge */
1326     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1327     vnc_flush(vs);
1328
1329     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1330     return 0;
1331 }
1332
1333
1334 #if CONFIG_VNC_TLS
1335 #define DH_BITS 1024
1336 static gnutls_dh_params_t dh_params;
1337
1338 static int vnc_tls_initialize(void)
1339 {
1340     static int tlsinitialized = 0;
1341
1342     if (tlsinitialized)
1343         return 1;
1344
1345     if (gnutls_global_init () < 0)
1346         return 0;
1347
1348     /* XXX ought to re-generate diffie-hellmen params periodically */
1349     if (gnutls_dh_params_init (&dh_params) < 0)
1350         return 0;
1351     if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1352         return 0;
1353
1354 #if _VNC_DEBUG == 2
1355     gnutls_global_set_log_level(10);
1356     gnutls_global_set_log_function(vnc_debug_gnutls_log);
1357 #endif
1358
1359     tlsinitialized = 1;
1360
1361     return 1;
1362 }
1363
1364 static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1365 {
1366     gnutls_anon_server_credentials anon_cred;
1367     int ret;
1368
1369     if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1370         VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1371         return NULL;
1372     }
1373
1374     gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1375
1376     return anon_cred;
1377 }
1378
1379
1380 static int start_auth_vencrypt_subauth(VncState *vs)
1381 {
1382     switch (vs->subauth) {
1383     case VNC_AUTH_VENCRYPT_TLSNONE:
1384        VNC_DEBUG("Accept TLS auth none\n");
1385        vnc_write_u32(vs, 0); /* Accept auth completion */
1386        vnc_read_when(vs, protocol_client_init, 1);
1387        break;
1388
1389     case VNC_AUTH_VENCRYPT_TLSVNC:
1390        VNC_DEBUG("Start TLS auth VNC\n");
1391        return start_auth_vnc(vs);
1392
1393     default: /* Should not be possible, but just in case */
1394        VNC_DEBUG("Reject auth %d\n", vs->auth);
1395        vnc_write_u8(vs, 1);
1396        if (vs->minor >= 8) {
1397            static const char err[] = "Unsupported authentication type";
1398            vnc_write_u32(vs, sizeof(err));
1399            vnc_write(vs, err, sizeof(err));
1400        }
1401        vnc_client_error(vs);
1402     }
1403
1404     return 0;
1405 }
1406
1407 static void vnc_handshake_io(void *opaque);
1408
1409 static int vnc_continue_handshake(struct VncState *vs) {
1410     int ret;
1411
1412     if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1413        if (!gnutls_error_is_fatal(ret)) {
1414            VNC_DEBUG("Handshake interrupted (blocking)\n");
1415            if (!gnutls_record_get_direction(vs->tls_session))
1416                qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1417            else
1418                qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1419            return 0;
1420        }
1421        VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1422        vnc_client_error(vs);
1423        return -1;
1424     }
1425
1426     VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1427     vs->wiremode = VNC_WIREMODE_TLS;
1428     qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1429
1430     return start_auth_vencrypt_subauth(vs);
1431 }
1432
1433 static void vnc_handshake_io(void *opaque) {
1434     struct VncState *vs = (struct VncState *)opaque;
1435
1436     VNC_DEBUG("Handshake IO continue\n");
1437     vnc_continue_handshake(vs);
1438 }
1439
1440 static int vnc_start_tls(struct VncState *vs) {
1441     static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
1442     static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
1443     static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
1444     gnutls_anon_server_credentials anon_cred = NULL;
1445
1446     VNC_DEBUG("Do TLS setup\n");
1447     if (vnc_tls_initialize() < 0) {
1448         VNC_DEBUG("Failed to init TLS\n");
1449         vnc_client_error(vs);
1450         return -1;
1451     }
1452     if (vs->tls_session == NULL) {
1453         if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
1454             vnc_client_error(vs);
1455             return -1;
1456         }
1457
1458         if (gnutls_set_default_priority(vs->tls_session) < 0) {
1459             gnutls_deinit(vs->tls_session);
1460             vs->tls_session = NULL;
1461             vnc_client_error(vs);
1462             return -1;
1463         }
1464
1465         if (gnutls_kx_set_priority(vs->tls_session, kx_anon) < 0) {
1466             gnutls_deinit(vs->tls_session);
1467             vs->tls_session = NULL;
1468             vnc_client_error(vs);
1469             return -1;
1470         }
1471
1472         if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
1473             gnutls_deinit(vs->tls_session);
1474             vs->tls_session = NULL;
1475             vnc_client_error(vs);
1476             return -1;
1477         }
1478
1479         if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
1480             gnutls_deinit(vs->tls_session);
1481             vs->tls_session = NULL;
1482             vnc_client_error(vs);
1483             return -1;
1484         }
1485
1486         anon_cred = vnc_tls_initialize_anon_cred();
1487         if (!anon_cred) {
1488             gnutls_deinit(vs->tls_session);
1489             vs->tls_session = NULL;
1490             vnc_client_error(vs);
1491             return -1;
1492         }
1493         if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
1494             gnutls_deinit(vs->tls_session);
1495             vs->tls_session = NULL;
1496             gnutls_anon_free_server_credentials(anon_cred);
1497             vnc_client_error(vs);
1498             return -1;
1499         }
1500
1501         gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
1502         gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
1503         gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
1504     }
1505
1506     VNC_DEBUG("Start TLS handshake process\n");
1507     return vnc_continue_handshake(vs);
1508 }
1509
1510 static int protocol_client_vencrypt_auth(VncState *vs, char *data, size_t len)
1511 {
1512     int auth = read_u32(data, 0);
1513
1514     if (auth != vs->subauth) {
1515         VNC_DEBUG("Rejecting auth %d\n", auth);
1516         vnc_write_u8(vs, 0); /* Reject auth */
1517         vnc_flush(vs);
1518         vnc_client_error(vs);
1519     } else {
1520         VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
1521         vnc_write_u8(vs, 1); /* Accept auth */
1522         vnc_flush(vs);
1523
1524         if (vnc_start_tls(vs) < 0) {
1525             VNC_DEBUG("Failed to complete TLS\n");
1526             return 0;
1527         }
1528
1529         if (vs->wiremode == VNC_WIREMODE_TLS) {
1530             VNC_DEBUG("Starting VeNCrypt subauth\n");
1531             return start_auth_vencrypt_subauth(vs);
1532         } else {
1533             VNC_DEBUG("TLS handshake blocked\n");
1534             return 0;
1535         }
1536     }
1537     return 0;
1538 }
1539
1540 static int protocol_client_vencrypt_init(VncState *vs, char *data, size_t len)
1541 {
1542     if (data[0] != 0 ||
1543         data[1] != 2) {
1544         VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
1545         vnc_write_u8(vs, 1); /* Reject version */
1546         vnc_flush(vs);
1547         vnc_client_error(vs);
1548     } else {
1549         VNC_DEBUG("Sending allowed auth %d\n", vs->subauth);
1550         vnc_write_u8(vs, 0); /* Accept version */
1551         vnc_write_u8(vs, 1); /* Number of sub-auths */
1552         vnc_write_u32(vs, vs->subauth); /* The supported auth */
1553         vnc_flush(vs);
1554         vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
1555     }
1556     return 0;
1557 }
1558
1559 static int start_auth_vencrypt(VncState *vs)
1560 {
1561     /* Send VeNCrypt version 0.2 */
1562     vnc_write_u8(vs, 0);
1563     vnc_write_u8(vs, 2);
1564
1565     vnc_read_when(vs, protocol_client_vencrypt_init, 2);
1566     return 0;
1567 }
1568 #endif /* CONFIG_VNC_TLS */
1569
1570 static int protocol_client_auth(VncState *vs, char *data, size_t len)
1571 {
1572     /* We only advertise 1 auth scheme at a time, so client
1573      * must pick the one we sent. Verify this */
1574     if (data[0] != vs->auth) { /* Reject auth */
1575        VNC_DEBUG("Reject auth %d\n", (int)data[0]);
1576        vnc_write_u32(vs, 1);
1577        if (vs->minor >= 8) {
1578            static const char err[] = "Authentication failed";
1579            vnc_write_u32(vs, sizeof(err));
1580            vnc_write(vs, err, sizeof(err));
1581        }
1582        vnc_client_error(vs);
1583     } else { /* Accept requested auth */
1584        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
1585        switch (vs->auth) {
1586        case VNC_AUTH_NONE:
1587            VNC_DEBUG("Accept auth none\n");
1588            vnc_write_u32(vs, 0); /* Accept auth completion */
1589            vnc_read_when(vs, protocol_client_init, 1);
1590            break;
1591
1592        case VNC_AUTH_VNC:
1593            VNC_DEBUG("Start VNC auth\n");
1594            return start_auth_vnc(vs);
1595
1596 #if CONFIG_VNC_TLS
1597        case VNC_AUTH_VENCRYPT:
1598            VNC_DEBUG("Accept VeNCrypt auth\n");;
1599            return start_auth_vencrypt(vs);
1600 #endif /* CONFIG_VNC_TLS */
1601
1602        default: /* Should not be possible, but just in case */
1603            VNC_DEBUG("Reject auth %d\n", vs->auth);
1604            vnc_write_u8(vs, 1);
1605            if (vs->minor >= 8) {
1606                static const char err[] = "Authentication failed";
1607                vnc_write_u32(vs, sizeof(err));
1608                vnc_write(vs, err, sizeof(err));
1609            }
1610            vnc_client_error(vs);
1611        }
1612     }
1613     return 0;
1614 }
1615
1616 static int protocol_version(VncState *vs, char *version, size_t len)
1617 {
1618     char local[13];
1619
1620     memcpy(local, version, 12);
1621     local[12] = 0;
1622
1623     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
1624         VNC_DEBUG("Malformed protocol version %s\n", local);
1625         vnc_client_error(vs);
1626         return 0;
1627     }
1628     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
1629     if (vs->major != 3 ||
1630         (vs->minor != 3 &&
1631          vs->minor != 5 &&
1632          vs->minor != 7 &&
1633          vs->minor != 8)) {
1634         VNC_DEBUG("Unsupported client version\n");
1635         vnc_write_u32(vs, VNC_AUTH_INVALID);
1636         vnc_flush(vs);
1637         vnc_client_error(vs);
1638         return 0;
1639     }
1640     /* Some broken client report v3.5 which spec requires to be treated
1641      * as equivalent to v3.3 by servers
1642      */
1643     if (vs->minor == 5)
1644         vs->minor = 3;
1645
1646     if (vs->minor == 3) {
1647         if (vs->auth == VNC_AUTH_NONE) {
1648             VNC_DEBUG("Tell client auth none\n");
1649             vnc_write_u32(vs, vs->auth);
1650             vnc_flush(vs);
1651             vnc_read_when(vs, protocol_client_init, 1);
1652        } else if (vs->auth == VNC_AUTH_VNC) {
1653             VNC_DEBUG("Tell client VNC auth\n");
1654             vnc_write_u32(vs, vs->auth);
1655             vnc_flush(vs);
1656             start_auth_vnc(vs);
1657        } else {
1658             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
1659             vnc_write_u32(vs, VNC_AUTH_INVALID);
1660             vnc_flush(vs);
1661             vnc_client_error(vs);
1662        }
1663     } else {
1664         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
1665         vnc_write_u8(vs, 1); /* num auth */
1666         vnc_write_u8(vs, vs->auth);
1667         vnc_read_when(vs, protocol_client_auth, 1);
1668         vnc_flush(vs);
1669     }
1670
1671     return 0;
1672 }
1673
1674 static void vnc_listen_read(void *opaque)
1675 {
1676     VncState *vs = opaque;
1677     struct sockaddr_in addr;
1678     socklen_t addrlen = sizeof(addr);
1679
1680     vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
1681     if (vs->csock != -1) {
1682         VNC_DEBUG("New client on socket %d\n", vs->csock);
1683         socket_set_nonblock(vs->csock);
1684         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, opaque);
1685         vnc_write(vs, "RFB 003.008\n", 12);
1686         vnc_flush(vs);
1687         vnc_read_when(vs, protocol_version, 12);
1688         memset(vs->old_data, 0, vs->ds->linesize * vs->ds->height);
1689         memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1690         vs->has_resize = 0;
1691         vs->has_hextile = 0;
1692         vs->ds->dpy_copy = NULL;
1693     }
1694 }
1695
1696 extern int parse_host_port(struct sockaddr_in *saddr, const char *str);
1697
1698 void vnc_display_init(DisplayState *ds)
1699 {
1700     VncState *vs;
1701
1702     vs = qemu_mallocz(sizeof(VncState));
1703     if (!vs)
1704         exit(1);
1705
1706     ds->opaque = vs;
1707     vnc_state = vs;
1708     vs->display = NULL;
1709     vs->password = NULL;
1710
1711     vs->lsock = -1;
1712     vs->csock = -1;
1713     vs->depth = 4;
1714     vs->last_x = -1;
1715     vs->last_y = -1;
1716
1717     vs->ds = ds;
1718
1719     if (!keyboard_layout)
1720         keyboard_layout = "en-us";
1721
1722     vs->kbd_layout = init_keyboard_layout(keyboard_layout);
1723     if (!vs->kbd_layout)
1724         exit(1);
1725
1726     vs->ds->data = NULL;
1727     vs->ds->dpy_update = vnc_dpy_update;
1728     vs->ds->dpy_resize = vnc_dpy_resize;
1729     vs->ds->dpy_refresh = vnc_dpy_refresh;
1730
1731     memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1732
1733     vnc_dpy_resize(vs->ds, 640, 400);
1734 }
1735
1736 void vnc_display_close(DisplayState *ds)
1737 {
1738     VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
1739
1740     if (vs->display) {
1741         qemu_free(vs->display);
1742         vs->display = NULL;
1743     }
1744     if (vs->lsock != -1) {
1745         qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
1746         close(vs->lsock);
1747         vs->lsock = -1;
1748     }
1749     if (vs->csock != -1) {
1750         qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1751         closesocket(vs->csock);
1752         vs->csock = -1;
1753         buffer_reset(&vs->input);
1754         buffer_reset(&vs->output);
1755         vs->need_update = 0;
1756 #if CONFIG_VNC_TLS
1757         if (vs->tls_session) {
1758             gnutls_deinit(vs->tls_session);
1759             vs->tls_session = NULL;
1760         }
1761         vs->wiremode = VNC_WIREMODE_CLEAR;
1762 #endif /* CONFIG_VNC_TLS */
1763     }
1764     vs->auth = VNC_AUTH_INVALID;
1765 #if CONFIG_VNC_TLS
1766     vs->subauth = VNC_AUTH_INVALID;
1767 #endif
1768 }
1769
1770 int vnc_display_password(DisplayState *ds, const char *password)
1771 {
1772     VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
1773
1774     if (vs->password) {
1775         qemu_free(vs->password);
1776         vs->password = NULL;
1777     }
1778     if (password && password[0]) {
1779         if (!(vs->password = qemu_strdup(password)))
1780             return -1;
1781     }
1782
1783     return 0;
1784 }
1785
1786 int vnc_display_open(DisplayState *ds, const char *display)
1787 {
1788     struct sockaddr *addr;
1789     struct sockaddr_in iaddr;
1790 #ifndef _WIN32
1791     struct sockaddr_un uaddr;
1792 #endif
1793     int reuse_addr, ret;
1794     socklen_t addrlen;
1795     const char *p;
1796     VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
1797     const char *options;
1798     int password = 0;
1799 #if CONFIG_VNC_TLS
1800     int tls = 0;
1801 #endif
1802
1803     vnc_display_close(ds);
1804     if (strcmp(display, "none") == 0)
1805         return 0;
1806
1807     if (!(vs->display = strdup(display)))
1808         return -1;
1809
1810     options = display;
1811     while ((options = strchr(options, ','))) {
1812         options++;
1813         if (strncmp(options, "password", 8) == 0)
1814             password = 1; /* Require password auth */
1815 #if CONFIG_VNC_TLS
1816         else if (strncmp(options, "tls", 3) == 0)
1817             tls = 1; /* Require TLS */
1818 #endif
1819     }
1820
1821     if (password) {
1822 #if CONFIG_VNC_TLS
1823         if (tls) {
1824             VNC_DEBUG("Initializing VNC server with TLS password auth\n");
1825             vs->auth = VNC_AUTH_VENCRYPT;
1826             vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
1827         } else {
1828 #endif
1829             VNC_DEBUG("Initializing VNC server with password auth\n");
1830             vs->auth = VNC_AUTH_VNC;
1831 #if CONFIG_VNC_TLS
1832             vs->subauth = VNC_AUTH_INVALID;
1833         }
1834 #endif
1835     } else {
1836 #if CONFIG_VNC_TLS
1837         if (tls) {
1838             VNC_DEBUG("Initializing VNC server with TLS no auth\n");
1839             vs->auth = VNC_AUTH_VENCRYPT;
1840             vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
1841         } else {
1842 #endif
1843             VNC_DEBUG("Initializing VNC server with no auth\n");
1844             vs->auth = VNC_AUTH_NONE;
1845 #if CONFIG_VNC_TLS
1846             vs->subauth = VNC_AUTH_INVALID;
1847         }
1848 #endif
1849     }
1850 #ifndef _WIN32
1851     if (strstart(display, "unix:", &p)) {
1852         addr = (struct sockaddr *)&uaddr;
1853         addrlen = sizeof(uaddr);
1854
1855         vs->lsock = socket(PF_UNIX, SOCK_STREAM, 0);
1856         if (vs->lsock == -1) {
1857             fprintf(stderr, "Could not create socket\n");
1858             free(vs->display);
1859             vs->display = NULL;
1860             return -1;
1861         }
1862
1863         uaddr.sun_family = AF_UNIX;
1864         memset(uaddr.sun_path, 0, 108);
1865         snprintf(uaddr.sun_path, 108, "%s", p);
1866
1867         unlink(uaddr.sun_path);
1868     } else
1869 #endif
1870     {
1871         addr = (struct sockaddr *)&iaddr;
1872         addrlen = sizeof(iaddr);
1873
1874         if (parse_host_port(&iaddr, display) < 0) {
1875             fprintf(stderr, "Could not parse VNC address\n");
1876             free(vs->display);
1877             vs->display = NULL;
1878             return -1;
1879         }
1880
1881         iaddr.sin_port = htons(ntohs(iaddr.sin_port) + 5900);
1882
1883         vs->lsock = socket(PF_INET, SOCK_STREAM, 0);
1884         if (vs->lsock == -1) {
1885             fprintf(stderr, "Could not create socket\n");
1886             free(vs->display);
1887             vs->display = NULL;
1888             return -1;
1889         }
1890
1891         reuse_addr = 1;
1892         ret = setsockopt(vs->lsock, SOL_SOCKET, SO_REUSEADDR,
1893                          (const char *)&reuse_addr, sizeof(reuse_addr));
1894         if (ret == -1) {
1895             fprintf(stderr, "setsockopt() failed\n");
1896             close(vs->lsock);
1897             vs->lsock = -1;
1898             free(vs->display);
1899             vs->display = NULL;
1900             return -1;
1901         }
1902     }
1903
1904     if (bind(vs->lsock, addr, addrlen) == -1) {
1905         fprintf(stderr, "bind() failed\n");
1906         close(vs->lsock);
1907         vs->lsock = -1;
1908         free(vs->display);
1909         vs->display = NULL;
1910         return -1;
1911     }
1912
1913     if (listen(vs->lsock, 1) == -1) {
1914         fprintf(stderr, "listen() failed\n");
1915         close(vs->lsock);
1916         vs->lsock = -1;
1917         free(vs->display);
1918         vs->display = NULL;
1919         return -1;
1920     }
1921
1922     return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);
1923 }