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