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