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