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