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