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