VNC: Cache client info at connection time
[qemu.git] / vnc.c
blobd37fa6021fd913a86a5ba38065ea8ddfda540f10
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"
32 #include "qemu-objects.h"
34 #define VNC_REFRESH_INTERVAL_BASE 30
35 #define VNC_REFRESH_INTERVAL_INC 50
36 #define VNC_REFRESH_INTERVAL_MAX 2000
38 #include "vnc_keysym.h"
39 #include "d3des.h"
41 #define count_bits(c, v) { \
42 for (c = 0; v; v >>= 1) \
43 { \
44 c += v & 1; \
45 } \
49 static VncDisplay *vnc_display; /* needed for info vnc */
50 static DisplayChangeListener *dcl;
52 static char *addr_to_string(const char *format,
53 struct sockaddr_storage *sa,
54 socklen_t salen) {
55 char *addr;
56 char host[NI_MAXHOST];
57 char serv[NI_MAXSERV];
58 int err;
59 size_t addrlen;
61 if ((err = getnameinfo((struct sockaddr *)sa, salen,
62 host, sizeof(host),
63 serv, sizeof(serv),
64 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
65 VNC_DEBUG("Cannot resolve address %d: %s\n",
66 err, gai_strerror(err));
67 return NULL;
70 /* Enough for the existing format + the 2 vars we're
71 * substituting in. */
72 addrlen = strlen(format) + strlen(host) + strlen(serv);
73 addr = qemu_malloc(addrlen + 1);
74 snprintf(addr, addrlen, format, host, serv);
75 addr[addrlen] = '\0';
77 return addr;
81 char *vnc_socket_local_addr(const char *format, int fd) {
82 struct sockaddr_storage sa;
83 socklen_t salen;
85 salen = sizeof(sa);
86 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
87 return NULL;
89 return addr_to_string(format, &sa, salen);
92 char *vnc_socket_remote_addr(const char *format, int fd) {
93 struct sockaddr_storage sa;
94 socklen_t salen;
96 salen = sizeof(sa);
97 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
98 return NULL;
100 return addr_to_string(format, &sa, salen);
103 static QString *get_sock_family(const struct sockaddr_storage *sa)
105 const char *name;
107 switch (sa->ss_family)
109 case AF_INET:
110 name = "ipv4";
111 break;
112 case AF_INET6:
113 name = "ipv6";
114 break;
115 default:
116 name = "unknown";
117 break;
120 return qstring_from_str(name);
123 static int put_addr_qdict(QDict *qdict, struct sockaddr_storage *sa,
124 socklen_t salen)
126 char host[NI_MAXHOST];
127 char serv[NI_MAXSERV];
128 int err;
130 if ((err = getnameinfo((struct sockaddr *)sa, salen,
131 host, sizeof(host),
132 serv, sizeof(serv),
133 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
134 VNC_DEBUG("Cannot resolve address %d: %s\n",
135 err, gai_strerror(err));
136 return -1;
139 qdict_put(qdict, "host", qstring_from_str(host));
140 qdict_put(qdict, "service", qstring_from_str(serv));
141 qdict_put(qdict, "family", get_sock_family(sa));
143 return 0;
146 static int vnc_server_addr_put(QDict *qdict, int fd)
148 struct sockaddr_storage sa;
149 socklen_t salen;
151 salen = sizeof(sa);
152 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
153 return -1;
156 return put_addr_qdict(qdict, &sa, salen);
159 static int vnc_qdict_remote_addr(QDict *qdict, int fd)
161 struct sockaddr_storage sa;
162 socklen_t salen;
164 salen = sizeof(sa);
165 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
166 return -1;
169 return put_addr_qdict(qdict, &sa, salen);
172 static const char *vnc_auth_name(VncDisplay *vd) {
173 switch (vd->auth) {
174 case VNC_AUTH_INVALID:
175 return "invalid";
176 case VNC_AUTH_NONE:
177 return "none";
178 case VNC_AUTH_VNC:
179 return "vnc";
180 case VNC_AUTH_RA2:
181 return "ra2";
182 case VNC_AUTH_RA2NE:
183 return "ra2ne";
184 case VNC_AUTH_TIGHT:
185 return "tight";
186 case VNC_AUTH_ULTRA:
187 return "ultra";
188 case VNC_AUTH_TLS:
189 return "tls";
190 case VNC_AUTH_VENCRYPT:
191 #ifdef CONFIG_VNC_TLS
192 switch (vd->subauth) {
193 case VNC_AUTH_VENCRYPT_PLAIN:
194 return "vencrypt+plain";
195 case VNC_AUTH_VENCRYPT_TLSNONE:
196 return "vencrypt+tls+none";
197 case VNC_AUTH_VENCRYPT_TLSVNC:
198 return "vencrypt+tls+vnc";
199 case VNC_AUTH_VENCRYPT_TLSPLAIN:
200 return "vencrypt+tls+plain";
201 case VNC_AUTH_VENCRYPT_X509NONE:
202 return "vencrypt+x509+none";
203 case VNC_AUTH_VENCRYPT_X509VNC:
204 return "vencrypt+x509+vnc";
205 case VNC_AUTH_VENCRYPT_X509PLAIN:
206 return "vencrypt+x509+plain";
207 case VNC_AUTH_VENCRYPT_TLSSASL:
208 return "vencrypt+tls+sasl";
209 case VNC_AUTH_VENCRYPT_X509SASL:
210 return "vencrypt+x509+sasl";
211 default:
212 return "vencrypt";
214 #else
215 return "vencrypt";
216 #endif
217 case VNC_AUTH_SASL:
218 return "sasl";
220 return "unknown";
223 static int vnc_server_info_put(QDict *qdict)
225 if (vnc_server_addr_put(qdict, vnc_display->lsock) < 0) {
226 return -1;
229 qdict_put(qdict, "auth", qstring_from_str(vnc_auth_name(vnc_display)));
230 return 0;
233 static void vnc_client_cache_auth(VncState *client)
235 QDict *qdict;
237 if (!client->info) {
238 return;
241 qdict = qobject_to_qdict(client->info);
243 #ifdef CONFIG_VNC_TLS
244 if (client->tls.session &&
245 client->tls.dname) {
246 qdict_put(qdict, "x509_dname", qstring_from_str(client->tls.dname));
248 #endif
249 #ifdef CONFIG_VNC_SASL
250 if (client->sasl.conn &&
251 client->sasl.username) {
252 qdict_put(qdict, "sasl_username",
253 qstring_from_str(client->sasl.username));
255 #endif
258 static void vnc_client_cache_addr(VncState *client)
260 QDict *qdict;
262 qdict = qdict_new();
263 if (vnc_qdict_remote_addr(qdict, client->csock) < 0) {
264 QDECREF(qdict);
265 /* XXX: how to report the error? */
266 return;
269 client->info = QOBJECT(qdict);
272 static void info_vnc_iter(QObject *obj, void *opaque)
274 QDict *client;
275 Monitor *mon = opaque;
277 client = qobject_to_qdict(obj);
278 monitor_printf(mon, "Client:\n");
279 monitor_printf(mon, " address: %s:%s\n",
280 qdict_get_str(client, "host"),
281 qdict_get_str(client, "service"));
283 #ifdef CONFIG_VNC_TLS
284 monitor_printf(mon, " x509_dname: %s\n",
285 qdict_haskey(client, "x509_dname") ?
286 qdict_get_str(client, "x509_dname") : "none");
287 #endif
288 #ifdef CONFIG_VNC_SASL
289 monitor_printf(mon, " username: %s\n",
290 qdict_haskey(client, "sasl_username") ?
291 qdict_get_str(client, "sasl_username") : "none");
292 #endif
295 void do_info_vnc_print(Monitor *mon, const QObject *data)
297 QDict *server;
298 QList *clients;
300 server = qobject_to_qdict(data);
301 if (qdict_get_bool(server, "enabled") == 0) {
302 monitor_printf(mon, "Server: disabled\n");
303 return;
306 monitor_printf(mon, "Server:\n");
307 monitor_printf(mon, " address: %s:%s\n",
308 qdict_get_str(server, "host"),
309 qdict_get_str(server, "service"));
310 monitor_printf(mon, " auth: %s\n", qdict_get_str(server, "auth"));
312 clients = qdict_get_qlist(server, "clients");
313 if (qlist_empty(clients)) {
314 monitor_printf(mon, "Client: none\n");
315 } else {
316 qlist_iter(clients, info_vnc_iter, mon);
321 * do_info_vnc(): Show VNC server information
323 * Return a QDict with server information. Connected clients are returned
324 * as a QList of QDicts.
326 * The main QDict contains the following:
328 * - "enabled": true or false
329 * - "host": server's IP address
330 * - "family": address family ("ipv4" or "ipv6")
331 * - "service": server's port number
332 * - "auth": authentication method
333 * - "clients": a QList of all connected clients
335 * Clients are described by a QDict, with the following information:
337 * - "host": client's IP address
338 * - "family": address family ("ipv4" or "ipv6")
339 * - "service": client's port number
340 * - "x509_dname": TLS dname (optional)
341 * - "sasl_username": SASL username (optional)
343 * Example:
345 * { "enabled": true, "host": "0.0.0.0", "service": "50402", "auth": "vnc",
346 * "family": "ipv4",
347 * "clients": [{ "host": "127.0.0.1", "service": "50401", "family": "ipv4" }]}
349 void do_info_vnc(Monitor *mon, QObject **ret_data)
351 if (vnc_display == NULL || vnc_display->display == NULL) {
352 *ret_data = qobject_from_jsonf("{ 'enabled': false }");
353 } else {
354 QList *clist;
356 clist = qlist_new();
357 if (vnc_display->clients) {
358 VncState *client = vnc_display->clients;
359 while (client) {
360 if (client->info) {
361 /* incref so that it's not freed by upper layers */
362 qobject_incref(client->info);
363 qlist_append_obj(clist, client->info);
365 client = client->next;
369 *ret_data = qobject_from_jsonf("{ 'enabled': true, 'clients': %p }",
370 QOBJECT(clist));
371 assert(*ret_data != NULL);
373 if (vnc_server_info_put(qobject_to_qdict(*ret_data)) < 0) {
374 qobject_decref(*ret_data);
375 *ret_data = NULL;
380 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
381 return (vs->features & (1 << feature));
384 /* TODO
385 1) Get the queue working for IO.
386 2) there is some weirdness when using the -S option (the screen is grey
387 and not totally invalidated
388 3) resolutions > 1024
391 static int vnc_update_client(VncState *vs, int has_dirty);
392 static void vnc_disconnect_start(VncState *vs);
393 static void vnc_disconnect_finish(VncState *vs);
394 static void vnc_init_timer(VncDisplay *vd);
395 static void vnc_remove_timer(VncDisplay *vd);
397 static void vnc_colordepth(VncState *vs);
398 static void framebuffer_update_request(VncState *vs, int incremental,
399 int x_position, int y_position,
400 int w, int h);
401 static void vnc_refresh(void *opaque);
402 static int vnc_refresh_server_surface(VncDisplay *vd);
404 static inline void vnc_set_bit(uint32_t *d, int k)
406 d[k >> 5] |= 1 << (k & 0x1f);
409 static inline void vnc_clear_bit(uint32_t *d, int k)
411 d[k >> 5] &= ~(1 << (k & 0x1f));
414 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
416 int j;
418 j = 0;
419 while (n >= 32) {
420 d[j++] = -1;
421 n -= 32;
423 if (n > 0)
424 d[j++] = (1 << n) - 1;
425 while (j < nb_words)
426 d[j++] = 0;
429 static inline int vnc_get_bit(const uint32_t *d, int k)
431 return (d[k >> 5] >> (k & 0x1f)) & 1;
434 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
435 int nb_words)
437 int i;
438 for(i = 0; i < nb_words; i++) {
439 if ((d1[i] & d2[i]) != 0)
440 return 1;
442 return 0;
445 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
447 int i;
448 VncDisplay *vd = ds->opaque;
449 struct VncSurface *s = &vd->guest;
451 h += y;
453 /* round x down to ensure the loop only spans one 16-pixel block per,
454 iteration. otherwise, if (x % 16) != 0, the last iteration may span
455 two 16-pixel blocks but we only mark the first as dirty
457 w += (x % 16);
458 x -= (x % 16);
460 x = MIN(x, s->ds->width);
461 y = MIN(y, s->ds->height);
462 w = MIN(x + w, s->ds->width) - x;
463 h = MIN(h, s->ds->height);
465 for (; y < h; y++)
466 for (i = 0; i < w; i += 16)
467 vnc_set_bit(s->dirty[y], (x + i) / 16);
470 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
471 int32_t encoding)
473 vnc_write_u16(vs, x);
474 vnc_write_u16(vs, y);
475 vnc_write_u16(vs, w);
476 vnc_write_u16(vs, h);
478 vnc_write_s32(vs, encoding);
481 void buffer_reserve(Buffer *buffer, size_t len)
483 if ((buffer->capacity - buffer->offset) < len) {
484 buffer->capacity += (len + 1024);
485 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
486 if (buffer->buffer == NULL) {
487 fprintf(stderr, "vnc: out of memory\n");
488 exit(1);
493 int buffer_empty(Buffer *buffer)
495 return buffer->offset == 0;
498 uint8_t *buffer_end(Buffer *buffer)
500 return buffer->buffer + buffer->offset;
503 void buffer_reset(Buffer *buffer)
505 buffer->offset = 0;
508 void buffer_append(Buffer *buffer, const void *data, size_t len)
510 memcpy(buffer->buffer + buffer->offset, data, len);
511 buffer->offset += len;
514 static void vnc_dpy_resize(DisplayState *ds)
516 int size_changed;
517 VncDisplay *vd = ds->opaque;
518 VncState *vs = vd->clients;
520 /* server surface */
521 if (!vd->server)
522 vd->server = qemu_mallocz(sizeof(*vd->server));
523 if (vd->server->data)
524 qemu_free(vd->server->data);
525 *(vd->server) = *(ds->surface);
526 vd->server->data = qemu_mallocz(vd->server->linesize *
527 vd->server->height);
529 /* guest surface */
530 if (!vd->guest.ds)
531 vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
532 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
533 console_color_init(ds);
534 size_changed = ds_get_width(ds) != vd->guest.ds->width ||
535 ds_get_height(ds) != vd->guest.ds->height;
536 *(vd->guest.ds) = *(ds->surface);
537 memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
539 while (vs != NULL) {
540 vnc_colordepth(vs);
541 if (size_changed) {
542 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
543 vnc_write_u8(vs, 0); /* msg id */
544 vnc_write_u8(vs, 0);
545 vnc_write_u16(vs, 1); /* number of rects */
546 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
547 VNC_ENCODING_DESKTOPRESIZE);
548 vnc_flush(vs);
551 memset(vs->dirty, 0xFF, sizeof(vs->dirty));
552 vs = vs->next;
556 /* fastest code */
557 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
559 vnc_write(vs, pixels, size);
562 /* slowest but generic code. */
563 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
565 uint8_t r, g, b;
566 VncDisplay *vd = vs->vd;
568 r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>
569 vd->server->pf.rbits);
570 g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>
571 vd->server->pf.gbits);
572 b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>
573 vd->server->pf.bbits);
574 v = (r << vs->clientds.pf.rshift) |
575 (g << vs->clientds.pf.gshift) |
576 (b << vs->clientds.pf.bshift);
577 switch(vs->clientds.pf.bytes_per_pixel) {
578 case 1:
579 buf[0] = v;
580 break;
581 case 2:
582 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
583 buf[0] = v >> 8;
584 buf[1] = v;
585 } else {
586 buf[1] = v >> 8;
587 buf[0] = v;
589 break;
590 default:
591 case 4:
592 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
593 buf[0] = v >> 24;
594 buf[1] = v >> 16;
595 buf[2] = v >> 8;
596 buf[3] = v;
597 } else {
598 buf[3] = v >> 24;
599 buf[2] = v >> 16;
600 buf[1] = v >> 8;
601 buf[0] = v;
603 break;
607 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
609 uint8_t buf[4];
610 VncDisplay *vd = vs->vd;
612 if (vd->server->pf.bytes_per_pixel == 4) {
613 uint32_t *pixels = pixels1;
614 int n, i;
615 n = size >> 2;
616 for(i = 0; i < n; i++) {
617 vnc_convert_pixel(vs, buf, pixels[i]);
618 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
620 } else if (vd->server->pf.bytes_per_pixel == 2) {
621 uint16_t *pixels = pixels1;
622 int n, i;
623 n = size >> 1;
624 for(i = 0; i < n; i++) {
625 vnc_convert_pixel(vs, buf, pixels[i]);
626 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
628 } else if (vd->server->pf.bytes_per_pixel == 1) {
629 uint8_t *pixels = pixels1;
630 int n, i;
631 n = size;
632 for(i = 0; i < n; i++) {
633 vnc_convert_pixel(vs, buf, pixels[i]);
634 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
636 } else {
637 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
641 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
643 int i;
644 uint8_t *row;
645 VncDisplay *vd = vs->vd;
647 row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
648 for (i = 0; i < h; i++) {
649 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
650 row += ds_get_linesize(vs->ds);
654 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
656 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
657 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
660 #define BPP 8
661 #include "vnchextile.h"
662 #undef BPP
664 #define BPP 16
665 #include "vnchextile.h"
666 #undef BPP
668 #define BPP 32
669 #include "vnchextile.h"
670 #undef BPP
672 #define GENERIC
673 #define BPP 8
674 #include "vnchextile.h"
675 #undef BPP
676 #undef GENERIC
678 #define GENERIC
679 #define BPP 16
680 #include "vnchextile.h"
681 #undef BPP
682 #undef GENERIC
684 #define GENERIC
685 #define BPP 32
686 #include "vnchextile.h"
687 #undef BPP
688 #undef GENERIC
690 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
692 int i, j;
693 int has_fg, has_bg;
694 uint8_t *last_fg, *last_bg;
695 VncDisplay *vd = vs->vd;
697 last_fg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);
698 last_bg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);
699 has_fg = has_bg = 0;
700 for (j = y; j < (y + h); j += 16) {
701 for (i = x; i < (x + w); i += 16) {
702 vs->send_hextile_tile(vs, i, j,
703 MIN(16, x + w - i), MIN(16, y + h - j),
704 last_bg, last_fg, &has_bg, &has_fg);
707 free(last_fg);
708 free(last_bg);
712 #define ZALLOC_ALIGNMENT 16
714 static void *zalloc(void *x, unsigned items, unsigned size)
716 void *p;
718 size *= items;
719 size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
721 p = qemu_mallocz(size);
723 return (p);
726 static void zfree(void *x, void *addr)
728 qemu_free(addr);
731 static void vnc_zlib_init(VncState *vs)
733 int i;
734 for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
735 vs->zlib_stream[i].opaque = NULL;
738 static void vnc_zlib_start(VncState *vs)
740 buffer_reset(&vs->zlib);
742 // make the output buffer be the zlib buffer, so we can compress it later
743 vs->zlib_tmp = vs->output;
744 vs->output = vs->zlib;
747 static int vnc_zlib_stop(VncState *vs, int stream_id)
749 z_streamp zstream = &vs->zlib_stream[stream_id];
750 int previous_out;
752 // switch back to normal output/zlib buffers
753 vs->zlib = vs->output;
754 vs->output = vs->zlib_tmp;
756 // compress the zlib buffer
758 // initialize the stream
759 // XXX need one stream per session
760 if (zstream->opaque != vs) {
761 int err;
763 VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
764 VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
765 zstream->zalloc = zalloc;
766 zstream->zfree = zfree;
768 err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
769 MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
771 if (err != Z_OK) {
772 fprintf(stderr, "VNC: error initializing zlib\n");
773 return -1;
776 zstream->opaque = vs;
779 // XXX what to do if tight_compression changed in between?
781 // reserve memory in output buffer
782 buffer_reserve(&vs->output, vs->zlib.offset + 64);
784 // set pointers
785 zstream->next_in = vs->zlib.buffer;
786 zstream->avail_in = vs->zlib.offset;
787 zstream->next_out = vs->output.buffer + vs->output.offset;
788 zstream->avail_out = vs->output.capacity - vs->output.offset;
789 zstream->data_type = Z_BINARY;
790 previous_out = zstream->total_out;
792 // start encoding
793 if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
794 fprintf(stderr, "VNC: error during zlib compression\n");
795 return -1;
798 vs->output.offset = vs->output.capacity - zstream->avail_out;
799 return zstream->total_out - previous_out;
802 static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
804 int old_offset, new_offset, bytes_written;
806 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
808 // remember where we put in the follow-up size
809 old_offset = vs->output.offset;
810 vnc_write_s32(vs, 0);
812 // compress the stream
813 vnc_zlib_start(vs);
814 send_framebuffer_update_raw(vs, x, y, w, h);
815 bytes_written = vnc_zlib_stop(vs, 0);
817 if (bytes_written == -1)
818 return;
820 // hack in the size
821 new_offset = vs->output.offset;
822 vs->output.offset = old_offset;
823 vnc_write_u32(vs, bytes_written);
824 vs->output.offset = new_offset;
827 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
829 switch(vs->vnc_encoding) {
830 case VNC_ENCODING_ZLIB:
831 send_framebuffer_update_zlib(vs, x, y, w, h);
832 break;
833 case VNC_ENCODING_HEXTILE:
834 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
835 send_framebuffer_update_hextile(vs, x, y, w, h);
836 break;
837 default:
838 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
839 send_framebuffer_update_raw(vs, x, y, w, h);
840 break;
844 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
846 /* send bitblit op to the vnc client */
847 vnc_write_u8(vs, 0); /* msg id */
848 vnc_write_u8(vs, 0);
849 vnc_write_u16(vs, 1); /* number of rects */
850 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
851 vnc_write_u16(vs, src_x);
852 vnc_write_u16(vs, src_y);
853 vnc_flush(vs);
856 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
858 VncDisplay *vd = ds->opaque;
859 VncState *vs, *vn;
860 uint8_t *src_row;
861 uint8_t *dst_row;
862 int i,x,y,pitch,depth,inc,w_lim,s;
863 int cmp_bytes;
865 vnc_refresh_server_surface(vd);
866 for (vs = vd->clients; vs != NULL; vs = vn) {
867 vn = vs->next;
868 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
869 vs->force_update = 1;
870 vnc_update_client(vs, 1);
871 /* vs might be free()ed here */
875 /* do bitblit op on the local surface too */
876 pitch = ds_get_linesize(vd->ds);
877 depth = ds_get_bytes_per_pixel(vd->ds);
878 src_row = vd->server->data + pitch * src_y + depth * src_x;
879 dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
880 y = dst_y;
881 inc = 1;
882 if (dst_y > src_y) {
883 /* copy backwards */
884 src_row += pitch * (h-1);
885 dst_row += pitch * (h-1);
886 pitch = -pitch;
887 y = dst_y + h - 1;
888 inc = -1;
890 w_lim = w - (16 - (dst_x % 16));
891 if (w_lim < 0)
892 w_lim = w;
893 else
894 w_lim = w - (w_lim % 16);
895 for (i = 0; i < h; i++) {
896 for (x = 0; x <= w_lim;
897 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
898 if (x == w_lim) {
899 if ((s = w - w_lim) == 0)
900 break;
901 } else if (!x) {
902 s = (16 - (dst_x % 16));
903 s = MIN(s, w_lim);
904 } else {
905 s = 16;
907 cmp_bytes = s * depth;
908 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
909 continue;
910 memmove(dst_row, src_row, cmp_bytes);
911 vs = vd->clients;
912 while (vs != NULL) {
913 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
914 vnc_set_bit(vs->dirty[y], ((x + dst_x) / 16));
915 vs = vs->next;
918 src_row += pitch - w * depth;
919 dst_row += pitch - w * depth;
920 y += inc;
923 for (vs = vd->clients; vs != NULL; vs = vs->next) {
924 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
925 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
929 static int find_and_clear_dirty_height(struct VncState *vs,
930 int y, int last_x, int x)
932 int h;
933 VncDisplay *vd = vs->vd;
935 for (h = 1; h < (vd->server->height - y); h++) {
936 int tmp_x;
937 if (!vnc_get_bit(vs->dirty[y + h], last_x))
938 break;
939 for (tmp_x = last_x; tmp_x < x; tmp_x++)
940 vnc_clear_bit(vs->dirty[y + h], tmp_x);
943 return h;
946 static int vnc_update_client(VncState *vs, int has_dirty)
948 if (vs->need_update && vs->csock != -1) {
949 VncDisplay *vd = vs->vd;
950 int y;
951 int n_rectangles;
952 int saved_offset;
954 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
955 /* kernel send buffers are full -> drop frames to throttle */
956 return 0;
958 if (!has_dirty && !vs->audio_cap && !vs->force_update)
959 return 0;
962 * Send screen updates to the vnc client using the server
963 * surface and server dirty map. guest surface updates
964 * happening in parallel don't disturb us, the next pass will
965 * send them to the client.
967 n_rectangles = 0;
968 vnc_write_u8(vs, 0); /* msg id */
969 vnc_write_u8(vs, 0);
970 saved_offset = vs->output.offset;
971 vnc_write_u16(vs, 0);
973 for (y = 0; y < vd->server->height; y++) {
974 int x;
975 int last_x = -1;
976 for (x = 0; x < vd->server->width / 16; x++) {
977 if (vnc_get_bit(vs->dirty[y], x)) {
978 if (last_x == -1) {
979 last_x = x;
981 vnc_clear_bit(vs->dirty[y], x);
982 } else {
983 if (last_x != -1) {
984 int h = find_and_clear_dirty_height(vs, y, last_x, x);
985 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
986 n_rectangles++;
988 last_x = -1;
991 if (last_x != -1) {
992 int h = find_and_clear_dirty_height(vs, y, last_x, x);
993 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
994 n_rectangles++;
997 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
998 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
999 vnc_flush(vs);
1000 vs->force_update = 0;
1001 return n_rectangles;
1004 if (vs->csock == -1)
1005 vnc_disconnect_finish(vs);
1007 return 0;
1010 /* audio */
1011 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1013 VncState *vs = opaque;
1015 switch (cmd) {
1016 case AUD_CNOTIFY_DISABLE:
1017 vnc_write_u8(vs, 255);
1018 vnc_write_u8(vs, 1);
1019 vnc_write_u16(vs, 0);
1020 vnc_flush(vs);
1021 break;
1023 case AUD_CNOTIFY_ENABLE:
1024 vnc_write_u8(vs, 255);
1025 vnc_write_u8(vs, 1);
1026 vnc_write_u16(vs, 1);
1027 vnc_flush(vs);
1028 break;
1032 static void audio_capture_destroy(void *opaque)
1036 static void audio_capture(void *opaque, void *buf, int size)
1038 VncState *vs = opaque;
1040 vnc_write_u8(vs, 255);
1041 vnc_write_u8(vs, 1);
1042 vnc_write_u16(vs, 2);
1043 vnc_write_u32(vs, size);
1044 vnc_write(vs, buf, size);
1045 vnc_flush(vs);
1048 static void audio_add(VncState *vs)
1050 Monitor *mon = cur_mon;
1051 struct audio_capture_ops ops;
1053 if (vs->audio_cap) {
1054 monitor_printf(mon, "audio already running\n");
1055 return;
1058 ops.notify = audio_capture_notify;
1059 ops.destroy = audio_capture_destroy;
1060 ops.capture = audio_capture;
1062 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1063 if (!vs->audio_cap) {
1064 monitor_printf(mon, "Failed to add audio capture\n");
1068 static void audio_del(VncState *vs)
1070 if (vs->audio_cap) {
1071 AUD_del_capture(vs->audio_cap, vs);
1072 vs->audio_cap = NULL;
1076 static void vnc_disconnect_start(VncState *vs)
1078 if (vs->csock == -1)
1079 return;
1080 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1081 closesocket(vs->csock);
1082 vs->csock = -1;
1085 static void vnc_disconnect_finish(VncState *vs)
1087 if (vs->input.buffer) {
1088 qemu_free(vs->input.buffer);
1089 vs->input.buffer = NULL;
1091 if (vs->output.buffer) {
1092 qemu_free(vs->output.buffer);
1093 vs->output.buffer = NULL;
1096 qobject_decref(vs->info);
1098 #ifdef CONFIG_VNC_TLS
1099 vnc_tls_client_cleanup(vs);
1100 #endif /* CONFIG_VNC_TLS */
1101 #ifdef CONFIG_VNC_SASL
1102 vnc_sasl_client_cleanup(vs);
1103 #endif /* CONFIG_VNC_SASL */
1104 audio_del(vs);
1106 VncState *p, *parent = NULL;
1107 for (p = vs->vd->clients; p != NULL; p = p->next) {
1108 if (p == vs) {
1109 if (parent)
1110 parent->next = p->next;
1111 else
1112 vs->vd->clients = p->next;
1113 break;
1115 parent = p;
1117 if (!vs->vd->clients)
1118 dcl->idle = 1;
1120 vnc_remove_timer(vs->vd);
1121 qemu_free(vs);
1124 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1126 if (ret == 0 || ret == -1) {
1127 if (ret == -1) {
1128 switch (last_errno) {
1129 case EINTR:
1130 case EAGAIN:
1131 #ifdef _WIN32
1132 case WSAEWOULDBLOCK:
1133 #endif
1134 return 0;
1135 default:
1136 break;
1140 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1141 ret, ret < 0 ? last_errno : 0);
1142 vnc_disconnect_start(vs);
1144 return 0;
1146 return ret;
1150 void vnc_client_error(VncState *vs)
1152 VNC_DEBUG("Closing down client sock: protocol error\n");
1153 vnc_disconnect_start(vs);
1158 * Called to write a chunk of data to the client socket. The data may
1159 * be the raw data, or may have already been encoded by SASL.
1160 * The data will be written either straight onto the socket, or
1161 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1163 * NB, it is theoretically possible to have 2 layers of encryption,
1164 * both SASL, and this TLS layer. It is highly unlikely in practice
1165 * though, since SASL encryption will typically be a no-op if TLS
1166 * is active
1168 * Returns the number of bytes written, which may be less than
1169 * the requested 'datalen' if the socket would block. Returns
1170 * -1 on error, and disconnects the client socket.
1172 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1174 long ret;
1175 #ifdef CONFIG_VNC_TLS
1176 if (vs->tls.session) {
1177 ret = gnutls_write(vs->tls.session, data, datalen);
1178 if (ret < 0) {
1179 if (ret == GNUTLS_E_AGAIN)
1180 errno = EAGAIN;
1181 else
1182 errno = EIO;
1183 ret = -1;
1185 } else
1186 #endif /* CONFIG_VNC_TLS */
1187 ret = send(vs->csock, (const void *)data, datalen, 0);
1188 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1189 return vnc_client_io_error(vs, ret, socket_error());
1194 * Called to write buffered data to the client socket, when not
1195 * using any SASL SSF encryption layers. Will write as much data
1196 * as possible without blocking. If all buffered data is written,
1197 * will switch the FD poll() handler back to read monitoring.
1199 * Returns the number of bytes written, which may be less than
1200 * the buffered output data if the socket would block. Returns
1201 * -1 on error, and disconnects the client socket.
1203 static long vnc_client_write_plain(VncState *vs)
1205 long ret;
1207 #ifdef CONFIG_VNC_SASL
1208 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1209 vs->output.buffer, vs->output.capacity, vs->output.offset,
1210 vs->sasl.waitWriteSSF);
1212 if (vs->sasl.conn &&
1213 vs->sasl.runSSF &&
1214 vs->sasl.waitWriteSSF) {
1215 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1216 if (ret)
1217 vs->sasl.waitWriteSSF -= ret;
1218 } else
1219 #endif /* CONFIG_VNC_SASL */
1220 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1221 if (!ret)
1222 return 0;
1224 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1225 vs->output.offset -= ret;
1227 if (vs->output.offset == 0) {
1228 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1231 return ret;
1236 * First function called whenever there is data to be written to
1237 * the client socket. Will delegate actual work according to whether
1238 * SASL SSF layers are enabled (thus requiring encryption calls)
1240 void vnc_client_write(void *opaque)
1242 long ret;
1243 VncState *vs = opaque;
1245 #ifdef CONFIG_VNC_SASL
1246 if (vs->sasl.conn &&
1247 vs->sasl.runSSF &&
1248 !vs->sasl.waitWriteSSF)
1249 ret = vnc_client_write_sasl(vs);
1250 else
1251 #endif /* CONFIG_VNC_SASL */
1252 ret = vnc_client_write_plain(vs);
1255 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1257 vs->read_handler = func;
1258 vs->read_handler_expect = expecting;
1263 * Called to read a chunk of data from the client socket. The data may
1264 * be the raw data, or may need to be further decoded by SASL.
1265 * The data will be read either straight from to the socket, or
1266 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1268 * NB, it is theoretically possible to have 2 layers of encryption,
1269 * both SASL, and this TLS layer. It is highly unlikely in practice
1270 * though, since SASL encryption will typically be a no-op if TLS
1271 * is active
1273 * Returns the number of bytes read, which may be less than
1274 * the requested 'datalen' if the socket would block. Returns
1275 * -1 on error, and disconnects the client socket.
1277 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1279 long ret;
1280 #ifdef CONFIG_VNC_TLS
1281 if (vs->tls.session) {
1282 ret = gnutls_read(vs->tls.session, data, datalen);
1283 if (ret < 0) {
1284 if (ret == GNUTLS_E_AGAIN)
1285 errno = EAGAIN;
1286 else
1287 errno = EIO;
1288 ret = -1;
1290 } else
1291 #endif /* CONFIG_VNC_TLS */
1292 ret = recv(vs->csock, (void *)data, datalen, 0);
1293 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1294 return vnc_client_io_error(vs, ret, socket_error());
1299 * Called to read data from the client socket to the input buffer,
1300 * when not using any SASL SSF encryption layers. Will read as much
1301 * data as possible without blocking.
1303 * Returns the number of bytes read. Returns -1 on error, and
1304 * disconnects the client socket.
1306 static long vnc_client_read_plain(VncState *vs)
1308 int ret;
1309 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1310 vs->input.buffer, vs->input.capacity, vs->input.offset);
1311 buffer_reserve(&vs->input, 4096);
1312 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1313 if (!ret)
1314 return 0;
1315 vs->input.offset += ret;
1316 return ret;
1321 * First function called whenever there is more data to be read from
1322 * the client socket. Will delegate actual work according to whether
1323 * SASL SSF layers are enabled (thus requiring decryption calls)
1325 void vnc_client_read(void *opaque)
1327 VncState *vs = opaque;
1328 long ret;
1330 #ifdef CONFIG_VNC_SASL
1331 if (vs->sasl.conn && vs->sasl.runSSF)
1332 ret = vnc_client_read_sasl(vs);
1333 else
1334 #endif /* CONFIG_VNC_SASL */
1335 ret = vnc_client_read_plain(vs);
1336 if (!ret) {
1337 if (vs->csock == -1)
1338 vnc_disconnect_finish(vs);
1339 return;
1342 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1343 size_t len = vs->read_handler_expect;
1344 int ret;
1346 ret = vs->read_handler(vs, vs->input.buffer, len);
1347 if (vs->csock == -1) {
1348 vnc_disconnect_finish(vs);
1349 return;
1352 if (!ret) {
1353 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1354 vs->input.offset -= len;
1355 } else {
1356 vs->read_handler_expect = ret;
1361 void vnc_write(VncState *vs, const void *data, size_t len)
1363 buffer_reserve(&vs->output, len);
1365 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1366 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1369 buffer_append(&vs->output, data, len);
1372 void vnc_write_s32(VncState *vs, int32_t value)
1374 vnc_write_u32(vs, *(uint32_t *)&value);
1377 void vnc_write_u32(VncState *vs, uint32_t value)
1379 uint8_t buf[4];
1381 buf[0] = (value >> 24) & 0xFF;
1382 buf[1] = (value >> 16) & 0xFF;
1383 buf[2] = (value >> 8) & 0xFF;
1384 buf[3] = value & 0xFF;
1386 vnc_write(vs, buf, 4);
1389 void vnc_write_u16(VncState *vs, uint16_t value)
1391 uint8_t buf[2];
1393 buf[0] = (value >> 8) & 0xFF;
1394 buf[1] = value & 0xFF;
1396 vnc_write(vs, buf, 2);
1399 void vnc_write_u8(VncState *vs, uint8_t value)
1401 vnc_write(vs, (char *)&value, 1);
1404 void vnc_flush(VncState *vs)
1406 if (vs->csock != -1 && vs->output.offset)
1407 vnc_client_write(vs);
1410 uint8_t read_u8(uint8_t *data, size_t offset)
1412 return data[offset];
1415 uint16_t read_u16(uint8_t *data, size_t offset)
1417 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1420 int32_t read_s32(uint8_t *data, size_t offset)
1422 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1423 (data[offset + 2] << 8) | data[offset + 3]);
1426 uint32_t read_u32(uint8_t *data, size_t offset)
1428 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1429 (data[offset + 2] << 8) | data[offset + 3]);
1432 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1436 static void check_pointer_type_change(VncState *vs, int absolute)
1438 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1439 vnc_write_u8(vs, 0);
1440 vnc_write_u8(vs, 0);
1441 vnc_write_u16(vs, 1);
1442 vnc_framebuffer_update(vs, absolute, 0,
1443 ds_get_width(vs->ds), ds_get_height(vs->ds),
1444 VNC_ENCODING_POINTER_TYPE_CHANGE);
1445 vnc_flush(vs);
1447 vs->absolute = absolute;
1450 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1452 int buttons = 0;
1453 int dz = 0;
1455 if (button_mask & 0x01)
1456 buttons |= MOUSE_EVENT_LBUTTON;
1457 if (button_mask & 0x02)
1458 buttons |= MOUSE_EVENT_MBUTTON;
1459 if (button_mask & 0x04)
1460 buttons |= MOUSE_EVENT_RBUTTON;
1461 if (button_mask & 0x08)
1462 dz = -1;
1463 if (button_mask & 0x10)
1464 dz = 1;
1466 if (vs->absolute) {
1467 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1468 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1469 dz, buttons);
1470 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1471 x -= 0x7FFF;
1472 y -= 0x7FFF;
1474 kbd_mouse_event(x, y, dz, buttons);
1475 } else {
1476 if (vs->last_x != -1)
1477 kbd_mouse_event(x - vs->last_x,
1478 y - vs->last_y,
1479 dz, buttons);
1480 vs->last_x = x;
1481 vs->last_y = y;
1484 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1487 static void reset_keys(VncState *vs)
1489 int i;
1490 for(i = 0; i < 256; i++) {
1491 if (vs->modifiers_state[i]) {
1492 if (i & 0x80)
1493 kbd_put_keycode(0xe0);
1494 kbd_put_keycode(i | 0x80);
1495 vs->modifiers_state[i] = 0;
1500 static void press_key(VncState *vs, int keysym)
1502 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1503 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
1506 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1508 /* QEMU console switch */
1509 switch(keycode) {
1510 case 0x2a: /* Left Shift */
1511 case 0x36: /* Right Shift */
1512 case 0x1d: /* Left CTRL */
1513 case 0x9d: /* Right CTRL */
1514 case 0x38: /* Left ALT */
1515 case 0xb8: /* Right ALT */
1516 if (down)
1517 vs->modifiers_state[keycode] = 1;
1518 else
1519 vs->modifiers_state[keycode] = 0;
1520 break;
1521 case 0x02 ... 0x0a: /* '1' to '9' keys */
1522 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1523 /* Reset the modifiers sent to the current console */
1524 reset_keys(vs);
1525 console_select(keycode - 0x02);
1526 return;
1528 break;
1529 case 0x3a: /* CapsLock */
1530 case 0x45: /* NumLock */
1531 if (!down)
1532 vs->modifiers_state[keycode] ^= 1;
1533 break;
1536 if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1537 /* If the numlock state needs to change then simulate an additional
1538 keypress before sending this one. This will happen if the user
1539 toggles numlock away from the VNC window.
1541 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1542 if (!vs->modifiers_state[0x45]) {
1543 vs->modifiers_state[0x45] = 1;
1544 press_key(vs, 0xff7f);
1546 } else {
1547 if (vs->modifiers_state[0x45]) {
1548 vs->modifiers_state[0x45] = 0;
1549 press_key(vs, 0xff7f);
1554 if ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z')) {
1555 /* If the capslock state needs to change then simulate an additional
1556 keypress before sending this one. This will happen if the user
1557 toggles capslock away from the VNC window.
1559 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1560 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1561 int capslock = !!(vs->modifiers_state[0x3a]);
1562 if (capslock) {
1563 if (uppercase == shift) {
1564 vs->modifiers_state[0x3a] = 0;
1565 press_key(vs, 0xffe5);
1567 } else {
1568 if (uppercase != shift) {
1569 vs->modifiers_state[0x3a] = 1;
1570 press_key(vs, 0xffe5);
1575 if (is_graphic_console()) {
1576 if (keycode & 0x80)
1577 kbd_put_keycode(0xe0);
1578 if (down)
1579 kbd_put_keycode(keycode & 0x7f);
1580 else
1581 kbd_put_keycode(keycode | 0x80);
1582 } else {
1583 /* QEMU console emulation */
1584 if (down) {
1585 int numlock = vs->modifiers_state[0x45];
1586 switch (keycode) {
1587 case 0x2a: /* Left Shift */
1588 case 0x36: /* Right Shift */
1589 case 0x1d: /* Left CTRL */
1590 case 0x9d: /* Right CTRL */
1591 case 0x38: /* Left ALT */
1592 case 0xb8: /* Right ALT */
1593 break;
1594 case 0xc8:
1595 kbd_put_keysym(QEMU_KEY_UP);
1596 break;
1597 case 0xd0:
1598 kbd_put_keysym(QEMU_KEY_DOWN);
1599 break;
1600 case 0xcb:
1601 kbd_put_keysym(QEMU_KEY_LEFT);
1602 break;
1603 case 0xcd:
1604 kbd_put_keysym(QEMU_KEY_RIGHT);
1605 break;
1606 case 0xd3:
1607 kbd_put_keysym(QEMU_KEY_DELETE);
1608 break;
1609 case 0xc7:
1610 kbd_put_keysym(QEMU_KEY_HOME);
1611 break;
1612 case 0xcf:
1613 kbd_put_keysym(QEMU_KEY_END);
1614 break;
1615 case 0xc9:
1616 kbd_put_keysym(QEMU_KEY_PAGEUP);
1617 break;
1618 case 0xd1:
1619 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1620 break;
1622 case 0x47:
1623 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1624 break;
1625 case 0x48:
1626 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1627 break;
1628 case 0x49:
1629 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1630 break;
1631 case 0x4b:
1632 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1633 break;
1634 case 0x4c:
1635 kbd_put_keysym('5');
1636 break;
1637 case 0x4d:
1638 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1639 break;
1640 case 0x4f:
1641 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1642 break;
1643 case 0x50:
1644 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1645 break;
1646 case 0x51:
1647 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1648 break;
1649 case 0x52:
1650 kbd_put_keysym('0');
1651 break;
1652 case 0x53:
1653 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1654 break;
1656 case 0xb5:
1657 kbd_put_keysym('/');
1658 break;
1659 case 0x37:
1660 kbd_put_keysym('*');
1661 break;
1662 case 0x4a:
1663 kbd_put_keysym('-');
1664 break;
1665 case 0x4e:
1666 kbd_put_keysym('+');
1667 break;
1668 case 0x9c:
1669 kbd_put_keysym('\n');
1670 break;
1672 default:
1673 kbd_put_keysym(sym);
1674 break;
1680 static void key_event(VncState *vs, int down, uint32_t sym)
1682 int keycode;
1683 int lsym = sym;
1685 if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1686 lsym = lsym - 'A' + 'a';
1689 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF);
1690 do_key_event(vs, down, keycode, sym);
1693 static void ext_key_event(VncState *vs, int down,
1694 uint32_t sym, uint16_t keycode)
1696 /* if the user specifies a keyboard layout, always use it */
1697 if (keyboard_layout)
1698 key_event(vs, down, sym);
1699 else
1700 do_key_event(vs, down, keycode, sym);
1703 static void framebuffer_update_request(VncState *vs, int incremental,
1704 int x_position, int y_position,
1705 int w, int h)
1707 if (x_position > ds_get_width(vs->ds))
1708 x_position = ds_get_width(vs->ds);
1709 if (y_position > ds_get_height(vs->ds))
1710 y_position = ds_get_height(vs->ds);
1711 if (x_position + w >= ds_get_width(vs->ds))
1712 w = ds_get_width(vs->ds) - x_position;
1713 if (y_position + h >= ds_get_height(vs->ds))
1714 h = ds_get_height(vs->ds) - y_position;
1716 int i;
1717 vs->need_update = 1;
1718 if (!incremental) {
1719 vs->force_update = 1;
1720 for (i = 0; i < h; i++) {
1721 vnc_set_bits(vs->dirty[y_position + i],
1722 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1727 static void send_ext_key_event_ack(VncState *vs)
1729 vnc_write_u8(vs, 0);
1730 vnc_write_u8(vs, 0);
1731 vnc_write_u16(vs, 1);
1732 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1733 VNC_ENCODING_EXT_KEY_EVENT);
1734 vnc_flush(vs);
1737 static void send_ext_audio_ack(VncState *vs)
1739 vnc_write_u8(vs, 0);
1740 vnc_write_u8(vs, 0);
1741 vnc_write_u16(vs, 1);
1742 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1743 VNC_ENCODING_AUDIO);
1744 vnc_flush(vs);
1747 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1749 int i;
1750 unsigned int enc = 0;
1752 vnc_zlib_init(vs);
1753 vs->features = 0;
1754 vs->vnc_encoding = 0;
1755 vs->tight_compression = 9;
1756 vs->tight_quality = 9;
1757 vs->absolute = -1;
1759 for (i = n_encodings - 1; i >= 0; i--) {
1760 enc = encodings[i];
1761 switch (enc) {
1762 case VNC_ENCODING_RAW:
1763 vs->vnc_encoding = enc;
1764 break;
1765 case VNC_ENCODING_COPYRECT:
1766 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1767 break;
1768 case VNC_ENCODING_HEXTILE:
1769 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1770 vs->vnc_encoding = enc;
1771 break;
1772 case VNC_ENCODING_ZLIB:
1773 vs->features |= VNC_FEATURE_ZLIB_MASK;
1774 vs->vnc_encoding = enc;
1775 break;
1776 case VNC_ENCODING_DESKTOPRESIZE:
1777 vs->features |= VNC_FEATURE_RESIZE_MASK;
1778 break;
1779 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1780 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1781 break;
1782 case VNC_ENCODING_EXT_KEY_EVENT:
1783 send_ext_key_event_ack(vs);
1784 break;
1785 case VNC_ENCODING_AUDIO:
1786 send_ext_audio_ack(vs);
1787 break;
1788 case VNC_ENCODING_WMVi:
1789 vs->features |= VNC_FEATURE_WMVI_MASK;
1790 break;
1791 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1792 vs->tight_compression = (enc & 0x0F);
1793 break;
1794 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1795 vs->tight_quality = (enc & 0x0F);
1796 break;
1797 default:
1798 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1799 break;
1803 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1806 static void set_pixel_conversion(VncState *vs)
1808 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1809 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1810 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1811 vs->write_pixels = vnc_write_pixels_copy;
1812 switch (vs->ds->surface->pf.bits_per_pixel) {
1813 case 8:
1814 vs->send_hextile_tile = send_hextile_tile_8;
1815 break;
1816 case 16:
1817 vs->send_hextile_tile = send_hextile_tile_16;
1818 break;
1819 case 32:
1820 vs->send_hextile_tile = send_hextile_tile_32;
1821 break;
1823 } else {
1824 vs->write_pixels = vnc_write_pixels_generic;
1825 switch (vs->ds->surface->pf.bits_per_pixel) {
1826 case 8:
1827 vs->send_hextile_tile = send_hextile_tile_generic_8;
1828 break;
1829 case 16:
1830 vs->send_hextile_tile = send_hextile_tile_generic_16;
1831 break;
1832 case 32:
1833 vs->send_hextile_tile = send_hextile_tile_generic_32;
1834 break;
1839 static void set_pixel_format(VncState *vs,
1840 int bits_per_pixel, int depth,
1841 int big_endian_flag, int true_color_flag,
1842 int red_max, int green_max, int blue_max,
1843 int red_shift, int green_shift, int blue_shift)
1845 if (!true_color_flag) {
1846 vnc_client_error(vs);
1847 return;
1850 vs->clientds = *(vs->vd->guest.ds);
1851 vs->clientds.pf.rmax = red_max;
1852 count_bits(vs->clientds.pf.rbits, red_max);
1853 vs->clientds.pf.rshift = red_shift;
1854 vs->clientds.pf.rmask = red_max << red_shift;
1855 vs->clientds.pf.gmax = green_max;
1856 count_bits(vs->clientds.pf.gbits, green_max);
1857 vs->clientds.pf.gshift = green_shift;
1858 vs->clientds.pf.gmask = green_max << green_shift;
1859 vs->clientds.pf.bmax = blue_max;
1860 count_bits(vs->clientds.pf.bbits, blue_max);
1861 vs->clientds.pf.bshift = blue_shift;
1862 vs->clientds.pf.bmask = blue_max << blue_shift;
1863 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1864 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1865 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1866 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1868 set_pixel_conversion(vs);
1870 vga_hw_invalidate();
1871 vga_hw_update();
1874 static void pixel_format_message (VncState *vs) {
1875 char pad[3] = { 0, 0, 0 };
1877 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1878 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1880 #ifdef HOST_WORDS_BIGENDIAN
1881 vnc_write_u8(vs, 1); /* big-endian-flag */
1882 #else
1883 vnc_write_u8(vs, 0); /* big-endian-flag */
1884 #endif
1885 vnc_write_u8(vs, 1); /* true-color-flag */
1886 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1887 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1888 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1889 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1890 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1891 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1892 if (vs->ds->surface->pf.bits_per_pixel == 32)
1893 vs->send_hextile_tile = send_hextile_tile_32;
1894 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1895 vs->send_hextile_tile = send_hextile_tile_16;
1896 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1897 vs->send_hextile_tile = send_hextile_tile_8;
1898 vs->clientds = *(vs->ds->surface);
1899 vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1900 vs->write_pixels = vnc_write_pixels_copy;
1902 vnc_write(vs, pad, 3); /* padding */
1905 static void vnc_dpy_setdata(DisplayState *ds)
1907 /* We don't have to do anything */
1910 static void vnc_colordepth(VncState *vs)
1912 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1913 /* Sending a WMVi message to notify the client*/
1914 vnc_write_u8(vs, 0); /* msg id */
1915 vnc_write_u8(vs, 0);
1916 vnc_write_u16(vs, 1); /* number of rects */
1917 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1918 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1919 pixel_format_message(vs);
1920 vnc_flush(vs);
1921 } else {
1922 set_pixel_conversion(vs);
1926 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1928 int i;
1929 uint16_t limit;
1930 VncDisplay *vd = vs->vd;
1932 if (data[0] > 3) {
1933 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1934 if (!qemu_timer_expired(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval))
1935 qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
1938 switch (data[0]) {
1939 case 0:
1940 if (len == 1)
1941 return 20;
1943 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1944 read_u8(data, 6), read_u8(data, 7),
1945 read_u16(data, 8), read_u16(data, 10),
1946 read_u16(data, 12), read_u8(data, 14),
1947 read_u8(data, 15), read_u8(data, 16));
1948 break;
1949 case 2:
1950 if (len == 1)
1951 return 4;
1953 if (len == 4) {
1954 limit = read_u16(data, 2);
1955 if (limit > 0)
1956 return 4 + (limit * 4);
1957 } else
1958 limit = read_u16(data, 2);
1960 for (i = 0; i < limit; i++) {
1961 int32_t val = read_s32(data, 4 + (i * 4));
1962 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1965 set_encodings(vs, (int32_t *)(data + 4), limit);
1966 break;
1967 case 3:
1968 if (len == 1)
1969 return 10;
1971 framebuffer_update_request(vs,
1972 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1973 read_u16(data, 6), read_u16(data, 8));
1974 break;
1975 case 4:
1976 if (len == 1)
1977 return 8;
1979 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1980 break;
1981 case 5:
1982 if (len == 1)
1983 return 6;
1985 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1986 break;
1987 case 6:
1988 if (len == 1)
1989 return 8;
1991 if (len == 8) {
1992 uint32_t dlen = read_u32(data, 4);
1993 if (dlen > 0)
1994 return 8 + dlen;
1997 client_cut_text(vs, read_u32(data, 4), data + 8);
1998 break;
1999 case 255:
2000 if (len == 1)
2001 return 2;
2003 switch (read_u8(data, 1)) {
2004 case 0:
2005 if (len == 2)
2006 return 12;
2008 ext_key_event(vs, read_u16(data, 2),
2009 read_u32(data, 4), read_u32(data, 8));
2010 break;
2011 case 1:
2012 if (len == 2)
2013 return 4;
2015 switch (read_u16 (data, 2)) {
2016 case 0:
2017 audio_add(vs);
2018 break;
2019 case 1:
2020 audio_del(vs);
2021 break;
2022 case 2:
2023 if (len == 4)
2024 return 10;
2025 switch (read_u8(data, 4)) {
2026 case 0: vs->as.fmt = AUD_FMT_U8; break;
2027 case 1: vs->as.fmt = AUD_FMT_S8; break;
2028 case 2: vs->as.fmt = AUD_FMT_U16; break;
2029 case 3: vs->as.fmt = AUD_FMT_S16; break;
2030 case 4: vs->as.fmt = AUD_FMT_U32; break;
2031 case 5: vs->as.fmt = AUD_FMT_S32; break;
2032 default:
2033 printf("Invalid audio format %d\n", read_u8(data, 4));
2034 vnc_client_error(vs);
2035 break;
2037 vs->as.nchannels = read_u8(data, 5);
2038 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2039 printf("Invalid audio channel coount %d\n",
2040 read_u8(data, 5));
2041 vnc_client_error(vs);
2042 break;
2044 vs->as.freq = read_u32(data, 6);
2045 break;
2046 default:
2047 printf ("Invalid audio message %d\n", read_u8(data, 4));
2048 vnc_client_error(vs);
2049 break;
2051 break;
2053 default:
2054 printf("Msg: %d\n", read_u16(data, 0));
2055 vnc_client_error(vs);
2056 break;
2058 break;
2059 default:
2060 printf("Msg: %d\n", data[0]);
2061 vnc_client_error(vs);
2062 break;
2065 vnc_read_when(vs, protocol_client_msg, 1);
2066 return 0;
2069 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2071 char buf[1024];
2072 int size;
2074 vnc_write_u16(vs, ds_get_width(vs->ds));
2075 vnc_write_u16(vs, ds_get_height(vs->ds));
2077 pixel_format_message(vs);
2079 if (qemu_name)
2080 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2081 else
2082 size = snprintf(buf, sizeof(buf), "QEMU");
2084 vnc_write_u32(vs, size);
2085 vnc_write(vs, buf, size);
2086 vnc_flush(vs);
2088 vnc_client_cache_auth(vs);
2090 vnc_read_when(vs, protocol_client_msg, 1);
2092 return 0;
2095 void start_client_init(VncState *vs)
2097 vnc_read_when(vs, protocol_client_init, 1);
2100 static void make_challenge(VncState *vs)
2102 int i;
2104 srand(time(NULL)+getpid()+getpid()*987654+rand());
2106 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2107 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2110 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2112 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2113 int i, j, pwlen;
2114 unsigned char key[8];
2116 if (!vs->vd->password || !vs->vd->password[0]) {
2117 VNC_DEBUG("No password configured on server");
2118 vnc_write_u32(vs, 1); /* Reject auth */
2119 if (vs->minor >= 8) {
2120 static const char err[] = "Authentication failed";
2121 vnc_write_u32(vs, sizeof(err));
2122 vnc_write(vs, err, sizeof(err));
2124 vnc_flush(vs);
2125 vnc_client_error(vs);
2126 return 0;
2129 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2131 /* Calculate the expected challenge response */
2132 pwlen = strlen(vs->vd->password);
2133 for (i=0; i<sizeof(key); i++)
2134 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2135 deskey(key, EN0);
2136 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2137 des(response+j, response+j);
2139 /* Compare expected vs actual challenge response */
2140 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2141 VNC_DEBUG("Client challenge reponse did not match\n");
2142 vnc_write_u32(vs, 1); /* Reject auth */
2143 if (vs->minor >= 8) {
2144 static const char err[] = "Authentication failed";
2145 vnc_write_u32(vs, sizeof(err));
2146 vnc_write(vs, err, sizeof(err));
2148 vnc_flush(vs);
2149 vnc_client_error(vs);
2150 } else {
2151 VNC_DEBUG("Accepting VNC challenge response\n");
2152 vnc_write_u32(vs, 0); /* Accept auth */
2153 vnc_flush(vs);
2155 start_client_init(vs);
2157 return 0;
2160 void start_auth_vnc(VncState *vs)
2162 make_challenge(vs);
2163 /* Send client a 'random' challenge */
2164 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2165 vnc_flush(vs);
2167 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2171 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2173 /* We only advertise 1 auth scheme at a time, so client
2174 * must pick the one we sent. Verify this */
2175 if (data[0] != vs->vd->auth) { /* Reject auth */
2176 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2177 vnc_write_u32(vs, 1);
2178 if (vs->minor >= 8) {
2179 static const char err[] = "Authentication failed";
2180 vnc_write_u32(vs, sizeof(err));
2181 vnc_write(vs, err, sizeof(err));
2183 vnc_client_error(vs);
2184 } else { /* Accept requested auth */
2185 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2186 switch (vs->vd->auth) {
2187 case VNC_AUTH_NONE:
2188 VNC_DEBUG("Accept auth none\n");
2189 if (vs->minor >= 8) {
2190 vnc_write_u32(vs, 0); /* Accept auth completion */
2191 vnc_flush(vs);
2193 start_client_init(vs);
2194 break;
2196 case VNC_AUTH_VNC:
2197 VNC_DEBUG("Start VNC auth\n");
2198 start_auth_vnc(vs);
2199 break;
2201 #ifdef CONFIG_VNC_TLS
2202 case VNC_AUTH_VENCRYPT:
2203 VNC_DEBUG("Accept VeNCrypt auth\n");;
2204 start_auth_vencrypt(vs);
2205 break;
2206 #endif /* CONFIG_VNC_TLS */
2208 #ifdef CONFIG_VNC_SASL
2209 case VNC_AUTH_SASL:
2210 VNC_DEBUG("Accept SASL auth\n");
2211 start_auth_sasl(vs);
2212 break;
2213 #endif /* CONFIG_VNC_SASL */
2215 default: /* Should not be possible, but just in case */
2216 VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
2217 vnc_write_u8(vs, 1);
2218 if (vs->minor >= 8) {
2219 static const char err[] = "Authentication failed";
2220 vnc_write_u32(vs, sizeof(err));
2221 vnc_write(vs, err, sizeof(err));
2223 vnc_client_error(vs);
2226 return 0;
2229 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2231 char local[13];
2233 memcpy(local, version, 12);
2234 local[12] = 0;
2236 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2237 VNC_DEBUG("Malformed protocol version %s\n", local);
2238 vnc_client_error(vs);
2239 return 0;
2241 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2242 if (vs->major != 3 ||
2243 (vs->minor != 3 &&
2244 vs->minor != 4 &&
2245 vs->minor != 5 &&
2246 vs->minor != 7 &&
2247 vs->minor != 8)) {
2248 VNC_DEBUG("Unsupported client version\n");
2249 vnc_write_u32(vs, VNC_AUTH_INVALID);
2250 vnc_flush(vs);
2251 vnc_client_error(vs);
2252 return 0;
2254 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2255 * as equivalent to v3.3 by servers
2257 if (vs->minor == 4 || vs->minor == 5)
2258 vs->minor = 3;
2260 if (vs->minor == 3) {
2261 if (vs->vd->auth == VNC_AUTH_NONE) {
2262 VNC_DEBUG("Tell client auth none\n");
2263 vnc_write_u32(vs, vs->vd->auth);
2264 vnc_flush(vs);
2265 start_client_init(vs);
2266 } else if (vs->vd->auth == VNC_AUTH_VNC) {
2267 VNC_DEBUG("Tell client VNC auth\n");
2268 vnc_write_u32(vs, vs->vd->auth);
2269 vnc_flush(vs);
2270 start_auth_vnc(vs);
2271 } else {
2272 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2273 vnc_write_u32(vs, VNC_AUTH_INVALID);
2274 vnc_flush(vs);
2275 vnc_client_error(vs);
2277 } else {
2278 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2279 vnc_write_u8(vs, 1); /* num auth */
2280 vnc_write_u8(vs, vs->vd->auth);
2281 vnc_read_when(vs, protocol_client_auth, 1);
2282 vnc_flush(vs);
2285 return 0;
2288 static int vnc_refresh_server_surface(VncDisplay *vd)
2290 int y;
2291 uint8_t *guest_row;
2292 uint8_t *server_row;
2293 int cmp_bytes;
2294 uint32_t width_mask[VNC_DIRTY_WORDS];
2295 VncState *vs = NULL;
2296 int has_dirty = 0;
2299 * Walk through the guest dirty map.
2300 * Check and copy modified bits from guest to server surface.
2301 * Update server dirty map.
2303 vnc_set_bits(width_mask, (ds_get_width(vd->ds) / 16), VNC_DIRTY_WORDS);
2304 cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2305 guest_row = vd->guest.ds->data;
2306 server_row = vd->server->data;
2307 for (y = 0; y < vd->guest.ds->height; y++) {
2308 if (vnc_and_bits(vd->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
2309 int x;
2310 uint8_t *guest_ptr;
2311 uint8_t *server_ptr;
2313 guest_ptr = guest_row;
2314 server_ptr = server_row;
2316 for (x = 0; x < vd->guest.ds->width;
2317 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2318 if (!vnc_get_bit(vd->guest.dirty[y], (x / 16)))
2319 continue;
2320 vnc_clear_bit(vd->guest.dirty[y], (x / 16));
2321 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2322 continue;
2323 memcpy(server_ptr, guest_ptr, cmp_bytes);
2324 vs = vd->clients;
2325 while (vs != NULL) {
2326 vnc_set_bit(vs->dirty[y], (x / 16));
2327 vs = vs->next;
2329 has_dirty++;
2332 guest_row += ds_get_linesize(vd->ds);
2333 server_row += ds_get_linesize(vd->ds);
2335 return has_dirty;
2338 static void vnc_refresh(void *opaque)
2340 VncDisplay *vd = opaque;
2341 VncState *vs = NULL;
2342 int has_dirty = 0, rects = 0;
2344 vga_hw_update();
2346 has_dirty = vnc_refresh_server_surface(vd);
2348 vs = vd->clients;
2349 while (vs != NULL) {
2350 rects += vnc_update_client(vs, has_dirty);
2351 vs = vs->next;
2353 /* vd->timer could be NULL now if the last client disconnected,
2354 * in this case don't update the timer */
2355 if (vd->timer == NULL)
2356 return;
2358 if (has_dirty && rects) {
2359 vd->timer_interval /= 2;
2360 if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2361 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2362 } else {
2363 vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2364 if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2365 vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2367 qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
2370 static void vnc_init_timer(VncDisplay *vd)
2372 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2373 if (vd->timer == NULL && vd->clients != NULL) {
2374 vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
2375 vnc_refresh(vd);
2379 static void vnc_remove_timer(VncDisplay *vd)
2381 if (vd->timer != NULL && vd->clients == NULL) {
2382 qemu_del_timer(vd->timer);
2383 qemu_free_timer(vd->timer);
2384 vd->timer = NULL;
2388 static void vnc_connect(VncDisplay *vd, int csock)
2390 VncState *vs = qemu_mallocz(sizeof(VncState));
2391 vs->csock = csock;
2393 VNC_DEBUG("New client on socket %d\n", csock);
2394 dcl->idle = 0;
2395 socket_set_nonblock(vs->csock);
2396 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2398 vnc_client_cache_addr(vs);
2400 vs->vd = vd;
2401 vs->ds = vd->ds;
2402 vs->last_x = -1;
2403 vs->last_y = -1;
2405 vs->as.freq = 44100;
2406 vs->as.nchannels = 2;
2407 vs->as.fmt = AUD_FMT_S16;
2408 vs->as.endianness = 0;
2410 vs->next = vd->clients;
2411 vd->clients = vs;
2413 vga_hw_update();
2415 vnc_write(vs, "RFB 003.008\n", 12);
2416 vnc_flush(vs);
2417 vnc_read_when(vs, protocol_version, 12);
2418 reset_keys(vs);
2420 vnc_init_timer(vd);
2422 /* vs might be free()ed here */
2425 static void vnc_listen_read(void *opaque)
2427 VncDisplay *vs = opaque;
2428 struct sockaddr_in addr;
2429 socklen_t addrlen = sizeof(addr);
2431 /* Catch-up */
2432 vga_hw_update();
2434 int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2435 if (csock != -1) {
2436 vnc_connect(vs, csock);
2440 void vnc_display_init(DisplayState *ds)
2442 VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2444 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2446 ds->opaque = vs;
2447 dcl->idle = 1;
2448 vnc_display = vs;
2450 vs->lsock = -1;
2452 vs->ds = ds;
2454 if (keyboard_layout)
2455 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2456 else
2457 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2459 if (!vs->kbd_layout)
2460 exit(1);
2462 dcl->dpy_copy = vnc_dpy_copy;
2463 dcl->dpy_update = vnc_dpy_update;
2464 dcl->dpy_resize = vnc_dpy_resize;
2465 dcl->dpy_setdata = vnc_dpy_setdata;
2466 register_displaychangelistener(ds, dcl);
2470 void vnc_display_close(DisplayState *ds)
2472 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2474 if (!vs)
2475 return;
2476 if (vs->display) {
2477 qemu_free(vs->display);
2478 vs->display = NULL;
2480 if (vs->lsock != -1) {
2481 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2482 close(vs->lsock);
2483 vs->lsock = -1;
2485 vs->auth = VNC_AUTH_INVALID;
2486 #ifdef CONFIG_VNC_TLS
2487 vs->subauth = VNC_AUTH_INVALID;
2488 vs->tls.x509verify = 0;
2489 #endif
2492 int vnc_display_password(DisplayState *ds, const char *password)
2494 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2496 if (!vs) {
2497 return -1;
2500 if (vs->password) {
2501 qemu_free(vs->password);
2502 vs->password = NULL;
2504 if (password && password[0]) {
2505 if (!(vs->password = qemu_strdup(password)))
2506 return -1;
2507 if (vs->auth == VNC_AUTH_NONE) {
2508 vs->auth = VNC_AUTH_VNC;
2510 } else {
2511 vs->auth = VNC_AUTH_NONE;
2514 return 0;
2517 char *vnc_display_local_addr(DisplayState *ds)
2519 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2521 return vnc_socket_local_addr("%s:%s", vs->lsock);
2524 int vnc_display_open(DisplayState *ds, const char *display)
2526 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2527 const char *options;
2528 int password = 0;
2529 int reverse = 0;
2530 int to_port = 0;
2531 #ifdef CONFIG_VNC_TLS
2532 int tls = 0, x509 = 0;
2533 #endif
2534 #ifdef CONFIG_VNC_SASL
2535 int sasl = 0;
2536 int saslErr;
2537 #endif
2538 int acl = 0;
2540 if (!vnc_display)
2541 return -1;
2542 vnc_display_close(ds);
2543 if (strcmp(display, "none") == 0)
2544 return 0;
2546 if (!(vs->display = strdup(display)))
2547 return -1;
2549 options = display;
2550 while ((options = strchr(options, ','))) {
2551 options++;
2552 if (strncmp(options, "password", 8) == 0) {
2553 password = 1; /* Require password auth */
2554 } else if (strncmp(options, "reverse", 7) == 0) {
2555 reverse = 1;
2556 } else if (strncmp(options, "to=", 3) == 0) {
2557 to_port = atoi(options+3) + 5900;
2558 #ifdef CONFIG_VNC_SASL
2559 } else if (strncmp(options, "sasl", 4) == 0) {
2560 sasl = 1; /* Require SASL auth */
2561 #endif
2562 #ifdef CONFIG_VNC_TLS
2563 } else if (strncmp(options, "tls", 3) == 0) {
2564 tls = 1; /* Require TLS */
2565 } else if (strncmp(options, "x509", 4) == 0) {
2566 char *start, *end;
2567 x509 = 1; /* Require x509 certificates */
2568 if (strncmp(options, "x509verify", 10) == 0)
2569 vs->tls.x509verify = 1; /* ...and verify client certs */
2571 /* Now check for 'x509=/some/path' postfix
2572 * and use that to setup x509 certificate/key paths */
2573 start = strchr(options, '=');
2574 end = strchr(options, ',');
2575 if (start && (!end || (start < end))) {
2576 int len = end ? end-(start+1) : strlen(start+1);
2577 char *path = qemu_strndup(start + 1, len);
2579 VNC_DEBUG("Trying certificate path '%s'\n", path);
2580 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2581 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2582 qemu_free(path);
2583 qemu_free(vs->display);
2584 vs->display = NULL;
2585 return -1;
2587 qemu_free(path);
2588 } else {
2589 fprintf(stderr, "No certificate path provided\n");
2590 qemu_free(vs->display);
2591 vs->display = NULL;
2592 return -1;
2594 #endif
2595 } else if (strncmp(options, "acl", 3) == 0) {
2596 acl = 1;
2600 #ifdef CONFIG_VNC_TLS
2601 if (acl && x509 && vs->tls.x509verify) {
2602 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2603 fprintf(stderr, "Failed to create x509 dname ACL\n");
2604 exit(1);
2607 #endif
2608 #ifdef CONFIG_VNC_SASL
2609 if (acl && sasl) {
2610 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2611 fprintf(stderr, "Failed to create username ACL\n");
2612 exit(1);
2615 #endif
2618 * Combinations we support here:
2620 * - no-auth (clear text, no auth)
2621 * - password (clear text, weak auth)
2622 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
2623 * - tls (encrypt, weak anonymous creds, no auth)
2624 * - tls + password (encrypt, weak anonymous creds, weak auth)
2625 * - tls + sasl (encrypt, weak anonymous creds, good auth)
2626 * - tls + x509 (encrypt, good x509 creds, no auth)
2627 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
2628 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
2630 * NB1. TLS is a stackable auth scheme.
2631 * NB2. the x509 schemes have option to validate a client cert dname
2633 if (password) {
2634 #ifdef CONFIG_VNC_TLS
2635 if (tls) {
2636 vs->auth = VNC_AUTH_VENCRYPT;
2637 if (x509) {
2638 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2639 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2640 } else {
2641 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2642 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2644 } else {
2645 #endif /* CONFIG_VNC_TLS */
2646 VNC_DEBUG("Initializing VNC server with password auth\n");
2647 vs->auth = VNC_AUTH_VNC;
2648 #ifdef CONFIG_VNC_TLS
2649 vs->subauth = VNC_AUTH_INVALID;
2651 #endif /* CONFIG_VNC_TLS */
2652 #ifdef CONFIG_VNC_SASL
2653 } else if (sasl) {
2654 #ifdef CONFIG_VNC_TLS
2655 if (tls) {
2656 vs->auth = VNC_AUTH_VENCRYPT;
2657 if (x509) {
2658 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2659 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2660 } else {
2661 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2662 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2664 } else {
2665 #endif /* CONFIG_VNC_TLS */
2666 VNC_DEBUG("Initializing VNC server with SASL auth\n");
2667 vs->auth = VNC_AUTH_SASL;
2668 #ifdef CONFIG_VNC_TLS
2669 vs->subauth = VNC_AUTH_INVALID;
2671 #endif /* CONFIG_VNC_TLS */
2672 #endif /* CONFIG_VNC_SASL */
2673 } else {
2674 #ifdef CONFIG_VNC_TLS
2675 if (tls) {
2676 vs->auth = VNC_AUTH_VENCRYPT;
2677 if (x509) {
2678 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2679 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2680 } else {
2681 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2682 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2684 } else {
2685 #endif
2686 VNC_DEBUG("Initializing VNC server with no auth\n");
2687 vs->auth = VNC_AUTH_NONE;
2688 #ifdef CONFIG_VNC_TLS
2689 vs->subauth = VNC_AUTH_INVALID;
2691 #endif
2694 #ifdef CONFIG_VNC_SASL
2695 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2696 fprintf(stderr, "Failed to initialize SASL auth %s",
2697 sasl_errstring(saslErr, NULL, NULL));
2698 free(vs->display);
2699 vs->display = NULL;
2700 return -1;
2702 #endif
2704 if (reverse) {
2705 /* connect to viewer */
2706 if (strncmp(display, "unix:", 5) == 0)
2707 vs->lsock = unix_connect(display+5);
2708 else
2709 vs->lsock = inet_connect(display, SOCK_STREAM);
2710 if (-1 == vs->lsock) {
2711 free(vs->display);
2712 vs->display = NULL;
2713 return -1;
2714 } else {
2715 int csock = vs->lsock;
2716 vs->lsock = -1;
2717 vnc_connect(vs, csock);
2719 return 0;
2721 } else {
2722 /* listen for connects */
2723 char *dpy;
2724 dpy = qemu_malloc(256);
2725 if (strncmp(display, "unix:", 5) == 0) {
2726 pstrcpy(dpy, 256, "unix:");
2727 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2728 } else {
2729 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2731 if (-1 == vs->lsock) {
2732 free(dpy);
2733 return -1;
2734 } else {
2735 free(vs->display);
2736 vs->display = dpy;
2739 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);