single vnc server surface
[qemu/ar7.git] / vnc.c
blobcfaf7ba29cc13017d995a64cca6ecd4d9ba5befb
1 /*
2 * QEMU VNC display driver
4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5 * Copyright (C) 2006 Fabrice Bellard
6 * Copyright (C) 2009 Red Hat, Inc
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:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
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.
27 #include "vnc.h"
28 #include "sysemu.h"
29 #include "qemu_socket.h"
30 #include "qemu-timer.h"
31 #include "acl.h"
33 #define VNC_REFRESH_INTERVAL (1000 / 30)
35 #include "vnc_keysym.h"
36 #include "d3des.h"
38 #define count_bits(c, v) { \
39 for (c = 0; v; v >>= 1) \
40 { \
41 c += v & 1; \
42 } \
46 static VncDisplay *vnc_display; /* needed for info vnc */
47 static DisplayChangeListener *dcl;
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;
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;
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';
74 return addr;
78 char *vnc_socket_local_addr(const char *format, int fd) {
79 struct sockaddr_storage sa;
80 socklen_t salen;
82 salen = sizeof(sa);
83 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
84 return NULL;
86 return addr_to_string(format, &sa, salen);
89 char *vnc_socket_remote_addr(const char *format, int fd) {
90 struct sockaddr_storage sa;
91 socklen_t salen;
93 salen = sizeof(sa);
94 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
95 return NULL;
97 return addr_to_string(format, &sa, salen);
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";
142 #else
143 return "vencrypt";
144 #endif
145 case VNC_AUTH_SASL:
146 return "sasl";
148 return "unknown";
151 static void do_info_vnc_client(Monitor *mon, VncState *client)
153 char *clientAddr =
154 vnc_socket_remote_addr(" address: %s:%s\n",
155 client->csock);
156 if (!clientAddr)
157 return;
159 monitor_printf(mon, "Client:\n");
160 monitor_printf(mon, "%s", clientAddr);
161 free(clientAddr);
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
179 void do_info_vnc(Monitor *mon)
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);
187 if (!serverAddr)
188 return;
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));
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;
201 } else {
202 monitor_printf(mon, "Client: none\n");
207 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
208 return (vs->features & (1 << feature));
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
218 static void vnc_update_client(VncState *vs, int has_dirty);
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);
224 static void vnc_colordepth(VncState *vs);
225 static void framebuffer_update_request(VncState *vs, int incremental,
226 int x_position, int y_position,
227 int w, int h);
228 static void vnc_refresh(void *opaque);
229 static int vnc_refresh_server_surface(VncDisplay *vd);
231 static inline void vnc_set_bit(uint32_t *d, int k)
233 d[k >> 5] |= 1 << (k & 0x1f);
236 static inline void vnc_clear_bit(uint32_t *d, int k)
238 d[k >> 5] &= ~(1 << (k & 0x1f));
241 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
243 int j;
245 j = 0;
246 while (n >= 32) {
247 d[j++] = -1;
248 n -= 32;
250 if (n > 0)
251 d[j++] = (1 << n) - 1;
252 while (j < nb_words)
253 d[j++] = 0;
256 static inline int vnc_get_bit(const uint32_t *d, int k)
258 return (d[k >> 5] >> (k & 0x1f)) & 1;
261 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
262 int nb_words)
264 int i;
265 for(i = 0; i < nb_words; i++) {
266 if ((d1[i] & d2[i]) != 0)
267 return 1;
269 return 0;
272 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
274 int i;
275 VncDisplay *vd = ds->opaque;
276 struct VncSurface *s = &vd->guest;
278 h += y;
280 /* round x down to ensure the loop only spans one 16-pixel block per,
281 iteration. otherwise, if (x % 16) != 0, the last iteration may span
282 two 16-pixel blocks but we only mark the first as dirty
284 w += (x % 16);
285 x -= (x % 16);
287 x = MIN(x, s->ds->width);
288 y = MIN(y, s->ds->height);
289 w = MIN(x + w, s->ds->width) - x;
290 h = MIN(h, s->ds->height);
292 for (; y < h; y++)
293 for (i = 0; i < w; i += 16)
294 vnc_set_bit(s->dirty[y], (x + i) / 16);
297 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
298 int32_t encoding)
300 vnc_write_u16(vs, x);
301 vnc_write_u16(vs, y);
302 vnc_write_u16(vs, w);
303 vnc_write_u16(vs, h);
305 vnc_write_s32(vs, encoding);
308 void buffer_reserve(Buffer *buffer, size_t len)
310 if ((buffer->capacity - buffer->offset) < len) {
311 buffer->capacity += (len + 1024);
312 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
313 if (buffer->buffer == NULL) {
314 fprintf(stderr, "vnc: out of memory\n");
315 exit(1);
320 int buffer_empty(Buffer *buffer)
322 return buffer->offset == 0;
325 uint8_t *buffer_end(Buffer *buffer)
327 return buffer->buffer + buffer->offset;
330 void buffer_reset(Buffer *buffer)
332 buffer->offset = 0;
335 void buffer_append(Buffer *buffer, const void *data, size_t len)
337 memcpy(buffer->buffer + buffer->offset, data, len);
338 buffer->offset += len;
341 static void vnc_dpy_resize(DisplayState *ds)
343 int size_changed;
344 VncDisplay *vd = ds->opaque;
345 VncState *vs = vd->clients;
347 /* server surface */
348 if (!vd->server)
349 vd->server = qemu_mallocz(sizeof(*vd->server));
350 if (vd->server->data)
351 qemu_free(vd->server->data);
352 *(vd->server) = *(ds->surface);
353 vd->server->data = qemu_mallocz(vd->server->linesize *
354 vd->server->height);
356 /* guest surface */
357 if (!vd->guest.ds)
358 vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
359 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
360 console_color_init(ds);
361 size_changed = ds_get_width(ds) != vd->guest.ds->width ||
362 ds_get_height(ds) != vd->guest.ds->height;
363 *(vd->guest.ds) = *(ds->surface);
364 memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
366 while (vs != NULL) {
367 vnc_colordepth(vs);
368 if (size_changed) {
369 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
370 vnc_write_u8(vs, 0); /* msg id */
371 vnc_write_u8(vs, 0);
372 vnc_write_u16(vs, 1); /* number of rects */
373 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
374 VNC_ENCODING_DESKTOPRESIZE);
375 vnc_flush(vs);
378 memset(vs->dirty, 0xFF, sizeof(vs->dirty));
379 vs = vs->next;
383 /* fastest code */
384 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
386 vnc_write(vs, pixels, size);
389 /* slowest but generic code. */
390 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
392 uint8_t r, g, b;
393 VncDisplay *vd = vs->vd;
395 r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>
396 vd->server->pf.rbits);
397 g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>
398 vd->server->pf.gbits);
399 b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>
400 vd->server->pf.bbits);
401 v = (r << vs->clientds.pf.rshift) |
402 (g << vs->clientds.pf.gshift) |
403 (b << vs->clientds.pf.bshift);
404 switch(vs->clientds.pf.bytes_per_pixel) {
405 case 1:
406 buf[0] = v;
407 break;
408 case 2:
409 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
410 buf[0] = v >> 8;
411 buf[1] = v;
412 } else {
413 buf[1] = v >> 8;
414 buf[0] = v;
416 break;
417 default:
418 case 4:
419 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
420 buf[0] = v >> 24;
421 buf[1] = v >> 16;
422 buf[2] = v >> 8;
423 buf[3] = v;
424 } else {
425 buf[3] = v >> 24;
426 buf[2] = v >> 16;
427 buf[1] = v >> 8;
428 buf[0] = v;
430 break;
434 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
436 uint8_t buf[4];
437 VncDisplay *vd = vs->vd;
439 if (vd->server->pf.bytes_per_pixel == 4) {
440 uint32_t *pixels = pixels1;
441 int n, i;
442 n = size >> 2;
443 for(i = 0; i < n; i++) {
444 vnc_convert_pixel(vs, buf, pixels[i]);
445 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
447 } else if (vd->server->pf.bytes_per_pixel == 2) {
448 uint16_t *pixels = pixels1;
449 int n, i;
450 n = size >> 1;
451 for(i = 0; i < n; i++) {
452 vnc_convert_pixel(vs, buf, pixels[i]);
453 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
455 } else if (vd->server->pf.bytes_per_pixel == 1) {
456 uint8_t *pixels = pixels1;
457 int n, i;
458 n = size;
459 for(i = 0; i < n; i++) {
460 vnc_convert_pixel(vs, buf, pixels[i]);
461 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
463 } else {
464 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
468 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
470 int i;
471 uint8_t *row;
472 VncDisplay *vd = vs->vd;
474 row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
475 for (i = 0; i < h; i++) {
476 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
477 row += ds_get_linesize(vs->ds);
481 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
483 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
484 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
487 #define BPP 8
488 #include "vnchextile.h"
489 #undef BPP
491 #define BPP 16
492 #include "vnchextile.h"
493 #undef BPP
495 #define BPP 32
496 #include "vnchextile.h"
497 #undef BPP
499 #define GENERIC
500 #define BPP 8
501 #include "vnchextile.h"
502 #undef BPP
503 #undef GENERIC
505 #define GENERIC
506 #define BPP 16
507 #include "vnchextile.h"
508 #undef BPP
509 #undef GENERIC
511 #define GENERIC
512 #define BPP 32
513 #include "vnchextile.h"
514 #undef BPP
515 #undef GENERIC
517 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
519 int i, j;
520 int has_fg, has_bg;
521 uint8_t *last_fg, *last_bg;
522 VncDisplay *vd = vs->vd;
524 last_fg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);
525 last_bg = (uint8_t *) qemu_malloc(vd->server->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);
534 free(last_fg);
535 free(last_bg);
539 static void vnc_zlib_init(VncState *vs)
541 int i;
542 for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
543 vs->zlib_stream[i].opaque = NULL;
546 static void vnc_zlib_start(VncState *vs)
548 buffer_reset(&vs->zlib);
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;
555 static int vnc_zlib_stop(VncState *vs, int stream_id)
557 z_streamp zstream = &vs->zlib_stream[stream_id];
558 int previous_out;
560 // switch back to normal output/zlib buffers
561 vs->zlib = vs->output;
562 vs->output = vs->zlib_tmp;
564 // compress the zlib buffer
566 // initialize the stream
567 // XXX need one stream per session
568 if (zstream->opaque != vs) {
569 int err;
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;
576 err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
577 MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
579 if (err != Z_OK) {
580 fprintf(stderr, "VNC: error initializing zlib\n");
581 return -1;
584 zstream->opaque = vs;
587 // XXX what to do if tight_compression changed in between?
589 // reserve memory in output buffer
590 buffer_reserve(&vs->output, vs->zlib.offset + 64);
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;
600 // start encoding
601 if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
602 fprintf(stderr, "VNC: error during zlib compression\n");
603 return -1;
606 vs->output.offset = vs->output.capacity - zstream->avail_out;
607 return zstream->total_out - previous_out;
610 static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
612 int old_offset, new_offset, bytes_written;
614 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
616 // remember where we put in the follow-up size
617 old_offset = vs->output.offset;
618 vnc_write_s32(vs, 0);
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);
625 if (bytes_written == -1)
626 return;
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;
635 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
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;
652 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
654 /* send bitblit op to the vnc client */
655 vnc_write_u8(vs, 0); /* msg id */
656 vnc_write_u8(vs, 0);
657 vnc_write_u16(vs, 1); /* number of rects */
658 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
659 vnc_write_u16(vs, src_x);
660 vnc_write_u16(vs, src_y);
661 vnc_flush(vs);
664 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
666 VncDisplay *vd = ds->opaque;
667 VncState *vs, *vn;
668 uint8_t *src_row;
669 uint8_t *dst_row;
670 int i,x,y,pitch,depth,inc,w_lim,s;
671 int cmp_bytes;
673 vnc_refresh_server_surface(vd);
674 for (vs = vd->clients; vs != NULL; vs = vn) {
675 vn = vs->next;
676 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
677 vs->force_update = 1;
678 vnc_update_client(vs, 1);
679 /* vs might be free()ed here */
683 /* do bitblit op on the local surface too */
684 pitch = ds_get_linesize(vd->ds);
685 depth = ds_get_bytes_per_pixel(vd->ds);
686 src_row = vd->server->data + pitch * src_y + depth * src_x;
687 dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
688 y = dst_y;
689 inc = 1;
690 if (dst_y > src_y) {
691 /* copy backwards */
692 src_row += pitch * (h-1);
693 dst_row += pitch * (h-1);
694 pitch = -pitch;
695 y = dst_y + h - 1;
696 inc = -1;
698 w_lim = w - (16 - (dst_x % 16));
699 if (w_lim < 0)
700 w_lim = w;
701 else
702 w_lim = w - (w_lim % 16);
703 for (i = 0; i < h; i++) {
704 for (x = 0; x <= w_lim;
705 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
706 if (x == w_lim) {
707 if ((s = w - w_lim) == 0)
708 break;
709 } else if (!x) {
710 s = (16 - (dst_x % 16));
711 s = MIN(s, w_lim);
712 } else {
713 s = 16;
715 cmp_bytes = s * depth;
716 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
717 continue;
718 memmove(dst_row, src_row, cmp_bytes);
719 vs = vd->clients;
720 while (vs != NULL) {
721 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
722 vnc_set_bit(vs->dirty[y], ((x + dst_x) / 16));
723 vs = vs->next;
726 src_row += pitch - w * depth;
727 dst_row += pitch - w * depth;
728 y += inc;
731 for (vs = vd->clients; vs != NULL; vs = vs->next) {
732 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
733 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
737 static int find_and_clear_dirty_height(struct VncState *vs,
738 int y, int last_x, int x)
740 int h;
741 VncDisplay *vd = vs->vd;
743 for (h = 1; h < (vd->server->height - y); h++) {
744 int tmp_x;
745 if (!vnc_get_bit(vs->dirty[y + h], last_x))
746 break;
747 for (tmp_x = last_x; tmp_x < x; tmp_x++)
748 vnc_clear_bit(vs->dirty[y + h], tmp_x);
751 return h;
754 static void vnc_update_client(VncState *vs, int has_dirty)
756 if (vs->need_update && vs->csock != -1) {
757 VncDisplay *vd = vs->vd;
758 int y;
759 int n_rectangles;
760 int saved_offset;
762 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
763 /* kernel send buffers are full -> drop frames to throttle */
764 return;
766 if (!has_dirty && !vs->audio_cap && !vs->force_update)
767 return;
770 * Send screen updates to the vnc client using the server
771 * surface and server dirty map. guest surface updates
772 * happening in parallel don't disturb us, the next pass will
773 * send them to the client.
775 n_rectangles = 0;
776 vnc_write_u8(vs, 0); /* msg id */
777 vnc_write_u8(vs, 0);
778 saved_offset = vs->output.offset;
779 vnc_write_u16(vs, 0);
781 for (y = 0; y < vd->server->height; y++) {
782 int x;
783 int last_x = -1;
784 for (x = 0; x < vd->server->width / 16; x++) {
785 if (vnc_get_bit(vs->dirty[y], x)) {
786 if (last_x == -1) {
787 last_x = x;
789 vnc_clear_bit(vs->dirty[y], x);
790 } else {
791 if (last_x != -1) {
792 int h = find_and_clear_dirty_height(vs, y, last_x, x);
793 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
794 n_rectangles++;
796 last_x = -1;
799 if (last_x != -1) {
800 int h = find_and_clear_dirty_height(vs, y, last_x, x);
801 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
802 n_rectangles++;
805 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
806 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
807 vnc_flush(vs);
808 vs->force_update = 0;
812 if (vs->csock == -1)
813 vnc_disconnect_finish(vs);
816 /* audio */
817 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
819 VncState *vs = opaque;
821 switch (cmd) {
822 case AUD_CNOTIFY_DISABLE:
823 vnc_write_u8(vs, 255);
824 vnc_write_u8(vs, 1);
825 vnc_write_u16(vs, 0);
826 vnc_flush(vs);
827 break;
829 case AUD_CNOTIFY_ENABLE:
830 vnc_write_u8(vs, 255);
831 vnc_write_u8(vs, 1);
832 vnc_write_u16(vs, 1);
833 vnc_flush(vs);
834 break;
838 static void audio_capture_destroy(void *opaque)
842 static void audio_capture(void *opaque, void *buf, int size)
844 VncState *vs = opaque;
846 vnc_write_u8(vs, 255);
847 vnc_write_u8(vs, 1);
848 vnc_write_u16(vs, 2);
849 vnc_write_u32(vs, size);
850 vnc_write(vs, buf, size);
851 vnc_flush(vs);
854 static void audio_add(VncState *vs)
856 Monitor *mon = cur_mon;
857 struct audio_capture_ops ops;
859 if (vs->audio_cap) {
860 monitor_printf(mon, "audio already running\n");
861 return;
864 ops.notify = audio_capture_notify;
865 ops.destroy = audio_capture_destroy;
866 ops.capture = audio_capture;
868 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
869 if (!vs->audio_cap) {
870 monitor_printf(mon, "Failed to add audio capture\n");
874 static void audio_del(VncState *vs)
876 if (vs->audio_cap) {
877 AUD_del_capture(vs->audio_cap, vs);
878 vs->audio_cap = NULL;
882 static void vnc_disconnect_start(VncState *vs)
884 if (vs->csock == -1)
885 return;
886 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
887 closesocket(vs->csock);
888 vs->csock = -1;
891 static void vnc_disconnect_finish(VncState *vs)
893 if (vs->input.buffer) qemu_free(vs->input.buffer);
894 if (vs->output.buffer) qemu_free(vs->output.buffer);
895 #ifdef CONFIG_VNC_TLS
896 vnc_tls_client_cleanup(vs);
897 #endif /* CONFIG_VNC_TLS */
898 #ifdef CONFIG_VNC_SASL
899 vnc_sasl_client_cleanup(vs);
900 #endif /* CONFIG_VNC_SASL */
901 audio_del(vs);
903 VncState *p, *parent = NULL;
904 for (p = vs->vd->clients; p != NULL; p = p->next) {
905 if (p == vs) {
906 if (parent)
907 parent->next = p->next;
908 else
909 vs->vd->clients = p->next;
910 break;
912 parent = p;
914 if (!vs->vd->clients)
915 dcl->idle = 1;
917 qemu_free(vs);
918 vnc_remove_timer(vs->vd);
921 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
923 if (ret == 0 || ret == -1) {
924 if (ret == -1) {
925 switch (last_errno) {
926 case EINTR:
927 case EAGAIN:
928 #ifdef _WIN32
929 case WSAEWOULDBLOCK:
930 #endif
931 return 0;
932 default:
933 break;
937 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
938 ret, ret < 0 ? last_errno : 0);
939 vnc_disconnect_start(vs);
941 return 0;
943 return ret;
947 void vnc_client_error(VncState *vs)
949 VNC_DEBUG("Closing down client sock: protocol error\n");
950 vnc_disconnect_start(vs);
955 * Called to write a chunk of data to the client socket. The data may
956 * be the raw data, or may have already been encoded by SASL.
957 * The data will be written either straight onto the socket, or
958 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
960 * NB, it is theoretically possible to have 2 layers of encryption,
961 * both SASL, and this TLS layer. It is highly unlikely in practice
962 * though, since SASL encryption will typically be a no-op if TLS
963 * is active
965 * Returns the number of bytes written, which may be less than
966 * the requested 'datalen' if the socket would block. Returns
967 * -1 on error, and disconnects the client socket.
969 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
971 long ret;
972 #ifdef CONFIG_VNC_TLS
973 if (vs->tls.session) {
974 ret = gnutls_write(vs->tls.session, data, datalen);
975 if (ret < 0) {
976 if (ret == GNUTLS_E_AGAIN)
977 errno = EAGAIN;
978 else
979 errno = EIO;
980 ret = -1;
982 } else
983 #endif /* CONFIG_VNC_TLS */
984 ret = send(vs->csock, (const void *)data, datalen, 0);
985 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
986 return vnc_client_io_error(vs, ret, socket_error());
991 * Called to write buffered data to the client socket, when not
992 * using any SASL SSF encryption layers. Will write as much data
993 * as possible without blocking. If all buffered data is written,
994 * will switch the FD poll() handler back to read monitoring.
996 * Returns the number of bytes written, which may be less than
997 * the buffered output data if the socket would block. Returns
998 * -1 on error, and disconnects the client socket.
1000 static long vnc_client_write_plain(VncState *vs)
1002 long ret;
1004 #ifdef CONFIG_VNC_SASL
1005 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1006 vs->output.buffer, vs->output.capacity, vs->output.offset,
1007 vs->sasl.waitWriteSSF);
1009 if (vs->sasl.conn &&
1010 vs->sasl.runSSF &&
1011 vs->sasl.waitWriteSSF) {
1012 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1013 if (ret)
1014 vs->sasl.waitWriteSSF -= ret;
1015 } else
1016 #endif /* CONFIG_VNC_SASL */
1017 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1018 if (!ret)
1019 return 0;
1021 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1022 vs->output.offset -= ret;
1024 if (vs->output.offset == 0) {
1025 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1028 return ret;
1033 * First function called whenever there is data to be written to
1034 * the client socket. Will delegate actual work according to whether
1035 * SASL SSF layers are enabled (thus requiring encryption calls)
1037 void vnc_client_write(void *opaque)
1039 long ret;
1040 VncState *vs = opaque;
1042 #ifdef CONFIG_VNC_SASL
1043 if (vs->sasl.conn &&
1044 vs->sasl.runSSF &&
1045 !vs->sasl.waitWriteSSF)
1046 ret = vnc_client_write_sasl(vs);
1047 else
1048 #endif /* CONFIG_VNC_SASL */
1049 ret = vnc_client_write_plain(vs);
1052 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1054 vs->read_handler = func;
1055 vs->read_handler_expect = expecting;
1060 * Called to read a chunk of data from the client socket. The data may
1061 * be the raw data, or may need to be further decoded by SASL.
1062 * The data will be read either straight from to the socket, or
1063 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1065 * NB, it is theoretically possible to have 2 layers of encryption,
1066 * both SASL, and this TLS layer. It is highly unlikely in practice
1067 * though, since SASL encryption will typically be a no-op if TLS
1068 * is active
1070 * Returns the number of bytes read, which may be less than
1071 * the requested 'datalen' if the socket would block. Returns
1072 * -1 on error, and disconnects the client socket.
1074 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1076 long ret;
1077 #ifdef CONFIG_VNC_TLS
1078 if (vs->tls.session) {
1079 ret = gnutls_read(vs->tls.session, data, datalen);
1080 if (ret < 0) {
1081 if (ret == GNUTLS_E_AGAIN)
1082 errno = EAGAIN;
1083 else
1084 errno = EIO;
1085 ret = -1;
1087 } else
1088 #endif /* CONFIG_VNC_TLS */
1089 ret = recv(vs->csock, (void *)data, datalen, 0);
1090 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1091 return vnc_client_io_error(vs, ret, socket_error());
1096 * Called to read data from the client socket to the input buffer,
1097 * when not using any SASL SSF encryption layers. Will read as much
1098 * data as possible without blocking.
1100 * Returns the number of bytes read. Returns -1 on error, and
1101 * disconnects the client socket.
1103 static long vnc_client_read_plain(VncState *vs)
1105 int ret;
1106 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1107 vs->input.buffer, vs->input.capacity, vs->input.offset);
1108 buffer_reserve(&vs->input, 4096);
1109 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1110 if (!ret)
1111 return 0;
1112 vs->input.offset += ret;
1113 return ret;
1118 * First function called whenever there is more data to be read from
1119 * the client socket. Will delegate actual work according to whether
1120 * SASL SSF layers are enabled (thus requiring decryption calls)
1122 void vnc_client_read(void *opaque)
1124 VncState *vs = opaque;
1125 long ret;
1127 #ifdef CONFIG_VNC_SASL
1128 if (vs->sasl.conn && vs->sasl.runSSF)
1129 ret = vnc_client_read_sasl(vs);
1130 else
1131 #endif /* CONFIG_VNC_SASL */
1132 ret = vnc_client_read_plain(vs);
1133 if (!ret) {
1134 if (vs->csock == -1)
1135 vnc_disconnect_finish(vs);
1136 return;
1139 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1140 size_t len = vs->read_handler_expect;
1141 int ret;
1143 ret = vs->read_handler(vs, vs->input.buffer, len);
1144 if (vs->csock == -1) {
1145 vnc_disconnect_finish(vs);
1146 return;
1149 if (!ret) {
1150 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1151 vs->input.offset -= len;
1152 } else {
1153 vs->read_handler_expect = ret;
1158 void vnc_write(VncState *vs, const void *data, size_t len)
1160 buffer_reserve(&vs->output, len);
1162 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1163 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1166 buffer_append(&vs->output, data, len);
1169 void vnc_write_s32(VncState *vs, int32_t value)
1171 vnc_write_u32(vs, *(uint32_t *)&value);
1174 void vnc_write_u32(VncState *vs, uint32_t value)
1176 uint8_t buf[4];
1178 buf[0] = (value >> 24) & 0xFF;
1179 buf[1] = (value >> 16) & 0xFF;
1180 buf[2] = (value >> 8) & 0xFF;
1181 buf[3] = value & 0xFF;
1183 vnc_write(vs, buf, 4);
1186 void vnc_write_u16(VncState *vs, uint16_t value)
1188 uint8_t buf[2];
1190 buf[0] = (value >> 8) & 0xFF;
1191 buf[1] = value & 0xFF;
1193 vnc_write(vs, buf, 2);
1196 void vnc_write_u8(VncState *vs, uint8_t value)
1198 vnc_write(vs, (char *)&value, 1);
1201 void vnc_flush(VncState *vs)
1203 if (vs->csock != -1 && vs->output.offset)
1204 vnc_client_write(vs);
1207 uint8_t read_u8(uint8_t *data, size_t offset)
1209 return data[offset];
1212 uint16_t read_u16(uint8_t *data, size_t offset)
1214 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1217 int32_t read_s32(uint8_t *data, size_t offset)
1219 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1220 (data[offset + 2] << 8) | data[offset + 3]);
1223 uint32_t read_u32(uint8_t *data, size_t offset)
1225 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1226 (data[offset + 2] << 8) | data[offset + 3]);
1229 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1233 static void check_pointer_type_change(VncState *vs, int absolute)
1235 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1236 vnc_write_u8(vs, 0);
1237 vnc_write_u8(vs, 0);
1238 vnc_write_u16(vs, 1);
1239 vnc_framebuffer_update(vs, absolute, 0,
1240 ds_get_width(vs->ds), ds_get_height(vs->ds),
1241 VNC_ENCODING_POINTER_TYPE_CHANGE);
1242 vnc_flush(vs);
1244 vs->absolute = absolute;
1247 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1249 int buttons = 0;
1250 int dz = 0;
1252 if (button_mask & 0x01)
1253 buttons |= MOUSE_EVENT_LBUTTON;
1254 if (button_mask & 0x02)
1255 buttons |= MOUSE_EVENT_MBUTTON;
1256 if (button_mask & 0x04)
1257 buttons |= MOUSE_EVENT_RBUTTON;
1258 if (button_mask & 0x08)
1259 dz = -1;
1260 if (button_mask & 0x10)
1261 dz = 1;
1263 if (vs->absolute) {
1264 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1265 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1266 dz, buttons);
1267 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1268 x -= 0x7FFF;
1269 y -= 0x7FFF;
1271 kbd_mouse_event(x, y, dz, buttons);
1272 } else {
1273 if (vs->last_x != -1)
1274 kbd_mouse_event(x - vs->last_x,
1275 y - vs->last_y,
1276 dz, buttons);
1277 vs->last_x = x;
1278 vs->last_y = y;
1281 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1284 static void reset_keys(VncState *vs)
1286 int i;
1287 for(i = 0; i < 256; i++) {
1288 if (vs->modifiers_state[i]) {
1289 if (i & 0x80)
1290 kbd_put_keycode(0xe0);
1291 kbd_put_keycode(i | 0x80);
1292 vs->modifiers_state[i] = 0;
1297 static void press_key(VncState *vs, int keysym)
1299 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1300 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
1303 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1305 /* QEMU console switch */
1306 switch(keycode) {
1307 case 0x2a: /* Left Shift */
1308 case 0x36: /* Right Shift */
1309 case 0x1d: /* Left CTRL */
1310 case 0x9d: /* Right CTRL */
1311 case 0x38: /* Left ALT */
1312 case 0xb8: /* Right ALT */
1313 if (down)
1314 vs->modifiers_state[keycode] = 1;
1315 else
1316 vs->modifiers_state[keycode] = 0;
1317 break;
1318 case 0x02 ... 0x0a: /* '1' to '9' keys */
1319 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1320 /* Reset the modifiers sent to the current console */
1321 reset_keys(vs);
1322 console_select(keycode - 0x02);
1323 return;
1325 break;
1326 case 0x3a: /* CapsLock */
1327 case 0x45: /* NumLock */
1328 if (!down)
1329 vs->modifiers_state[keycode] ^= 1;
1330 break;
1333 if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1334 /* If the numlock state needs to change then simulate an additional
1335 keypress before sending this one. This will happen if the user
1336 toggles numlock away from the VNC window.
1338 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1339 if (!vs->modifiers_state[0x45]) {
1340 vs->modifiers_state[0x45] = 1;
1341 press_key(vs, 0xff7f);
1343 } else {
1344 if (vs->modifiers_state[0x45]) {
1345 vs->modifiers_state[0x45] = 0;
1346 press_key(vs, 0xff7f);
1351 if (is_graphic_console()) {
1352 if (keycode & 0x80)
1353 kbd_put_keycode(0xe0);
1354 if (down)
1355 kbd_put_keycode(keycode & 0x7f);
1356 else
1357 kbd_put_keycode(keycode | 0x80);
1358 } else {
1359 /* QEMU console emulation */
1360 if (down) {
1361 int numlock = vs->modifiers_state[0x45];
1362 switch (keycode) {
1363 case 0x2a: /* Left Shift */
1364 case 0x36: /* Right Shift */
1365 case 0x1d: /* Left CTRL */
1366 case 0x9d: /* Right CTRL */
1367 case 0x38: /* Left ALT */
1368 case 0xb8: /* Right ALT */
1369 break;
1370 case 0xc8:
1371 kbd_put_keysym(QEMU_KEY_UP);
1372 break;
1373 case 0xd0:
1374 kbd_put_keysym(QEMU_KEY_DOWN);
1375 break;
1376 case 0xcb:
1377 kbd_put_keysym(QEMU_KEY_LEFT);
1378 break;
1379 case 0xcd:
1380 kbd_put_keysym(QEMU_KEY_RIGHT);
1381 break;
1382 case 0xd3:
1383 kbd_put_keysym(QEMU_KEY_DELETE);
1384 break;
1385 case 0xc7:
1386 kbd_put_keysym(QEMU_KEY_HOME);
1387 break;
1388 case 0xcf:
1389 kbd_put_keysym(QEMU_KEY_END);
1390 break;
1391 case 0xc9:
1392 kbd_put_keysym(QEMU_KEY_PAGEUP);
1393 break;
1394 case 0xd1:
1395 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1396 break;
1398 case 0x47:
1399 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1400 break;
1401 case 0x48:
1402 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1403 break;
1404 case 0x49:
1405 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1406 break;
1407 case 0x4b:
1408 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1409 break;
1410 case 0x4c:
1411 kbd_put_keysym('5');
1412 break;
1413 case 0x4d:
1414 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1415 break;
1416 case 0x4f:
1417 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1418 break;
1419 case 0x50:
1420 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1421 break;
1422 case 0x51:
1423 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1424 break;
1425 case 0x52:
1426 kbd_put_keysym('0');
1427 break;
1428 case 0x53:
1429 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1430 break;
1432 case 0xb5:
1433 kbd_put_keysym('/');
1434 break;
1435 case 0x37:
1436 kbd_put_keysym('*');
1437 break;
1438 case 0x4a:
1439 kbd_put_keysym('-');
1440 break;
1441 case 0x4e:
1442 kbd_put_keysym('+');
1443 break;
1444 case 0x9c:
1445 kbd_put_keysym('\n');
1446 break;
1448 default:
1449 kbd_put_keysym(sym);
1450 break;
1456 static void key_event(VncState *vs, int down, uint32_t sym)
1458 int keycode;
1460 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1461 sym = sym - 'A' + 'a';
1463 keycode = keysym2scancode(vs->vd->kbd_layout, sym & 0xFFFF);
1464 do_key_event(vs, down, keycode, sym);
1467 static void ext_key_event(VncState *vs, int down,
1468 uint32_t sym, uint16_t keycode)
1470 /* if the user specifies a keyboard layout, always use it */
1471 if (keyboard_layout)
1472 key_event(vs, down, sym);
1473 else
1474 do_key_event(vs, down, keycode, sym);
1477 static void framebuffer_update_request(VncState *vs, int incremental,
1478 int x_position, int y_position,
1479 int w, int h)
1481 if (x_position > ds_get_width(vs->ds))
1482 x_position = ds_get_width(vs->ds);
1483 if (y_position > ds_get_height(vs->ds))
1484 y_position = ds_get_height(vs->ds);
1485 if (x_position + w >= ds_get_width(vs->ds))
1486 w = ds_get_width(vs->ds) - x_position;
1487 if (y_position + h >= ds_get_height(vs->ds))
1488 h = ds_get_height(vs->ds) - y_position;
1490 int i;
1491 vs->need_update = 1;
1492 if (!incremental) {
1493 vs->force_update = 1;
1494 for (i = 0; i < h; i++) {
1495 vnc_set_bits(vs->dirty[y_position + i],
1496 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1501 static void send_ext_key_event_ack(VncState *vs)
1503 vnc_write_u8(vs, 0);
1504 vnc_write_u8(vs, 0);
1505 vnc_write_u16(vs, 1);
1506 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1507 VNC_ENCODING_EXT_KEY_EVENT);
1508 vnc_flush(vs);
1511 static void send_ext_audio_ack(VncState *vs)
1513 vnc_write_u8(vs, 0);
1514 vnc_write_u8(vs, 0);
1515 vnc_write_u16(vs, 1);
1516 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1517 VNC_ENCODING_AUDIO);
1518 vnc_flush(vs);
1521 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1523 int i;
1524 unsigned int enc = 0;
1526 vnc_zlib_init(vs);
1527 vs->features = 0;
1528 vs->vnc_encoding = 0;
1529 vs->tight_compression = 9;
1530 vs->tight_quality = 9;
1531 vs->absolute = -1;
1533 for (i = n_encodings - 1; i >= 0; i--) {
1534 enc = encodings[i];
1535 switch (enc) {
1536 case VNC_ENCODING_RAW:
1537 vs->vnc_encoding = enc;
1538 break;
1539 case VNC_ENCODING_COPYRECT:
1540 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1541 break;
1542 case VNC_ENCODING_HEXTILE:
1543 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1544 vs->vnc_encoding = enc;
1545 break;
1546 case VNC_ENCODING_ZLIB:
1547 vs->features |= VNC_FEATURE_ZLIB_MASK;
1548 vs->vnc_encoding = enc;
1549 break;
1550 case VNC_ENCODING_DESKTOPRESIZE:
1551 vs->features |= VNC_FEATURE_RESIZE_MASK;
1552 break;
1553 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1554 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1555 break;
1556 case VNC_ENCODING_EXT_KEY_EVENT:
1557 send_ext_key_event_ack(vs);
1558 break;
1559 case VNC_ENCODING_AUDIO:
1560 send_ext_audio_ack(vs);
1561 break;
1562 case VNC_ENCODING_WMVi:
1563 vs->features |= VNC_FEATURE_WMVI_MASK;
1564 break;
1565 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1566 vs->tight_compression = (enc & 0x0F);
1567 break;
1568 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1569 vs->tight_quality = (enc & 0x0F);
1570 break;
1571 default:
1572 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1573 break;
1577 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1580 static void set_pixel_conversion(VncState *vs)
1582 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1583 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1584 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1585 vs->write_pixels = vnc_write_pixels_copy;
1586 switch (vs->ds->surface->pf.bits_per_pixel) {
1587 case 8:
1588 vs->send_hextile_tile = send_hextile_tile_8;
1589 break;
1590 case 16:
1591 vs->send_hextile_tile = send_hextile_tile_16;
1592 break;
1593 case 32:
1594 vs->send_hextile_tile = send_hextile_tile_32;
1595 break;
1597 } else {
1598 vs->write_pixels = vnc_write_pixels_generic;
1599 switch (vs->ds->surface->pf.bits_per_pixel) {
1600 case 8:
1601 vs->send_hextile_tile = send_hextile_tile_generic_8;
1602 break;
1603 case 16:
1604 vs->send_hextile_tile = send_hextile_tile_generic_16;
1605 break;
1606 case 32:
1607 vs->send_hextile_tile = send_hextile_tile_generic_32;
1608 break;
1613 static void set_pixel_format(VncState *vs,
1614 int bits_per_pixel, int depth,
1615 int big_endian_flag, int true_color_flag,
1616 int red_max, int green_max, int blue_max,
1617 int red_shift, int green_shift, int blue_shift)
1619 if (!true_color_flag) {
1620 vnc_client_error(vs);
1621 return;
1624 vs->clientds = *(vs->vd->guest.ds);
1625 vs->clientds.pf.rmax = red_max;
1626 count_bits(vs->clientds.pf.rbits, red_max);
1627 vs->clientds.pf.rshift = red_shift;
1628 vs->clientds.pf.rmask = red_max << red_shift;
1629 vs->clientds.pf.gmax = green_max;
1630 count_bits(vs->clientds.pf.gbits, green_max);
1631 vs->clientds.pf.gshift = green_shift;
1632 vs->clientds.pf.gmask = green_max << green_shift;
1633 vs->clientds.pf.bmax = blue_max;
1634 count_bits(vs->clientds.pf.bbits, blue_max);
1635 vs->clientds.pf.bshift = blue_shift;
1636 vs->clientds.pf.bmask = blue_max << blue_shift;
1637 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1638 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1639 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1640 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1642 set_pixel_conversion(vs);
1644 vga_hw_invalidate();
1645 vga_hw_update();
1648 static void pixel_format_message (VncState *vs) {
1649 char pad[3] = { 0, 0, 0 };
1651 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1652 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1654 #ifdef HOST_WORDS_BIGENDIAN
1655 vnc_write_u8(vs, 1); /* big-endian-flag */
1656 #else
1657 vnc_write_u8(vs, 0); /* big-endian-flag */
1658 #endif
1659 vnc_write_u8(vs, 1); /* true-color-flag */
1660 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1661 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1662 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1663 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1664 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1665 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1666 if (vs->ds->surface->pf.bits_per_pixel == 32)
1667 vs->send_hextile_tile = send_hextile_tile_32;
1668 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1669 vs->send_hextile_tile = send_hextile_tile_16;
1670 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1671 vs->send_hextile_tile = send_hextile_tile_8;
1672 vs->clientds = *(vs->ds->surface);
1673 vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1674 vs->write_pixels = vnc_write_pixels_copy;
1676 vnc_write(vs, pad, 3); /* padding */
1679 static void vnc_dpy_setdata(DisplayState *ds)
1681 /* We don't have to do anything */
1684 static void vnc_colordepth(VncState *vs)
1686 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1687 /* Sending a WMVi message to notify the client*/
1688 vnc_write_u8(vs, 0); /* msg id */
1689 vnc_write_u8(vs, 0);
1690 vnc_write_u16(vs, 1); /* number of rects */
1691 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1692 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1693 pixel_format_message(vs);
1694 vnc_flush(vs);
1695 } else {
1696 set_pixel_conversion(vs);
1700 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1702 int i;
1703 uint16_t limit;
1705 switch (data[0]) {
1706 case 0:
1707 if (len == 1)
1708 return 20;
1710 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1711 read_u8(data, 6), read_u8(data, 7),
1712 read_u16(data, 8), read_u16(data, 10),
1713 read_u16(data, 12), read_u8(data, 14),
1714 read_u8(data, 15), read_u8(data, 16));
1715 break;
1716 case 2:
1717 if (len == 1)
1718 return 4;
1720 if (len == 4) {
1721 limit = read_u16(data, 2);
1722 if (limit > 0)
1723 return 4 + (limit * 4);
1724 } else
1725 limit = read_u16(data, 2);
1727 for (i = 0; i < limit; i++) {
1728 int32_t val = read_s32(data, 4 + (i * 4));
1729 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1732 set_encodings(vs, (int32_t *)(data + 4), limit);
1733 break;
1734 case 3:
1735 if (len == 1)
1736 return 10;
1738 framebuffer_update_request(vs,
1739 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1740 read_u16(data, 6), read_u16(data, 8));
1741 break;
1742 case 4:
1743 if (len == 1)
1744 return 8;
1746 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1747 break;
1748 case 5:
1749 if (len == 1)
1750 return 6;
1752 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1753 break;
1754 case 6:
1755 if (len == 1)
1756 return 8;
1758 if (len == 8) {
1759 uint32_t dlen = read_u32(data, 4);
1760 if (dlen > 0)
1761 return 8 + dlen;
1764 client_cut_text(vs, read_u32(data, 4), data + 8);
1765 break;
1766 case 255:
1767 if (len == 1)
1768 return 2;
1770 switch (read_u8(data, 1)) {
1771 case 0:
1772 if (len == 2)
1773 return 12;
1775 ext_key_event(vs, read_u16(data, 2),
1776 read_u32(data, 4), read_u32(data, 8));
1777 break;
1778 case 1:
1779 if (len == 2)
1780 return 4;
1782 switch (read_u16 (data, 2)) {
1783 case 0:
1784 audio_add(vs);
1785 break;
1786 case 1:
1787 audio_del(vs);
1788 break;
1789 case 2:
1790 if (len == 4)
1791 return 10;
1792 switch (read_u8(data, 4)) {
1793 case 0: vs->as.fmt = AUD_FMT_U8; break;
1794 case 1: vs->as.fmt = AUD_FMT_S8; break;
1795 case 2: vs->as.fmt = AUD_FMT_U16; break;
1796 case 3: vs->as.fmt = AUD_FMT_S16; break;
1797 case 4: vs->as.fmt = AUD_FMT_U32; break;
1798 case 5: vs->as.fmt = AUD_FMT_S32; break;
1799 default:
1800 printf("Invalid audio format %d\n", read_u8(data, 4));
1801 vnc_client_error(vs);
1802 break;
1804 vs->as.nchannels = read_u8(data, 5);
1805 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1806 printf("Invalid audio channel coount %d\n",
1807 read_u8(data, 5));
1808 vnc_client_error(vs);
1809 break;
1811 vs->as.freq = read_u32(data, 6);
1812 break;
1813 default:
1814 printf ("Invalid audio message %d\n", read_u8(data, 4));
1815 vnc_client_error(vs);
1816 break;
1818 break;
1820 default:
1821 printf("Msg: %d\n", read_u16(data, 0));
1822 vnc_client_error(vs);
1823 break;
1825 break;
1826 default:
1827 printf("Msg: %d\n", data[0]);
1828 vnc_client_error(vs);
1829 break;
1832 vnc_read_when(vs, protocol_client_msg, 1);
1833 return 0;
1836 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1838 char buf[1024];
1839 int size;
1841 vnc_write_u16(vs, ds_get_width(vs->ds));
1842 vnc_write_u16(vs, ds_get_height(vs->ds));
1844 pixel_format_message(vs);
1846 if (qemu_name)
1847 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1848 else
1849 size = snprintf(buf, sizeof(buf), "QEMU");
1851 vnc_write_u32(vs, size);
1852 vnc_write(vs, buf, size);
1853 vnc_flush(vs);
1855 vnc_read_when(vs, protocol_client_msg, 1);
1857 return 0;
1860 void start_client_init(VncState *vs)
1862 vnc_read_when(vs, protocol_client_init, 1);
1865 static void make_challenge(VncState *vs)
1867 int i;
1869 srand(time(NULL)+getpid()+getpid()*987654+rand());
1871 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1872 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1875 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1877 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1878 int i, j, pwlen;
1879 unsigned char key[8];
1881 if (!vs->vd->password || !vs->vd->password[0]) {
1882 VNC_DEBUG("No password configured on server");
1883 vnc_write_u32(vs, 1); /* Reject auth */
1884 if (vs->minor >= 8) {
1885 static const char err[] = "Authentication failed";
1886 vnc_write_u32(vs, sizeof(err));
1887 vnc_write(vs, err, sizeof(err));
1889 vnc_flush(vs);
1890 vnc_client_error(vs);
1891 return 0;
1894 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1896 /* Calculate the expected challenge response */
1897 pwlen = strlen(vs->vd->password);
1898 for (i=0; i<sizeof(key); i++)
1899 key[i] = i<pwlen ? vs->vd->password[i] : 0;
1900 deskey(key, EN0);
1901 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1902 des(response+j, response+j);
1904 /* Compare expected vs actual challenge response */
1905 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1906 VNC_DEBUG("Client challenge reponse did not match\n");
1907 vnc_write_u32(vs, 1); /* Reject auth */
1908 if (vs->minor >= 8) {
1909 static const char err[] = "Authentication failed";
1910 vnc_write_u32(vs, sizeof(err));
1911 vnc_write(vs, err, sizeof(err));
1913 vnc_flush(vs);
1914 vnc_client_error(vs);
1915 } else {
1916 VNC_DEBUG("Accepting VNC challenge response\n");
1917 vnc_write_u32(vs, 0); /* Accept auth */
1918 vnc_flush(vs);
1920 start_client_init(vs);
1922 return 0;
1925 void start_auth_vnc(VncState *vs)
1927 make_challenge(vs);
1928 /* Send client a 'random' challenge */
1929 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1930 vnc_flush(vs);
1932 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1936 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
1938 /* We only advertise 1 auth scheme at a time, so client
1939 * must pick the one we sent. Verify this */
1940 if (data[0] != vs->vd->auth) { /* Reject auth */
1941 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
1942 vnc_write_u32(vs, 1);
1943 if (vs->minor >= 8) {
1944 static const char err[] = "Authentication failed";
1945 vnc_write_u32(vs, sizeof(err));
1946 vnc_write(vs, err, sizeof(err));
1948 vnc_client_error(vs);
1949 } else { /* Accept requested auth */
1950 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
1951 switch (vs->vd->auth) {
1952 case VNC_AUTH_NONE:
1953 VNC_DEBUG("Accept auth none\n");
1954 if (vs->minor >= 8) {
1955 vnc_write_u32(vs, 0); /* Accept auth completion */
1956 vnc_flush(vs);
1958 start_client_init(vs);
1959 break;
1961 case VNC_AUTH_VNC:
1962 VNC_DEBUG("Start VNC auth\n");
1963 start_auth_vnc(vs);
1964 break;
1966 #ifdef CONFIG_VNC_TLS
1967 case VNC_AUTH_VENCRYPT:
1968 VNC_DEBUG("Accept VeNCrypt auth\n");;
1969 start_auth_vencrypt(vs);
1970 break;
1971 #endif /* CONFIG_VNC_TLS */
1973 #ifdef CONFIG_VNC_SASL
1974 case VNC_AUTH_SASL:
1975 VNC_DEBUG("Accept SASL auth\n");
1976 start_auth_sasl(vs);
1977 break;
1978 #endif /* CONFIG_VNC_SASL */
1980 default: /* Should not be possible, but just in case */
1981 VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
1982 vnc_write_u8(vs, 1);
1983 if (vs->minor >= 8) {
1984 static const char err[] = "Authentication failed";
1985 vnc_write_u32(vs, sizeof(err));
1986 vnc_write(vs, err, sizeof(err));
1988 vnc_client_error(vs);
1991 return 0;
1994 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
1996 char local[13];
1998 memcpy(local, version, 12);
1999 local[12] = 0;
2001 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2002 VNC_DEBUG("Malformed protocol version %s\n", local);
2003 vnc_client_error(vs);
2004 return 0;
2006 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2007 if (vs->major != 3 ||
2008 (vs->minor != 3 &&
2009 vs->minor != 4 &&
2010 vs->minor != 5 &&
2011 vs->minor != 7 &&
2012 vs->minor != 8)) {
2013 VNC_DEBUG("Unsupported client version\n");
2014 vnc_write_u32(vs, VNC_AUTH_INVALID);
2015 vnc_flush(vs);
2016 vnc_client_error(vs);
2017 return 0;
2019 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2020 * as equivalent to v3.3 by servers
2022 if (vs->minor == 4 || vs->minor == 5)
2023 vs->minor = 3;
2025 if (vs->minor == 3) {
2026 if (vs->vd->auth == VNC_AUTH_NONE) {
2027 VNC_DEBUG("Tell client auth none\n");
2028 vnc_write_u32(vs, vs->vd->auth);
2029 vnc_flush(vs);
2030 start_client_init(vs);
2031 } else if (vs->vd->auth == VNC_AUTH_VNC) {
2032 VNC_DEBUG("Tell client VNC auth\n");
2033 vnc_write_u32(vs, vs->vd->auth);
2034 vnc_flush(vs);
2035 start_auth_vnc(vs);
2036 } else {
2037 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2038 vnc_write_u32(vs, VNC_AUTH_INVALID);
2039 vnc_flush(vs);
2040 vnc_client_error(vs);
2042 } else {
2043 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2044 vnc_write_u8(vs, 1); /* num auth */
2045 vnc_write_u8(vs, vs->vd->auth);
2046 vnc_read_when(vs, protocol_client_auth, 1);
2047 vnc_flush(vs);
2050 return 0;
2053 static int vnc_refresh_server_surface(VncDisplay *vd)
2055 int y;
2056 uint8_t *guest_row;
2057 uint8_t *server_row;
2058 int cmp_bytes;
2059 uint32_t width_mask[VNC_DIRTY_WORDS];
2060 VncState *vs = NULL;
2061 int has_dirty = 0;
2064 * Walk through the guest dirty map.
2065 * Check and copy modified bits from guest to server surface.
2066 * Update server dirty map.
2068 vnc_set_bits(width_mask, (ds_get_width(vd->ds) / 16), VNC_DIRTY_WORDS);
2069 cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2070 guest_row = vd->guest.ds->data;
2071 server_row = vd->server->data;
2072 for (y = 0; y < vd->guest.ds->height; y++) {
2073 if (vnc_and_bits(vd->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
2074 int x;
2075 uint8_t *guest_ptr;
2076 uint8_t *server_ptr;
2078 guest_ptr = guest_row;
2079 server_ptr = server_row;
2081 for (x = 0; x < vd->guest.ds->width;
2082 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2083 if (!vnc_get_bit(vd->guest.dirty[y], (x / 16)))
2084 continue;
2085 vnc_clear_bit(vd->guest.dirty[y], (x / 16));
2086 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2087 continue;
2088 memcpy(server_ptr, guest_ptr, cmp_bytes);
2089 vs = vd->clients;
2090 while (vs != NULL) {
2091 vnc_set_bit(vs->dirty[y], (x / 16));
2092 vs = vs->next;
2094 has_dirty++;
2097 guest_row += ds_get_linesize(vd->ds);
2098 server_row += ds_get_linesize(vd->ds);
2100 return has_dirty;
2103 static void vnc_refresh(void *opaque)
2105 VncDisplay *vd = opaque;
2106 VncState *vs = NULL;
2107 int has_dirty = 0;
2109 vga_hw_update();
2111 has_dirty = vnc_refresh_server_surface(vd);
2113 vs = vd->clients;
2114 while (vs != NULL) {
2115 vnc_update_client(vs, has_dirty);
2116 vs = vs->next;
2119 qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
2122 static void vnc_init_timer(VncDisplay *vd)
2124 if (vd->timer == NULL && vd->clients != NULL) {
2125 vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
2126 vnc_refresh(vd);
2130 static void vnc_remove_timer(VncDisplay *vd)
2132 if (vd->timer != NULL && vd->clients == NULL) {
2133 qemu_del_timer(vd->timer);
2134 qemu_free_timer(vd->timer);
2135 vd->timer = NULL;
2139 static void vnc_connect(VncDisplay *vd, int csock)
2141 VncState *vs = qemu_mallocz(sizeof(VncState));
2142 vs->csock = csock;
2144 VNC_DEBUG("New client on socket %d\n", csock);
2145 dcl->idle = 0;
2146 socket_set_nonblock(vs->csock);
2147 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2149 vs->vd = vd;
2150 vs->ds = vd->ds;
2151 vs->last_x = -1;
2152 vs->last_y = -1;
2154 vs->as.freq = 44100;
2155 vs->as.nchannels = 2;
2156 vs->as.fmt = AUD_FMT_S16;
2157 vs->as.endianness = 0;
2159 vs->next = vd->clients;
2160 vd->clients = vs;
2162 vga_hw_update();
2164 vnc_write(vs, "RFB 003.008\n", 12);
2165 vnc_flush(vs);
2166 vnc_read_when(vs, protocol_version, 12);
2167 reset_keys(vs);
2169 vnc_init_timer(vd);
2171 /* vs might be free()ed here */
2174 static void vnc_listen_read(void *opaque)
2176 VncDisplay *vs = opaque;
2177 struct sockaddr_in addr;
2178 socklen_t addrlen = sizeof(addr);
2180 /* Catch-up */
2181 vga_hw_update();
2183 int csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2184 if (csock != -1) {
2185 vnc_connect(vs, csock);
2189 void vnc_display_init(DisplayState *ds)
2191 VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2193 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2195 ds->opaque = vs;
2196 dcl->idle = 1;
2197 vnc_display = vs;
2199 vs->lsock = -1;
2201 vs->ds = ds;
2203 if (keyboard_layout)
2204 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2205 else
2206 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2208 if (!vs->kbd_layout)
2209 exit(1);
2211 dcl->dpy_copy = vnc_dpy_copy;
2212 dcl->dpy_update = vnc_dpy_update;
2213 dcl->dpy_resize = vnc_dpy_resize;
2214 dcl->dpy_setdata = vnc_dpy_setdata;
2215 register_displaychangelistener(ds, dcl);
2219 void vnc_display_close(DisplayState *ds)
2221 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2223 if (!vs)
2224 return;
2225 if (vs->display) {
2226 qemu_free(vs->display);
2227 vs->display = NULL;
2229 if (vs->lsock != -1) {
2230 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2231 close(vs->lsock);
2232 vs->lsock = -1;
2234 vs->auth = VNC_AUTH_INVALID;
2235 #ifdef CONFIG_VNC_TLS
2236 vs->subauth = VNC_AUTH_INVALID;
2237 vs->tls.x509verify = 0;
2238 #endif
2241 int vnc_display_password(DisplayState *ds, const char *password)
2243 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2245 if (vs->password) {
2246 qemu_free(vs->password);
2247 vs->password = NULL;
2249 if (password && password[0]) {
2250 if (!(vs->password = qemu_strdup(password)))
2251 return -1;
2254 return 0;
2257 char *vnc_display_local_addr(DisplayState *ds)
2259 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2261 return vnc_socket_local_addr("%s:%s", vs->lsock);
2264 int vnc_display_open(DisplayState *ds, const char *display)
2266 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2267 const char *options;
2268 int password = 0;
2269 int reverse = 0;
2270 int to_port = 0;
2271 #ifdef CONFIG_VNC_TLS
2272 int tls = 0, x509 = 0;
2273 #endif
2274 #ifdef CONFIG_VNC_SASL
2275 int sasl = 0;
2276 int saslErr;
2277 #endif
2278 int acl = 0;
2280 if (!vnc_display)
2281 return -1;
2282 vnc_display_close(ds);
2283 if (strcmp(display, "none") == 0)
2284 return 0;
2286 if (!(vs->display = strdup(display)))
2287 return -1;
2289 options = display;
2290 while ((options = strchr(options, ','))) {
2291 options++;
2292 if (strncmp(options, "password", 8) == 0) {
2293 password = 1; /* Require password auth */
2294 } else if (strncmp(options, "reverse", 7) == 0) {
2295 reverse = 1;
2296 } else if (strncmp(options, "to=", 3) == 0) {
2297 to_port = atoi(options+3) + 5900;
2298 #ifdef CONFIG_VNC_SASL
2299 } else if (strncmp(options, "sasl", 4) == 0) {
2300 sasl = 1; /* Require SASL auth */
2301 #endif
2302 #ifdef CONFIG_VNC_TLS
2303 } else if (strncmp(options, "tls", 3) == 0) {
2304 tls = 1; /* Require TLS */
2305 } else if (strncmp(options, "x509", 4) == 0) {
2306 char *start, *end;
2307 x509 = 1; /* Require x509 certificates */
2308 if (strncmp(options, "x509verify", 10) == 0)
2309 vs->tls.x509verify = 1; /* ...and verify client certs */
2311 /* Now check for 'x509=/some/path' postfix
2312 * and use that to setup x509 certificate/key paths */
2313 start = strchr(options, '=');
2314 end = strchr(options, ',');
2315 if (start && (!end || (start < end))) {
2316 int len = end ? end-(start+1) : strlen(start+1);
2317 char *path = qemu_strndup(start + 1, len);
2319 VNC_DEBUG("Trying certificate path '%s'\n", path);
2320 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2321 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2322 qemu_free(path);
2323 qemu_free(vs->display);
2324 vs->display = NULL;
2325 return -1;
2327 qemu_free(path);
2328 } else {
2329 fprintf(stderr, "No certificate path provided\n");
2330 qemu_free(vs->display);
2331 vs->display = NULL;
2332 return -1;
2334 #endif
2335 } else if (strncmp(options, "acl", 3) == 0) {
2336 acl = 1;
2340 #ifdef CONFIG_VNC_TLS
2341 if (acl && x509 && vs->tls.x509verify) {
2342 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2343 fprintf(stderr, "Failed to create x509 dname ACL\n");
2344 exit(1);
2347 #endif
2348 #ifdef CONFIG_VNC_SASL
2349 if (acl && sasl) {
2350 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2351 fprintf(stderr, "Failed to create username ACL\n");
2352 exit(1);
2355 #endif
2358 * Combinations we support here:
2360 * - no-auth (clear text, no auth)
2361 * - password (clear text, weak auth)
2362 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
2363 * - tls (encrypt, weak anonymous creds, no auth)
2364 * - tls + password (encrypt, weak anonymous creds, weak auth)
2365 * - tls + sasl (encrypt, weak anonymous creds, good auth)
2366 * - tls + x509 (encrypt, good x509 creds, no auth)
2367 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
2368 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
2370 * NB1. TLS is a stackable auth scheme.
2371 * NB2. the x509 schemes have option to validate a client cert dname
2373 if (password) {
2374 #ifdef CONFIG_VNC_TLS
2375 if (tls) {
2376 vs->auth = VNC_AUTH_VENCRYPT;
2377 if (x509) {
2378 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2379 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2380 } else {
2381 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2382 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2384 } else {
2385 #endif /* CONFIG_VNC_TLS */
2386 VNC_DEBUG("Initializing VNC server with password auth\n");
2387 vs->auth = VNC_AUTH_VNC;
2388 #ifdef CONFIG_VNC_TLS
2389 vs->subauth = VNC_AUTH_INVALID;
2391 #endif /* CONFIG_VNC_TLS */
2392 #ifdef CONFIG_VNC_SASL
2393 } else if (sasl) {
2394 #ifdef CONFIG_VNC_TLS
2395 if (tls) {
2396 vs->auth = VNC_AUTH_VENCRYPT;
2397 if (x509) {
2398 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2399 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2400 } else {
2401 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2402 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2404 } else {
2405 #endif /* CONFIG_VNC_TLS */
2406 VNC_DEBUG("Initializing VNC server with SASL auth\n");
2407 vs->auth = VNC_AUTH_SASL;
2408 #ifdef CONFIG_VNC_TLS
2409 vs->subauth = VNC_AUTH_INVALID;
2411 #endif /* CONFIG_VNC_TLS */
2412 #endif /* CONFIG_VNC_SASL */
2413 } else {
2414 #ifdef CONFIG_VNC_TLS
2415 if (tls) {
2416 vs->auth = VNC_AUTH_VENCRYPT;
2417 if (x509) {
2418 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2419 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2420 } else {
2421 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2422 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2424 } else {
2425 #endif
2426 VNC_DEBUG("Initializing VNC server with no auth\n");
2427 vs->auth = VNC_AUTH_NONE;
2428 #ifdef CONFIG_VNC_TLS
2429 vs->subauth = VNC_AUTH_INVALID;
2431 #endif
2434 #ifdef CONFIG_VNC_SASL
2435 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2436 fprintf(stderr, "Failed to initialize SASL auth %s",
2437 sasl_errstring(saslErr, NULL, NULL));
2438 free(vs->display);
2439 vs->display = NULL;
2440 return -1;
2442 #endif
2444 if (reverse) {
2445 /* connect to viewer */
2446 if (strncmp(display, "unix:", 5) == 0)
2447 vs->lsock = unix_connect(display+5);
2448 else
2449 vs->lsock = inet_connect(display, SOCK_STREAM);
2450 if (-1 == vs->lsock) {
2451 free(vs->display);
2452 vs->display = NULL;
2453 return -1;
2454 } else {
2455 int csock = vs->lsock;
2456 vs->lsock = -1;
2457 vnc_connect(vs, csock);
2459 return 0;
2461 } else {
2462 /* listen for connects */
2463 char *dpy;
2464 dpy = qemu_malloc(256);
2465 if (strncmp(display, "unix:", 5) == 0) {
2466 pstrcpy(dpy, 256, "unix:");
2467 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2468 } else {
2469 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2471 if (-1 == vs->lsock) {
2472 free(dpy);
2473 return -1;
2474 } else {
2475 free(vs->display);
2476 vs->display = dpy;
2479 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);