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