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