VNC: Rename client's 'username' key
[qemu.git] / vnc.c
blobe35cc3643267651f395fa26630d111d570708ab3
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 int put_addr_qdict(QDict *qdict, struct sockaddr_storage *sa,
104 socklen_t salen)
106 char host[NI_MAXHOST];
107 char serv[NI_MAXSERV];
108 int err;
110 if ((err = getnameinfo((struct sockaddr *)sa, salen,
111 host, sizeof(host),
112 serv, sizeof(serv),
113 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
114 VNC_DEBUG("Cannot resolve address %d: %s\n",
115 err, gai_strerror(err));
116 return -1;
119 qdict_put(qdict, "host", qstring_from_str(host));
120 qdict_put(qdict, "service", qstring_from_str(serv));
122 return 0;
125 static int vnc_server_addr_put(QDict *qdict, int fd)
127 struct sockaddr_storage sa;
128 socklen_t salen;
130 salen = sizeof(sa);
131 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
132 return -1;
135 return put_addr_qdict(qdict, &sa, salen);
138 static int vnc_qdict_remote_addr(QDict *qdict, int fd)
140 struct sockaddr_storage sa;
141 socklen_t salen;
143 salen = sizeof(sa);
144 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
145 return -1;
148 return put_addr_qdict(qdict, &sa, salen);
151 static const char *vnc_auth_name(VncDisplay *vd) {
152 switch (vd->auth) {
153 case VNC_AUTH_INVALID:
154 return "invalid";
155 case VNC_AUTH_NONE:
156 return "none";
157 case VNC_AUTH_VNC:
158 return "vnc";
159 case VNC_AUTH_RA2:
160 return "ra2";
161 case VNC_AUTH_RA2NE:
162 return "ra2ne";
163 case VNC_AUTH_TIGHT:
164 return "tight";
165 case VNC_AUTH_ULTRA:
166 return "ultra";
167 case VNC_AUTH_TLS:
168 return "tls";
169 case VNC_AUTH_VENCRYPT:
170 #ifdef CONFIG_VNC_TLS
171 switch (vd->subauth) {
172 case VNC_AUTH_VENCRYPT_PLAIN:
173 return "vencrypt+plain";
174 case VNC_AUTH_VENCRYPT_TLSNONE:
175 return "vencrypt+tls+none";
176 case VNC_AUTH_VENCRYPT_TLSVNC:
177 return "vencrypt+tls+vnc";
178 case VNC_AUTH_VENCRYPT_TLSPLAIN:
179 return "vencrypt+tls+plain";
180 case VNC_AUTH_VENCRYPT_X509NONE:
181 return "vencrypt+x509+none";
182 case VNC_AUTH_VENCRYPT_X509VNC:
183 return "vencrypt+x509+vnc";
184 case VNC_AUTH_VENCRYPT_X509PLAIN:
185 return "vencrypt+x509+plain";
186 case VNC_AUTH_VENCRYPT_TLSSASL:
187 return "vencrypt+tls+sasl";
188 case VNC_AUTH_VENCRYPT_X509SASL:
189 return "vencrypt+x509+sasl";
190 default:
191 return "vencrypt";
193 #else
194 return "vencrypt";
195 #endif
196 case VNC_AUTH_SASL:
197 return "sasl";
199 return "unknown";
202 static int vnc_server_info_put(QDict *qdict)
204 if (vnc_server_addr_put(qdict, vnc_display->lsock) < 0) {
205 return -1;
208 qdict_put(qdict, "auth", qstring_from_str(vnc_auth_name(vnc_display)));
209 return 0;
212 static QDict *do_info_vnc_client(Monitor *mon, VncState *client)
214 QDict *qdict;
216 qdict = qdict_new();
217 if (vnc_qdict_remote_addr(qdict, client->csock) < 0) {
218 QDECREF(qdict);
219 return NULL;
222 #ifdef CONFIG_VNC_TLS
223 if (client->tls.session &&
224 client->tls.dname) {
225 qdict_put(qdict, "x509_dname", qstring_from_str(client->tls.dname));
227 #endif
228 #ifdef CONFIG_VNC_SASL
229 if (client->sasl.conn &&
230 client->sasl.username) {
231 qdict_put(qdict, "sasl_username",
232 qstring_from_str(client->sasl.username));
234 #endif
236 return qdict;
239 static void info_vnc_iter(QObject *obj, void *opaque)
241 QDict *client;
242 Monitor *mon = opaque;
244 client = qobject_to_qdict(obj);
245 monitor_printf(mon, "Client:\n");
246 monitor_printf(mon, " address: %s:%s\n",
247 qdict_get_str(client, "host"),
248 qdict_get_str(client, "service"));
250 #ifdef CONFIG_VNC_TLS
251 monitor_printf(mon, " x509_dname: %s\n",
252 qdict_haskey(client, "x509_dname") ?
253 qdict_get_str(client, "x509_dname") : "none");
254 #endif
255 #ifdef CONFIG_VNC_SASL
256 monitor_printf(mon, " username: %s\n",
257 qdict_haskey(client, "sasl_username") ?
258 qdict_get_str(client, "sasl_username") : "none");
259 #endif
262 void do_info_vnc_print(Monitor *mon, const QObject *data)
264 QDict *server;
265 QList *clients;
267 server = qobject_to_qdict(data);
268 if (qdict_get_bool(server, "enabled") == 0) {
269 monitor_printf(mon, "Server: disabled\n");
270 return;
273 monitor_printf(mon, "Server:\n");
274 monitor_printf(mon, " address: %s:%s\n",
275 qdict_get_str(server, "host"),
276 qdict_get_str(server, "service"));
277 monitor_printf(mon, " auth: %s\n", qdict_get_str(server, "auth"));
279 clients = qdict_get_qlist(server, "clients");
280 if (qlist_empty(clients)) {
281 monitor_printf(mon, "Client: none\n");
282 } else {
283 qlist_iter(clients, info_vnc_iter, mon);
288 * do_info_vnc(): Show VNC server information
290 * Return a QDict with server information. Connected clients are returned
291 * as a QList of QDicts.
293 * The main QDict contains the following:
295 * - "enabled": true or false
296 * - "host": server's IP address
297 * - "service": server's port number
298 * - "auth": authentication method
299 * - "clients": a QList of all connected clients
301 * Clients are described by a QDict, with the following information:
303 * - "host": client's IP address
304 * - "service": client's port number
305 * - "x509_dname": TLS dname (optional)
306 * - "sasl_username": SASL username (optional)
308 * Example:
310 * { "enabled": true, "host": "0.0.0.0", "service": "50402", "auth": "vnc",
311 * "clients": [ { "host": "127.0.0.1", "service": "50401" } ] }
313 void do_info_vnc(Monitor *mon, QObject **ret_data)
315 if (vnc_display == NULL || vnc_display->display == NULL) {
316 *ret_data = qobject_from_jsonf("{ 'enabled': false }");
317 } else {
318 QDict *qdict;
319 QList *clist;
321 clist = qlist_new();
322 if (vnc_display->clients) {
323 VncState *client = vnc_display->clients;
324 while (client) {
325 qdict = do_info_vnc_client(mon, client);
326 if (qdict)
327 qlist_append(clist, qdict);
328 client = client->next;
332 *ret_data = qobject_from_jsonf("{ 'enabled': true, 'clients': %p }",
333 QOBJECT(clist));
334 assert(*ret_data != NULL);
336 if (vnc_server_info_put(qobject_to_qdict(*ret_data)) < 0) {
337 qobject_decref(*ret_data);
338 *ret_data = NULL;
343 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
344 return (vs->features & (1 << feature));
347 /* TODO
348 1) Get the queue working for IO.
349 2) there is some weirdness when using the -S option (the screen is grey
350 and not totally invalidated
351 3) resolutions > 1024
354 static int vnc_update_client(VncState *vs, int has_dirty);
355 static void vnc_disconnect_start(VncState *vs);
356 static void vnc_disconnect_finish(VncState *vs);
357 static void vnc_init_timer(VncDisplay *vd);
358 static void vnc_remove_timer(VncDisplay *vd);
360 static void vnc_colordepth(VncState *vs);
361 static void framebuffer_update_request(VncState *vs, int incremental,
362 int x_position, int y_position,
363 int w, int h);
364 static void vnc_refresh(void *opaque);
365 static int vnc_refresh_server_surface(VncDisplay *vd);
367 static inline void vnc_set_bit(uint32_t *d, int k)
369 d[k >> 5] |= 1 << (k & 0x1f);
372 static inline void vnc_clear_bit(uint32_t *d, int k)
374 d[k >> 5] &= ~(1 << (k & 0x1f));
377 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
379 int j;
381 j = 0;
382 while (n >= 32) {
383 d[j++] = -1;
384 n -= 32;
386 if (n > 0)
387 d[j++] = (1 << n) - 1;
388 while (j < nb_words)
389 d[j++] = 0;
392 static inline int vnc_get_bit(const uint32_t *d, int k)
394 return (d[k >> 5] >> (k & 0x1f)) & 1;
397 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
398 int nb_words)
400 int i;
401 for(i = 0; i < nb_words; i++) {
402 if ((d1[i] & d2[i]) != 0)
403 return 1;
405 return 0;
408 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
410 int i;
411 VncDisplay *vd = ds->opaque;
412 struct VncSurface *s = &vd->guest;
414 h += y;
416 /* round x down to ensure the loop only spans one 16-pixel block per,
417 iteration. otherwise, if (x % 16) != 0, the last iteration may span
418 two 16-pixel blocks but we only mark the first as dirty
420 w += (x % 16);
421 x -= (x % 16);
423 x = MIN(x, s->ds->width);
424 y = MIN(y, s->ds->height);
425 w = MIN(x + w, s->ds->width) - x;
426 h = MIN(h, s->ds->height);
428 for (; y < h; y++)
429 for (i = 0; i < w; i += 16)
430 vnc_set_bit(s->dirty[y], (x + i) / 16);
433 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
434 int32_t encoding)
436 vnc_write_u16(vs, x);
437 vnc_write_u16(vs, y);
438 vnc_write_u16(vs, w);
439 vnc_write_u16(vs, h);
441 vnc_write_s32(vs, encoding);
444 void buffer_reserve(Buffer *buffer, size_t len)
446 if ((buffer->capacity - buffer->offset) < len) {
447 buffer->capacity += (len + 1024);
448 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
449 if (buffer->buffer == NULL) {
450 fprintf(stderr, "vnc: out of memory\n");
451 exit(1);
456 int buffer_empty(Buffer *buffer)
458 return buffer->offset == 0;
461 uint8_t *buffer_end(Buffer *buffer)
463 return buffer->buffer + buffer->offset;
466 void buffer_reset(Buffer *buffer)
468 buffer->offset = 0;
471 void buffer_append(Buffer *buffer, const void *data, size_t len)
473 memcpy(buffer->buffer + buffer->offset, data, len);
474 buffer->offset += len;
477 static void vnc_dpy_resize(DisplayState *ds)
479 int size_changed;
480 VncDisplay *vd = ds->opaque;
481 VncState *vs = vd->clients;
483 /* server surface */
484 if (!vd->server)
485 vd->server = qemu_mallocz(sizeof(*vd->server));
486 if (vd->server->data)
487 qemu_free(vd->server->data);
488 *(vd->server) = *(ds->surface);
489 vd->server->data = qemu_mallocz(vd->server->linesize *
490 vd->server->height);
492 /* guest surface */
493 if (!vd->guest.ds)
494 vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
495 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
496 console_color_init(ds);
497 size_changed = ds_get_width(ds) != vd->guest.ds->width ||
498 ds_get_height(ds) != vd->guest.ds->height;
499 *(vd->guest.ds) = *(ds->surface);
500 memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
502 while (vs != NULL) {
503 vnc_colordepth(vs);
504 if (size_changed) {
505 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
506 vnc_write_u8(vs, 0); /* msg id */
507 vnc_write_u8(vs, 0);
508 vnc_write_u16(vs, 1); /* number of rects */
509 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
510 VNC_ENCODING_DESKTOPRESIZE);
511 vnc_flush(vs);
514 memset(vs->dirty, 0xFF, sizeof(vs->dirty));
515 vs = vs->next;
519 /* fastest code */
520 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
522 vnc_write(vs, pixels, size);
525 /* slowest but generic code. */
526 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
528 uint8_t r, g, b;
529 VncDisplay *vd = vs->vd;
531 r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>
532 vd->server->pf.rbits);
533 g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>
534 vd->server->pf.gbits);
535 b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>
536 vd->server->pf.bbits);
537 v = (r << vs->clientds.pf.rshift) |
538 (g << vs->clientds.pf.gshift) |
539 (b << vs->clientds.pf.bshift);
540 switch(vs->clientds.pf.bytes_per_pixel) {
541 case 1:
542 buf[0] = v;
543 break;
544 case 2:
545 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
546 buf[0] = v >> 8;
547 buf[1] = v;
548 } else {
549 buf[1] = v >> 8;
550 buf[0] = v;
552 break;
553 default:
554 case 4:
555 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
556 buf[0] = v >> 24;
557 buf[1] = v >> 16;
558 buf[2] = v >> 8;
559 buf[3] = v;
560 } else {
561 buf[3] = v >> 24;
562 buf[2] = v >> 16;
563 buf[1] = v >> 8;
564 buf[0] = v;
566 break;
570 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
572 uint8_t buf[4];
573 VncDisplay *vd = vs->vd;
575 if (vd->server->pf.bytes_per_pixel == 4) {
576 uint32_t *pixels = pixels1;
577 int n, i;
578 n = size >> 2;
579 for(i = 0; i < n; i++) {
580 vnc_convert_pixel(vs, buf, pixels[i]);
581 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
583 } else if (vd->server->pf.bytes_per_pixel == 2) {
584 uint16_t *pixels = pixels1;
585 int n, i;
586 n = size >> 1;
587 for(i = 0; i < n; i++) {
588 vnc_convert_pixel(vs, buf, pixels[i]);
589 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
591 } else if (vd->server->pf.bytes_per_pixel == 1) {
592 uint8_t *pixels = pixels1;
593 int n, i;
594 n = size;
595 for(i = 0; i < n; i++) {
596 vnc_convert_pixel(vs, buf, pixels[i]);
597 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
599 } else {
600 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
604 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
606 int i;
607 uint8_t *row;
608 VncDisplay *vd = vs->vd;
610 row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
611 for (i = 0; i < h; i++) {
612 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
613 row += ds_get_linesize(vs->ds);
617 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
619 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
620 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
623 #define BPP 8
624 #include "vnchextile.h"
625 #undef BPP
627 #define BPP 16
628 #include "vnchextile.h"
629 #undef BPP
631 #define BPP 32
632 #include "vnchextile.h"
633 #undef BPP
635 #define GENERIC
636 #define BPP 8
637 #include "vnchextile.h"
638 #undef BPP
639 #undef GENERIC
641 #define GENERIC
642 #define BPP 16
643 #include "vnchextile.h"
644 #undef BPP
645 #undef GENERIC
647 #define GENERIC
648 #define BPP 32
649 #include "vnchextile.h"
650 #undef BPP
651 #undef GENERIC
653 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
655 int i, j;
656 int has_fg, has_bg;
657 uint8_t *last_fg, *last_bg;
658 VncDisplay *vd = vs->vd;
660 last_fg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);
661 last_bg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);
662 has_fg = has_bg = 0;
663 for (j = y; j < (y + h); j += 16) {
664 for (i = x; i < (x + w); i += 16) {
665 vs->send_hextile_tile(vs, i, j,
666 MIN(16, x + w - i), MIN(16, y + h - j),
667 last_bg, last_fg, &has_bg, &has_fg);
670 free(last_fg);
671 free(last_bg);
675 #define ZALLOC_ALIGNMENT 16
677 static void *zalloc(void *x, unsigned items, unsigned size)
679 void *p;
681 size *= items;
682 size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
684 p = qemu_mallocz(size);
686 return (p);
689 static void zfree(void *x, void *addr)
691 qemu_free(addr);
694 static void vnc_zlib_init(VncState *vs)
696 int i;
697 for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
698 vs->zlib_stream[i].opaque = NULL;
701 static void vnc_zlib_start(VncState *vs)
703 buffer_reset(&vs->zlib);
705 // make the output buffer be the zlib buffer, so we can compress it later
706 vs->zlib_tmp = vs->output;
707 vs->output = vs->zlib;
710 static int vnc_zlib_stop(VncState *vs, int stream_id)
712 z_streamp zstream = &vs->zlib_stream[stream_id];
713 int previous_out;
715 // switch back to normal output/zlib buffers
716 vs->zlib = vs->output;
717 vs->output = vs->zlib_tmp;
719 // compress the zlib buffer
721 // initialize the stream
722 // XXX need one stream per session
723 if (zstream->opaque != vs) {
724 int err;
726 VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
727 VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
728 zstream->zalloc = zalloc;
729 zstream->zfree = zfree;
731 err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
732 MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
734 if (err != Z_OK) {
735 fprintf(stderr, "VNC: error initializing zlib\n");
736 return -1;
739 zstream->opaque = vs;
742 // XXX what to do if tight_compression changed in between?
744 // reserve memory in output buffer
745 buffer_reserve(&vs->output, vs->zlib.offset + 64);
747 // set pointers
748 zstream->next_in = vs->zlib.buffer;
749 zstream->avail_in = vs->zlib.offset;
750 zstream->next_out = vs->output.buffer + vs->output.offset;
751 zstream->avail_out = vs->output.capacity - vs->output.offset;
752 zstream->data_type = Z_BINARY;
753 previous_out = zstream->total_out;
755 // start encoding
756 if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
757 fprintf(stderr, "VNC: error during zlib compression\n");
758 return -1;
761 vs->output.offset = vs->output.capacity - zstream->avail_out;
762 return zstream->total_out - previous_out;
765 static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
767 int old_offset, new_offset, bytes_written;
769 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
771 // remember where we put in the follow-up size
772 old_offset = vs->output.offset;
773 vnc_write_s32(vs, 0);
775 // compress the stream
776 vnc_zlib_start(vs);
777 send_framebuffer_update_raw(vs, x, y, w, h);
778 bytes_written = vnc_zlib_stop(vs, 0);
780 if (bytes_written == -1)
781 return;
783 // hack in the size
784 new_offset = vs->output.offset;
785 vs->output.offset = old_offset;
786 vnc_write_u32(vs, bytes_written);
787 vs->output.offset = new_offset;
790 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
792 switch(vs->vnc_encoding) {
793 case VNC_ENCODING_ZLIB:
794 send_framebuffer_update_zlib(vs, x, y, w, h);
795 break;
796 case VNC_ENCODING_HEXTILE:
797 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
798 send_framebuffer_update_hextile(vs, x, y, w, h);
799 break;
800 default:
801 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
802 send_framebuffer_update_raw(vs, x, y, w, h);
803 break;
807 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
809 /* send bitblit op to the vnc client */
810 vnc_write_u8(vs, 0); /* msg id */
811 vnc_write_u8(vs, 0);
812 vnc_write_u16(vs, 1); /* number of rects */
813 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
814 vnc_write_u16(vs, src_x);
815 vnc_write_u16(vs, src_y);
816 vnc_flush(vs);
819 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
821 VncDisplay *vd = ds->opaque;
822 VncState *vs, *vn;
823 uint8_t *src_row;
824 uint8_t *dst_row;
825 int i,x,y,pitch,depth,inc,w_lim,s;
826 int cmp_bytes;
828 vnc_refresh_server_surface(vd);
829 for (vs = vd->clients; vs != NULL; vs = vn) {
830 vn = vs->next;
831 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
832 vs->force_update = 1;
833 vnc_update_client(vs, 1);
834 /* vs might be free()ed here */
838 /* do bitblit op on the local surface too */
839 pitch = ds_get_linesize(vd->ds);
840 depth = ds_get_bytes_per_pixel(vd->ds);
841 src_row = vd->server->data + pitch * src_y + depth * src_x;
842 dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
843 y = dst_y;
844 inc = 1;
845 if (dst_y > src_y) {
846 /* copy backwards */
847 src_row += pitch * (h-1);
848 dst_row += pitch * (h-1);
849 pitch = -pitch;
850 y = dst_y + h - 1;
851 inc = -1;
853 w_lim = w - (16 - (dst_x % 16));
854 if (w_lim < 0)
855 w_lim = w;
856 else
857 w_lim = w - (w_lim % 16);
858 for (i = 0; i < h; i++) {
859 for (x = 0; x <= w_lim;
860 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
861 if (x == w_lim) {
862 if ((s = w - w_lim) == 0)
863 break;
864 } else if (!x) {
865 s = (16 - (dst_x % 16));
866 s = MIN(s, w_lim);
867 } else {
868 s = 16;
870 cmp_bytes = s * depth;
871 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
872 continue;
873 memmove(dst_row, src_row, cmp_bytes);
874 vs = vd->clients;
875 while (vs != NULL) {
876 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
877 vnc_set_bit(vs->dirty[y], ((x + dst_x) / 16));
878 vs = vs->next;
881 src_row += pitch - w * depth;
882 dst_row += pitch - w * depth;
883 y += inc;
886 for (vs = vd->clients; vs != NULL; vs = vs->next) {
887 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
888 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
892 static int find_and_clear_dirty_height(struct VncState *vs,
893 int y, int last_x, int x)
895 int h;
896 VncDisplay *vd = vs->vd;
898 for (h = 1; h < (vd->server->height - y); h++) {
899 int tmp_x;
900 if (!vnc_get_bit(vs->dirty[y + h], last_x))
901 break;
902 for (tmp_x = last_x; tmp_x < x; tmp_x++)
903 vnc_clear_bit(vs->dirty[y + h], tmp_x);
906 return h;
909 static int vnc_update_client(VncState *vs, int has_dirty)
911 if (vs->need_update && vs->csock != -1) {
912 VncDisplay *vd = vs->vd;
913 int y;
914 int n_rectangles;
915 int saved_offset;
917 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
918 /* kernel send buffers are full -> drop frames to throttle */
919 return 0;
921 if (!has_dirty && !vs->audio_cap && !vs->force_update)
922 return 0;
925 * Send screen updates to the vnc client using the server
926 * surface and server dirty map. guest surface updates
927 * happening in parallel don't disturb us, the next pass will
928 * send them to the client.
930 n_rectangles = 0;
931 vnc_write_u8(vs, 0); /* msg id */
932 vnc_write_u8(vs, 0);
933 saved_offset = vs->output.offset;
934 vnc_write_u16(vs, 0);
936 for (y = 0; y < vd->server->height; y++) {
937 int x;
938 int last_x = -1;
939 for (x = 0; x < vd->server->width / 16; x++) {
940 if (vnc_get_bit(vs->dirty[y], x)) {
941 if (last_x == -1) {
942 last_x = x;
944 vnc_clear_bit(vs->dirty[y], x);
945 } else {
946 if (last_x != -1) {
947 int h = find_and_clear_dirty_height(vs, y, last_x, x);
948 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
949 n_rectangles++;
951 last_x = -1;
954 if (last_x != -1) {
955 int h = find_and_clear_dirty_height(vs, y, last_x, x);
956 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
957 n_rectangles++;
960 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
961 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
962 vnc_flush(vs);
963 vs->force_update = 0;
964 return n_rectangles;
967 if (vs->csock == -1)
968 vnc_disconnect_finish(vs);
970 return 0;
973 /* audio */
974 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
976 VncState *vs = opaque;
978 switch (cmd) {
979 case AUD_CNOTIFY_DISABLE:
980 vnc_write_u8(vs, 255);
981 vnc_write_u8(vs, 1);
982 vnc_write_u16(vs, 0);
983 vnc_flush(vs);
984 break;
986 case AUD_CNOTIFY_ENABLE:
987 vnc_write_u8(vs, 255);
988 vnc_write_u8(vs, 1);
989 vnc_write_u16(vs, 1);
990 vnc_flush(vs);
991 break;
995 static void audio_capture_destroy(void *opaque)
999 static void audio_capture(void *opaque, void *buf, int size)
1001 VncState *vs = opaque;
1003 vnc_write_u8(vs, 255);
1004 vnc_write_u8(vs, 1);
1005 vnc_write_u16(vs, 2);
1006 vnc_write_u32(vs, size);
1007 vnc_write(vs, buf, size);
1008 vnc_flush(vs);
1011 static void audio_add(VncState *vs)
1013 Monitor *mon = cur_mon;
1014 struct audio_capture_ops ops;
1016 if (vs->audio_cap) {
1017 monitor_printf(mon, "audio already running\n");
1018 return;
1021 ops.notify = audio_capture_notify;
1022 ops.destroy = audio_capture_destroy;
1023 ops.capture = audio_capture;
1025 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1026 if (!vs->audio_cap) {
1027 monitor_printf(mon, "Failed to add audio capture\n");
1031 static void audio_del(VncState *vs)
1033 if (vs->audio_cap) {
1034 AUD_del_capture(vs->audio_cap, vs);
1035 vs->audio_cap = NULL;
1039 static void vnc_disconnect_start(VncState *vs)
1041 if (vs->csock == -1)
1042 return;
1043 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1044 closesocket(vs->csock);
1045 vs->csock = -1;
1048 static void vnc_disconnect_finish(VncState *vs)
1050 if (vs->input.buffer) {
1051 qemu_free(vs->input.buffer);
1052 vs->input.buffer = NULL;
1054 if (vs->output.buffer) {
1055 qemu_free(vs->output.buffer);
1056 vs->output.buffer = NULL;
1058 #ifdef CONFIG_VNC_TLS
1059 vnc_tls_client_cleanup(vs);
1060 #endif /* CONFIG_VNC_TLS */
1061 #ifdef CONFIG_VNC_SASL
1062 vnc_sasl_client_cleanup(vs);
1063 #endif /* CONFIG_VNC_SASL */
1064 audio_del(vs);
1066 VncState *p, *parent = NULL;
1067 for (p = vs->vd->clients; p != NULL; p = p->next) {
1068 if (p == vs) {
1069 if (parent)
1070 parent->next = p->next;
1071 else
1072 vs->vd->clients = p->next;
1073 break;
1075 parent = p;
1077 if (!vs->vd->clients)
1078 dcl->idle = 1;
1080 vnc_remove_timer(vs->vd);
1081 qemu_free(vs);
1084 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1086 if (ret == 0 || ret == -1) {
1087 if (ret == -1) {
1088 switch (last_errno) {
1089 case EINTR:
1090 case EAGAIN:
1091 #ifdef _WIN32
1092 case WSAEWOULDBLOCK:
1093 #endif
1094 return 0;
1095 default:
1096 break;
1100 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1101 ret, ret < 0 ? last_errno : 0);
1102 vnc_disconnect_start(vs);
1104 return 0;
1106 return ret;
1110 void vnc_client_error(VncState *vs)
1112 VNC_DEBUG("Closing down client sock: protocol error\n");
1113 vnc_disconnect_start(vs);
1118 * Called to write a chunk of data to the client socket. The data may
1119 * be the raw data, or may have already been encoded by SASL.
1120 * The data will be written either straight onto the socket, or
1121 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1123 * NB, it is theoretically possible to have 2 layers of encryption,
1124 * both SASL, and this TLS layer. It is highly unlikely in practice
1125 * though, since SASL encryption will typically be a no-op if TLS
1126 * is active
1128 * Returns the number of bytes written, which may be less than
1129 * the requested 'datalen' if the socket would block. Returns
1130 * -1 on error, and disconnects the client socket.
1132 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1134 long ret;
1135 #ifdef CONFIG_VNC_TLS
1136 if (vs->tls.session) {
1137 ret = gnutls_write(vs->tls.session, data, datalen);
1138 if (ret < 0) {
1139 if (ret == GNUTLS_E_AGAIN)
1140 errno = EAGAIN;
1141 else
1142 errno = EIO;
1143 ret = -1;
1145 } else
1146 #endif /* CONFIG_VNC_TLS */
1147 ret = send(vs->csock, (const void *)data, datalen, 0);
1148 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1149 return vnc_client_io_error(vs, ret, socket_error());
1154 * Called to write buffered data to the client socket, when not
1155 * using any SASL SSF encryption layers. Will write as much data
1156 * as possible without blocking. If all buffered data is written,
1157 * will switch the FD poll() handler back to read monitoring.
1159 * Returns the number of bytes written, which may be less than
1160 * the buffered output data if the socket would block. Returns
1161 * -1 on error, and disconnects the client socket.
1163 static long vnc_client_write_plain(VncState *vs)
1165 long ret;
1167 #ifdef CONFIG_VNC_SASL
1168 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1169 vs->output.buffer, vs->output.capacity, vs->output.offset,
1170 vs->sasl.waitWriteSSF);
1172 if (vs->sasl.conn &&
1173 vs->sasl.runSSF &&
1174 vs->sasl.waitWriteSSF) {
1175 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1176 if (ret)
1177 vs->sasl.waitWriteSSF -= ret;
1178 } else
1179 #endif /* CONFIG_VNC_SASL */
1180 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1181 if (!ret)
1182 return 0;
1184 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1185 vs->output.offset -= ret;
1187 if (vs->output.offset == 0) {
1188 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1191 return ret;
1196 * First function called whenever there is data to be written to
1197 * the client socket. Will delegate actual work according to whether
1198 * SASL SSF layers are enabled (thus requiring encryption calls)
1200 void vnc_client_write(void *opaque)
1202 long ret;
1203 VncState *vs = opaque;
1205 #ifdef CONFIG_VNC_SASL
1206 if (vs->sasl.conn &&
1207 vs->sasl.runSSF &&
1208 !vs->sasl.waitWriteSSF)
1209 ret = vnc_client_write_sasl(vs);
1210 else
1211 #endif /* CONFIG_VNC_SASL */
1212 ret = vnc_client_write_plain(vs);
1215 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1217 vs->read_handler = func;
1218 vs->read_handler_expect = expecting;
1223 * Called to read a chunk of data from the client socket. The data may
1224 * be the raw data, or may need to be further decoded by SASL.
1225 * The data will be read either straight from to the socket, or
1226 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1228 * NB, it is theoretically possible to have 2 layers of encryption,
1229 * both SASL, and this TLS layer. It is highly unlikely in practice
1230 * though, since SASL encryption will typically be a no-op if TLS
1231 * is active
1233 * Returns the number of bytes read, which may be less than
1234 * the requested 'datalen' if the socket would block. Returns
1235 * -1 on error, and disconnects the client socket.
1237 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1239 long ret;
1240 #ifdef CONFIG_VNC_TLS
1241 if (vs->tls.session) {
1242 ret = gnutls_read(vs->tls.session, data, datalen);
1243 if (ret < 0) {
1244 if (ret == GNUTLS_E_AGAIN)
1245 errno = EAGAIN;
1246 else
1247 errno = EIO;
1248 ret = -1;
1250 } else
1251 #endif /* CONFIG_VNC_TLS */
1252 ret = recv(vs->csock, (void *)data, datalen, 0);
1253 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1254 return vnc_client_io_error(vs, ret, socket_error());
1259 * Called to read data from the client socket to the input buffer,
1260 * when not using any SASL SSF encryption layers. Will read as much
1261 * data as possible without blocking.
1263 * Returns the number of bytes read. Returns -1 on error, and
1264 * disconnects the client socket.
1266 static long vnc_client_read_plain(VncState *vs)
1268 int ret;
1269 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1270 vs->input.buffer, vs->input.capacity, vs->input.offset);
1271 buffer_reserve(&vs->input, 4096);
1272 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1273 if (!ret)
1274 return 0;
1275 vs->input.offset += ret;
1276 return ret;
1281 * First function called whenever there is more data to be read from
1282 * the client socket. Will delegate actual work according to whether
1283 * SASL SSF layers are enabled (thus requiring decryption calls)
1285 void vnc_client_read(void *opaque)
1287 VncState *vs = opaque;
1288 long ret;
1290 #ifdef CONFIG_VNC_SASL
1291 if (vs->sasl.conn && vs->sasl.runSSF)
1292 ret = vnc_client_read_sasl(vs);
1293 else
1294 #endif /* CONFIG_VNC_SASL */
1295 ret = vnc_client_read_plain(vs);
1296 if (!ret) {
1297 if (vs->csock == -1)
1298 vnc_disconnect_finish(vs);
1299 return;
1302 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1303 size_t len = vs->read_handler_expect;
1304 int ret;
1306 ret = vs->read_handler(vs, vs->input.buffer, len);
1307 if (vs->csock == -1) {
1308 vnc_disconnect_finish(vs);
1309 return;
1312 if (!ret) {
1313 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1314 vs->input.offset -= len;
1315 } else {
1316 vs->read_handler_expect = ret;
1321 void vnc_write(VncState *vs, const void *data, size_t len)
1323 buffer_reserve(&vs->output, len);
1325 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1326 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1329 buffer_append(&vs->output, data, len);
1332 void vnc_write_s32(VncState *vs, int32_t value)
1334 vnc_write_u32(vs, *(uint32_t *)&value);
1337 void vnc_write_u32(VncState *vs, uint32_t value)
1339 uint8_t buf[4];
1341 buf[0] = (value >> 24) & 0xFF;
1342 buf[1] = (value >> 16) & 0xFF;
1343 buf[2] = (value >> 8) & 0xFF;
1344 buf[3] = value & 0xFF;
1346 vnc_write(vs, buf, 4);
1349 void vnc_write_u16(VncState *vs, uint16_t value)
1351 uint8_t buf[2];
1353 buf[0] = (value >> 8) & 0xFF;
1354 buf[1] = value & 0xFF;
1356 vnc_write(vs, buf, 2);
1359 void vnc_write_u8(VncState *vs, uint8_t value)
1361 vnc_write(vs, (char *)&value, 1);
1364 void vnc_flush(VncState *vs)
1366 if (vs->csock != -1 && vs->output.offset)
1367 vnc_client_write(vs);
1370 uint8_t read_u8(uint8_t *data, size_t offset)
1372 return data[offset];
1375 uint16_t read_u16(uint8_t *data, size_t offset)
1377 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1380 int32_t read_s32(uint8_t *data, size_t offset)
1382 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1383 (data[offset + 2] << 8) | data[offset + 3]);
1386 uint32_t read_u32(uint8_t *data, size_t offset)
1388 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1389 (data[offset + 2] << 8) | data[offset + 3]);
1392 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1396 static void check_pointer_type_change(VncState *vs, int absolute)
1398 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1399 vnc_write_u8(vs, 0);
1400 vnc_write_u8(vs, 0);
1401 vnc_write_u16(vs, 1);
1402 vnc_framebuffer_update(vs, absolute, 0,
1403 ds_get_width(vs->ds), ds_get_height(vs->ds),
1404 VNC_ENCODING_POINTER_TYPE_CHANGE);
1405 vnc_flush(vs);
1407 vs->absolute = absolute;
1410 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1412 int buttons = 0;
1413 int dz = 0;
1415 if (button_mask & 0x01)
1416 buttons |= MOUSE_EVENT_LBUTTON;
1417 if (button_mask & 0x02)
1418 buttons |= MOUSE_EVENT_MBUTTON;
1419 if (button_mask & 0x04)
1420 buttons |= MOUSE_EVENT_RBUTTON;
1421 if (button_mask & 0x08)
1422 dz = -1;
1423 if (button_mask & 0x10)
1424 dz = 1;
1426 if (vs->absolute) {
1427 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1428 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1429 dz, buttons);
1430 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1431 x -= 0x7FFF;
1432 y -= 0x7FFF;
1434 kbd_mouse_event(x, y, dz, buttons);
1435 } else {
1436 if (vs->last_x != -1)
1437 kbd_mouse_event(x - vs->last_x,
1438 y - vs->last_y,
1439 dz, buttons);
1440 vs->last_x = x;
1441 vs->last_y = y;
1444 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1447 static void reset_keys(VncState *vs)
1449 int i;
1450 for(i = 0; i < 256; i++) {
1451 if (vs->modifiers_state[i]) {
1452 if (i & 0x80)
1453 kbd_put_keycode(0xe0);
1454 kbd_put_keycode(i | 0x80);
1455 vs->modifiers_state[i] = 0;
1460 static void press_key(VncState *vs, int keysym)
1462 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1463 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
1466 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1468 /* QEMU console switch */
1469 switch(keycode) {
1470 case 0x2a: /* Left Shift */
1471 case 0x36: /* Right Shift */
1472 case 0x1d: /* Left CTRL */
1473 case 0x9d: /* Right CTRL */
1474 case 0x38: /* Left ALT */
1475 case 0xb8: /* Right ALT */
1476 if (down)
1477 vs->modifiers_state[keycode] = 1;
1478 else
1479 vs->modifiers_state[keycode] = 0;
1480 break;
1481 case 0x02 ... 0x0a: /* '1' to '9' keys */
1482 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1483 /* Reset the modifiers sent to the current console */
1484 reset_keys(vs);
1485 console_select(keycode - 0x02);
1486 return;
1488 break;
1489 case 0x3a: /* CapsLock */
1490 case 0x45: /* NumLock */
1491 if (!down)
1492 vs->modifiers_state[keycode] ^= 1;
1493 break;
1496 if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1497 /* If the numlock state needs to change then simulate an additional
1498 keypress before sending this one. This will happen if the user
1499 toggles numlock away from the VNC window.
1501 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1502 if (!vs->modifiers_state[0x45]) {
1503 vs->modifiers_state[0x45] = 1;
1504 press_key(vs, 0xff7f);
1506 } else {
1507 if (vs->modifiers_state[0x45]) {
1508 vs->modifiers_state[0x45] = 0;
1509 press_key(vs, 0xff7f);
1514 if ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z')) {
1515 /* If the capslock state needs to change then simulate an additional
1516 keypress before sending this one. This will happen if the user
1517 toggles capslock away from the VNC window.
1519 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1520 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1521 int capslock = !!(vs->modifiers_state[0x3a]);
1522 if (capslock) {
1523 if (uppercase == shift) {
1524 vs->modifiers_state[0x3a] = 0;
1525 press_key(vs, 0xffe5);
1527 } else {
1528 if (uppercase != shift) {
1529 vs->modifiers_state[0x3a] = 1;
1530 press_key(vs, 0xffe5);
1535 if (is_graphic_console()) {
1536 if (keycode & 0x80)
1537 kbd_put_keycode(0xe0);
1538 if (down)
1539 kbd_put_keycode(keycode & 0x7f);
1540 else
1541 kbd_put_keycode(keycode | 0x80);
1542 } else {
1543 /* QEMU console emulation */
1544 if (down) {
1545 int numlock = vs->modifiers_state[0x45];
1546 switch (keycode) {
1547 case 0x2a: /* Left Shift */
1548 case 0x36: /* Right Shift */
1549 case 0x1d: /* Left CTRL */
1550 case 0x9d: /* Right CTRL */
1551 case 0x38: /* Left ALT */
1552 case 0xb8: /* Right ALT */
1553 break;
1554 case 0xc8:
1555 kbd_put_keysym(QEMU_KEY_UP);
1556 break;
1557 case 0xd0:
1558 kbd_put_keysym(QEMU_KEY_DOWN);
1559 break;
1560 case 0xcb:
1561 kbd_put_keysym(QEMU_KEY_LEFT);
1562 break;
1563 case 0xcd:
1564 kbd_put_keysym(QEMU_KEY_RIGHT);
1565 break;
1566 case 0xd3:
1567 kbd_put_keysym(QEMU_KEY_DELETE);
1568 break;
1569 case 0xc7:
1570 kbd_put_keysym(QEMU_KEY_HOME);
1571 break;
1572 case 0xcf:
1573 kbd_put_keysym(QEMU_KEY_END);
1574 break;
1575 case 0xc9:
1576 kbd_put_keysym(QEMU_KEY_PAGEUP);
1577 break;
1578 case 0xd1:
1579 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1580 break;
1582 case 0x47:
1583 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1584 break;
1585 case 0x48:
1586 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1587 break;
1588 case 0x49:
1589 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1590 break;
1591 case 0x4b:
1592 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1593 break;
1594 case 0x4c:
1595 kbd_put_keysym('5');
1596 break;
1597 case 0x4d:
1598 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1599 break;
1600 case 0x4f:
1601 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1602 break;
1603 case 0x50:
1604 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1605 break;
1606 case 0x51:
1607 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1608 break;
1609 case 0x52:
1610 kbd_put_keysym('0');
1611 break;
1612 case 0x53:
1613 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1614 break;
1616 case 0xb5:
1617 kbd_put_keysym('/');
1618 break;
1619 case 0x37:
1620 kbd_put_keysym('*');
1621 break;
1622 case 0x4a:
1623 kbd_put_keysym('-');
1624 break;
1625 case 0x4e:
1626 kbd_put_keysym('+');
1627 break;
1628 case 0x9c:
1629 kbd_put_keysym('\n');
1630 break;
1632 default:
1633 kbd_put_keysym(sym);
1634 break;
1640 static void key_event(VncState *vs, int down, uint32_t sym)
1642 int keycode;
1643 int lsym = sym;
1645 if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1646 lsym = lsym - 'A' + 'a';
1649 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF);
1650 do_key_event(vs, down, keycode, sym);
1653 static void ext_key_event(VncState *vs, int down,
1654 uint32_t sym, uint16_t keycode)
1656 /* if the user specifies a keyboard layout, always use it */
1657 if (keyboard_layout)
1658 key_event(vs, down, sym);
1659 else
1660 do_key_event(vs, down, keycode, sym);
1663 static void framebuffer_update_request(VncState *vs, int incremental,
1664 int x_position, int y_position,
1665 int w, int h)
1667 if (x_position > ds_get_width(vs->ds))
1668 x_position = ds_get_width(vs->ds);
1669 if (y_position > ds_get_height(vs->ds))
1670 y_position = ds_get_height(vs->ds);
1671 if (x_position + w >= ds_get_width(vs->ds))
1672 w = ds_get_width(vs->ds) - x_position;
1673 if (y_position + h >= ds_get_height(vs->ds))
1674 h = ds_get_height(vs->ds) - y_position;
1676 int i;
1677 vs->need_update = 1;
1678 if (!incremental) {
1679 vs->force_update = 1;
1680 for (i = 0; i < h; i++) {
1681 vnc_set_bits(vs->dirty[y_position + i],
1682 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1687 static void send_ext_key_event_ack(VncState *vs)
1689 vnc_write_u8(vs, 0);
1690 vnc_write_u8(vs, 0);
1691 vnc_write_u16(vs, 1);
1692 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1693 VNC_ENCODING_EXT_KEY_EVENT);
1694 vnc_flush(vs);
1697 static void send_ext_audio_ack(VncState *vs)
1699 vnc_write_u8(vs, 0);
1700 vnc_write_u8(vs, 0);
1701 vnc_write_u16(vs, 1);
1702 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1703 VNC_ENCODING_AUDIO);
1704 vnc_flush(vs);
1707 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1709 int i;
1710 unsigned int enc = 0;
1712 vnc_zlib_init(vs);
1713 vs->features = 0;
1714 vs->vnc_encoding = 0;
1715 vs->tight_compression = 9;
1716 vs->tight_quality = 9;
1717 vs->absolute = -1;
1719 for (i = n_encodings - 1; i >= 0; i--) {
1720 enc = encodings[i];
1721 switch (enc) {
1722 case VNC_ENCODING_RAW:
1723 vs->vnc_encoding = enc;
1724 break;
1725 case VNC_ENCODING_COPYRECT:
1726 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1727 break;
1728 case VNC_ENCODING_HEXTILE:
1729 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1730 vs->vnc_encoding = enc;
1731 break;
1732 case VNC_ENCODING_ZLIB:
1733 vs->features |= VNC_FEATURE_ZLIB_MASK;
1734 vs->vnc_encoding = enc;
1735 break;
1736 case VNC_ENCODING_DESKTOPRESIZE:
1737 vs->features |= VNC_FEATURE_RESIZE_MASK;
1738 break;
1739 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1740 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1741 break;
1742 case VNC_ENCODING_EXT_KEY_EVENT:
1743 send_ext_key_event_ack(vs);
1744 break;
1745 case VNC_ENCODING_AUDIO:
1746 send_ext_audio_ack(vs);
1747 break;
1748 case VNC_ENCODING_WMVi:
1749 vs->features |= VNC_FEATURE_WMVI_MASK;
1750 break;
1751 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1752 vs->tight_compression = (enc & 0x0F);
1753 break;
1754 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1755 vs->tight_quality = (enc & 0x0F);
1756 break;
1757 default:
1758 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1759 break;
1763 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1766 static void set_pixel_conversion(VncState *vs)
1768 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1769 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1770 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1771 vs->write_pixels = vnc_write_pixels_copy;
1772 switch (vs->ds->surface->pf.bits_per_pixel) {
1773 case 8:
1774 vs->send_hextile_tile = send_hextile_tile_8;
1775 break;
1776 case 16:
1777 vs->send_hextile_tile = send_hextile_tile_16;
1778 break;
1779 case 32:
1780 vs->send_hextile_tile = send_hextile_tile_32;
1781 break;
1783 } else {
1784 vs->write_pixels = vnc_write_pixels_generic;
1785 switch (vs->ds->surface->pf.bits_per_pixel) {
1786 case 8:
1787 vs->send_hextile_tile = send_hextile_tile_generic_8;
1788 break;
1789 case 16:
1790 vs->send_hextile_tile = send_hextile_tile_generic_16;
1791 break;
1792 case 32:
1793 vs->send_hextile_tile = send_hextile_tile_generic_32;
1794 break;
1799 static void set_pixel_format(VncState *vs,
1800 int bits_per_pixel, int depth,
1801 int big_endian_flag, int true_color_flag,
1802 int red_max, int green_max, int blue_max,
1803 int red_shift, int green_shift, int blue_shift)
1805 if (!true_color_flag) {
1806 vnc_client_error(vs);
1807 return;
1810 vs->clientds = *(vs->vd->guest.ds);
1811 vs->clientds.pf.rmax = red_max;
1812 count_bits(vs->clientds.pf.rbits, red_max);
1813 vs->clientds.pf.rshift = red_shift;
1814 vs->clientds.pf.rmask = red_max << red_shift;
1815 vs->clientds.pf.gmax = green_max;
1816 count_bits(vs->clientds.pf.gbits, green_max);
1817 vs->clientds.pf.gshift = green_shift;
1818 vs->clientds.pf.gmask = green_max << green_shift;
1819 vs->clientds.pf.bmax = blue_max;
1820 count_bits(vs->clientds.pf.bbits, blue_max);
1821 vs->clientds.pf.bshift = blue_shift;
1822 vs->clientds.pf.bmask = blue_max << blue_shift;
1823 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1824 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1825 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1826 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1828 set_pixel_conversion(vs);
1830 vga_hw_invalidate();
1831 vga_hw_update();
1834 static void pixel_format_message (VncState *vs) {
1835 char pad[3] = { 0, 0, 0 };
1837 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1838 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1840 #ifdef HOST_WORDS_BIGENDIAN
1841 vnc_write_u8(vs, 1); /* big-endian-flag */
1842 #else
1843 vnc_write_u8(vs, 0); /* big-endian-flag */
1844 #endif
1845 vnc_write_u8(vs, 1); /* true-color-flag */
1846 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1847 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1848 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1849 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1850 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1851 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1852 if (vs->ds->surface->pf.bits_per_pixel == 32)
1853 vs->send_hextile_tile = send_hextile_tile_32;
1854 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1855 vs->send_hextile_tile = send_hextile_tile_16;
1856 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1857 vs->send_hextile_tile = send_hextile_tile_8;
1858 vs->clientds = *(vs->ds->surface);
1859 vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1860 vs->write_pixels = vnc_write_pixels_copy;
1862 vnc_write(vs, pad, 3); /* padding */
1865 static void vnc_dpy_setdata(DisplayState *ds)
1867 /* We don't have to do anything */
1870 static void vnc_colordepth(VncState *vs)
1872 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1873 /* Sending a WMVi message to notify the client*/
1874 vnc_write_u8(vs, 0); /* msg id */
1875 vnc_write_u8(vs, 0);
1876 vnc_write_u16(vs, 1); /* number of rects */
1877 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1878 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1879 pixel_format_message(vs);
1880 vnc_flush(vs);
1881 } else {
1882 set_pixel_conversion(vs);
1886 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1888 int i;
1889 uint16_t limit;
1890 VncDisplay *vd = vs->vd;
1892 if (data[0] > 3) {
1893 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1894 if (!qemu_timer_expired(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval))
1895 qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
1898 switch (data[0]) {
1899 case 0:
1900 if (len == 1)
1901 return 20;
1903 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1904 read_u8(data, 6), read_u8(data, 7),
1905 read_u16(data, 8), read_u16(data, 10),
1906 read_u16(data, 12), read_u8(data, 14),
1907 read_u8(data, 15), read_u8(data, 16));
1908 break;
1909 case 2:
1910 if (len == 1)
1911 return 4;
1913 if (len == 4) {
1914 limit = read_u16(data, 2);
1915 if (limit > 0)
1916 return 4 + (limit * 4);
1917 } else
1918 limit = read_u16(data, 2);
1920 for (i = 0; i < limit; i++) {
1921 int32_t val = read_s32(data, 4 + (i * 4));
1922 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1925 set_encodings(vs, (int32_t *)(data + 4), limit);
1926 break;
1927 case 3:
1928 if (len == 1)
1929 return 10;
1931 framebuffer_update_request(vs,
1932 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1933 read_u16(data, 6), read_u16(data, 8));
1934 break;
1935 case 4:
1936 if (len == 1)
1937 return 8;
1939 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1940 break;
1941 case 5:
1942 if (len == 1)
1943 return 6;
1945 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1946 break;
1947 case 6:
1948 if (len == 1)
1949 return 8;
1951 if (len == 8) {
1952 uint32_t dlen = read_u32(data, 4);
1953 if (dlen > 0)
1954 return 8 + dlen;
1957 client_cut_text(vs, read_u32(data, 4), data + 8);
1958 break;
1959 case 255:
1960 if (len == 1)
1961 return 2;
1963 switch (read_u8(data, 1)) {
1964 case 0:
1965 if (len == 2)
1966 return 12;
1968 ext_key_event(vs, read_u16(data, 2),
1969 read_u32(data, 4), read_u32(data, 8));
1970 break;
1971 case 1:
1972 if (len == 2)
1973 return 4;
1975 switch (read_u16 (data, 2)) {
1976 case 0:
1977 audio_add(vs);
1978 break;
1979 case 1:
1980 audio_del(vs);
1981 break;
1982 case 2:
1983 if (len == 4)
1984 return 10;
1985 switch (read_u8(data, 4)) {
1986 case 0: vs->as.fmt = AUD_FMT_U8; break;
1987 case 1: vs->as.fmt = AUD_FMT_S8; break;
1988 case 2: vs->as.fmt = AUD_FMT_U16; break;
1989 case 3: vs->as.fmt = AUD_FMT_S16; break;
1990 case 4: vs->as.fmt = AUD_FMT_U32; break;
1991 case 5: vs->as.fmt = AUD_FMT_S32; break;
1992 default:
1993 printf("Invalid audio format %d\n", read_u8(data, 4));
1994 vnc_client_error(vs);
1995 break;
1997 vs->as.nchannels = read_u8(data, 5);
1998 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1999 printf("Invalid audio channel coount %d\n",
2000 read_u8(data, 5));
2001 vnc_client_error(vs);
2002 break;
2004 vs->as.freq = read_u32(data, 6);
2005 break;
2006 default:
2007 printf ("Invalid audio message %d\n", read_u8(data, 4));
2008 vnc_client_error(vs);
2009 break;
2011 break;
2013 default:
2014 printf("Msg: %d\n", read_u16(data, 0));
2015 vnc_client_error(vs);
2016 break;
2018 break;
2019 default:
2020 printf("Msg: %d\n", data[0]);
2021 vnc_client_error(vs);
2022 break;
2025 vnc_read_when(vs, protocol_client_msg, 1);
2026 return 0;
2029 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2031 char buf[1024];
2032 int size;
2034 vnc_write_u16(vs, ds_get_width(vs->ds));
2035 vnc_write_u16(vs, ds_get_height(vs->ds));
2037 pixel_format_message(vs);
2039 if (qemu_name)
2040 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2041 else
2042 size = snprintf(buf, sizeof(buf), "QEMU");
2044 vnc_write_u32(vs, size);
2045 vnc_write(vs, buf, size);
2046 vnc_flush(vs);
2048 vnc_read_when(vs, protocol_client_msg, 1);
2050 return 0;
2053 void start_client_init(VncState *vs)
2055 vnc_read_when(vs, protocol_client_init, 1);
2058 static void make_challenge(VncState *vs)
2060 int i;
2062 srand(time(NULL)+getpid()+getpid()*987654+rand());
2064 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2065 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2068 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2070 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2071 int i, j, pwlen;
2072 unsigned char key[8];
2074 if (!vs->vd->password || !vs->vd->password[0]) {
2075 VNC_DEBUG("No password configured on server");
2076 vnc_write_u32(vs, 1); /* Reject auth */
2077 if (vs->minor >= 8) {
2078 static const char err[] = "Authentication failed";
2079 vnc_write_u32(vs, sizeof(err));
2080 vnc_write(vs, err, sizeof(err));
2082 vnc_flush(vs);
2083 vnc_client_error(vs);
2084 return 0;
2087 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2089 /* Calculate the expected challenge response */
2090 pwlen = strlen(vs->vd->password);
2091 for (i=0; i<sizeof(key); i++)
2092 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2093 deskey(key, EN0);
2094 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2095 des(response+j, response+j);
2097 /* Compare expected vs actual challenge response */
2098 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2099 VNC_DEBUG("Client challenge reponse did not match\n");
2100 vnc_write_u32(vs, 1); /* Reject auth */
2101 if (vs->minor >= 8) {
2102 static const char err[] = "Authentication failed";
2103 vnc_write_u32(vs, sizeof(err));
2104 vnc_write(vs, err, sizeof(err));
2106 vnc_flush(vs);
2107 vnc_client_error(vs);
2108 } else {
2109 VNC_DEBUG("Accepting VNC challenge response\n");
2110 vnc_write_u32(vs, 0); /* Accept auth */
2111 vnc_flush(vs);
2113 start_client_init(vs);
2115 return 0;
2118 void start_auth_vnc(VncState *vs)
2120 make_challenge(vs);
2121 /* Send client a 'random' challenge */
2122 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2123 vnc_flush(vs);
2125 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2129 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2131 /* We only advertise 1 auth scheme at a time, so client
2132 * must pick the one we sent. Verify this */
2133 if (data[0] != vs->vd->auth) { /* Reject auth */
2134 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2135 vnc_write_u32(vs, 1);
2136 if (vs->minor >= 8) {
2137 static const char err[] = "Authentication failed";
2138 vnc_write_u32(vs, sizeof(err));
2139 vnc_write(vs, err, sizeof(err));
2141 vnc_client_error(vs);
2142 } else { /* Accept requested auth */
2143 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2144 switch (vs->vd->auth) {
2145 case VNC_AUTH_NONE:
2146 VNC_DEBUG("Accept auth none\n");
2147 if (vs->minor >= 8) {
2148 vnc_write_u32(vs, 0); /* Accept auth completion */
2149 vnc_flush(vs);
2151 start_client_init(vs);
2152 break;
2154 case VNC_AUTH_VNC:
2155 VNC_DEBUG("Start VNC auth\n");
2156 start_auth_vnc(vs);
2157 break;
2159 #ifdef CONFIG_VNC_TLS
2160 case VNC_AUTH_VENCRYPT:
2161 VNC_DEBUG("Accept VeNCrypt auth\n");;
2162 start_auth_vencrypt(vs);
2163 break;
2164 #endif /* CONFIG_VNC_TLS */
2166 #ifdef CONFIG_VNC_SASL
2167 case VNC_AUTH_SASL:
2168 VNC_DEBUG("Accept SASL auth\n");
2169 start_auth_sasl(vs);
2170 break;
2171 #endif /* CONFIG_VNC_SASL */
2173 default: /* Should not be possible, but just in case */
2174 VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
2175 vnc_write_u8(vs, 1);
2176 if (vs->minor >= 8) {
2177 static const char err[] = "Authentication failed";
2178 vnc_write_u32(vs, sizeof(err));
2179 vnc_write(vs, err, sizeof(err));
2181 vnc_client_error(vs);
2184 return 0;
2187 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2189 char local[13];
2191 memcpy(local, version, 12);
2192 local[12] = 0;
2194 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2195 VNC_DEBUG("Malformed protocol version %s\n", local);
2196 vnc_client_error(vs);
2197 return 0;
2199 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2200 if (vs->major != 3 ||
2201 (vs->minor != 3 &&
2202 vs->minor != 4 &&
2203 vs->minor != 5 &&
2204 vs->minor != 7 &&
2205 vs->minor != 8)) {
2206 VNC_DEBUG("Unsupported client version\n");
2207 vnc_write_u32(vs, VNC_AUTH_INVALID);
2208 vnc_flush(vs);
2209 vnc_client_error(vs);
2210 return 0;
2212 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2213 * as equivalent to v3.3 by servers
2215 if (vs->minor == 4 || vs->minor == 5)
2216 vs->minor = 3;
2218 if (vs->minor == 3) {
2219 if (vs->vd->auth == VNC_AUTH_NONE) {
2220 VNC_DEBUG("Tell client auth none\n");
2221 vnc_write_u32(vs, vs->vd->auth);
2222 vnc_flush(vs);
2223 start_client_init(vs);
2224 } else if (vs->vd->auth == VNC_AUTH_VNC) {
2225 VNC_DEBUG("Tell client VNC auth\n");
2226 vnc_write_u32(vs, vs->vd->auth);
2227 vnc_flush(vs);
2228 start_auth_vnc(vs);
2229 } else {
2230 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2231 vnc_write_u32(vs, VNC_AUTH_INVALID);
2232 vnc_flush(vs);
2233 vnc_client_error(vs);
2235 } else {
2236 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2237 vnc_write_u8(vs, 1); /* num auth */
2238 vnc_write_u8(vs, vs->vd->auth);
2239 vnc_read_when(vs, protocol_client_auth, 1);
2240 vnc_flush(vs);
2243 return 0;
2246 static int vnc_refresh_server_surface(VncDisplay *vd)
2248 int y;
2249 uint8_t *guest_row;
2250 uint8_t *server_row;
2251 int cmp_bytes;
2252 uint32_t width_mask[VNC_DIRTY_WORDS];
2253 VncState *vs = NULL;
2254 int has_dirty = 0;
2257 * Walk through the guest dirty map.
2258 * Check and copy modified bits from guest to server surface.
2259 * Update server dirty map.
2261 vnc_set_bits(width_mask, (ds_get_width(vd->ds) / 16), VNC_DIRTY_WORDS);
2262 cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2263 guest_row = vd->guest.ds->data;
2264 server_row = vd->server->data;
2265 for (y = 0; y < vd->guest.ds->height; y++) {
2266 if (vnc_and_bits(vd->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
2267 int x;
2268 uint8_t *guest_ptr;
2269 uint8_t *server_ptr;
2271 guest_ptr = guest_row;
2272 server_ptr = server_row;
2274 for (x = 0; x < vd->guest.ds->width;
2275 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2276 if (!vnc_get_bit(vd->guest.dirty[y], (x / 16)))
2277 continue;
2278 vnc_clear_bit(vd->guest.dirty[y], (x / 16));
2279 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2280 continue;
2281 memcpy(server_ptr, guest_ptr, cmp_bytes);
2282 vs = vd->clients;
2283 while (vs != NULL) {
2284 vnc_set_bit(vs->dirty[y], (x / 16));
2285 vs = vs->next;
2287 has_dirty++;
2290 guest_row += ds_get_linesize(vd->ds);
2291 server_row += ds_get_linesize(vd->ds);
2293 return has_dirty;
2296 static void vnc_refresh(void *opaque)
2298 VncDisplay *vd = opaque;
2299 VncState *vs = NULL;
2300 int has_dirty = 0, rects = 0;
2302 vga_hw_update();
2304 has_dirty = vnc_refresh_server_surface(vd);
2306 vs = vd->clients;
2307 while (vs != NULL) {
2308 rects += vnc_update_client(vs, has_dirty);
2309 vs = vs->next;
2311 /* vd->timer could be NULL now if the last client disconnected,
2312 * in this case don't update the timer */
2313 if (vd->timer == NULL)
2314 return;
2316 if (has_dirty && rects) {
2317 vd->timer_interval /= 2;
2318 if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2319 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2320 } else {
2321 vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2322 if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2323 vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2325 qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
2328 static void vnc_init_timer(VncDisplay *vd)
2330 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2331 if (vd->timer == NULL && vd->clients != NULL) {
2332 vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
2333 vnc_refresh(vd);
2337 static void vnc_remove_timer(VncDisplay *vd)
2339 if (vd->timer != NULL && vd->clients == NULL) {
2340 qemu_del_timer(vd->timer);
2341 qemu_free_timer(vd->timer);
2342 vd->timer = NULL;
2346 static void vnc_connect(VncDisplay *vd, int csock)
2348 VncState *vs = qemu_mallocz(sizeof(VncState));
2349 vs->csock = csock;
2351 VNC_DEBUG("New client on socket %d\n", csock);
2352 dcl->idle = 0;
2353 socket_set_nonblock(vs->csock);
2354 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2356 vs->vd = vd;
2357 vs->ds = vd->ds;
2358 vs->last_x = -1;
2359 vs->last_y = -1;
2361 vs->as.freq = 44100;
2362 vs->as.nchannels = 2;
2363 vs->as.fmt = AUD_FMT_S16;
2364 vs->as.endianness = 0;
2366 vs->next = vd->clients;
2367 vd->clients = vs;
2369 vga_hw_update();
2371 vnc_write(vs, "RFB 003.008\n", 12);
2372 vnc_flush(vs);
2373 vnc_read_when(vs, protocol_version, 12);
2374 reset_keys(vs);
2376 vnc_init_timer(vd);
2378 /* vs might be free()ed here */
2381 static void vnc_listen_read(void *opaque)
2383 VncDisplay *vs = opaque;
2384 struct sockaddr_in addr;
2385 socklen_t addrlen = sizeof(addr);
2387 /* Catch-up */
2388 vga_hw_update();
2390 int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2391 if (csock != -1) {
2392 vnc_connect(vs, csock);
2396 void vnc_display_init(DisplayState *ds)
2398 VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2400 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2402 ds->opaque = vs;
2403 dcl->idle = 1;
2404 vnc_display = vs;
2406 vs->lsock = -1;
2408 vs->ds = ds;
2410 if (keyboard_layout)
2411 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2412 else
2413 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2415 if (!vs->kbd_layout)
2416 exit(1);
2418 dcl->dpy_copy = vnc_dpy_copy;
2419 dcl->dpy_update = vnc_dpy_update;
2420 dcl->dpy_resize = vnc_dpy_resize;
2421 dcl->dpy_setdata = vnc_dpy_setdata;
2422 register_displaychangelistener(ds, dcl);
2426 void vnc_display_close(DisplayState *ds)
2428 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2430 if (!vs)
2431 return;
2432 if (vs->display) {
2433 qemu_free(vs->display);
2434 vs->display = NULL;
2436 if (vs->lsock != -1) {
2437 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2438 close(vs->lsock);
2439 vs->lsock = -1;
2441 vs->auth = VNC_AUTH_INVALID;
2442 #ifdef CONFIG_VNC_TLS
2443 vs->subauth = VNC_AUTH_INVALID;
2444 vs->tls.x509verify = 0;
2445 #endif
2448 int vnc_display_password(DisplayState *ds, const char *password)
2450 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2452 if (!vs) {
2453 return -1;
2456 if (vs->password) {
2457 qemu_free(vs->password);
2458 vs->password = NULL;
2460 if (password && password[0]) {
2461 if (!(vs->password = qemu_strdup(password)))
2462 return -1;
2463 if (vs->auth == VNC_AUTH_NONE) {
2464 vs->auth = VNC_AUTH_VNC;
2466 } else {
2467 vs->auth = VNC_AUTH_NONE;
2470 return 0;
2473 char *vnc_display_local_addr(DisplayState *ds)
2475 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2477 return vnc_socket_local_addr("%s:%s", vs->lsock);
2480 int vnc_display_open(DisplayState *ds, const char *display)
2482 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2483 const char *options;
2484 int password = 0;
2485 int reverse = 0;
2486 int to_port = 0;
2487 #ifdef CONFIG_VNC_TLS
2488 int tls = 0, x509 = 0;
2489 #endif
2490 #ifdef CONFIG_VNC_SASL
2491 int sasl = 0;
2492 int saslErr;
2493 #endif
2494 int acl = 0;
2496 if (!vnc_display)
2497 return -1;
2498 vnc_display_close(ds);
2499 if (strcmp(display, "none") == 0)
2500 return 0;
2502 if (!(vs->display = strdup(display)))
2503 return -1;
2505 options = display;
2506 while ((options = strchr(options, ','))) {
2507 options++;
2508 if (strncmp(options, "password", 8) == 0) {
2509 password = 1; /* Require password auth */
2510 } else if (strncmp(options, "reverse", 7) == 0) {
2511 reverse = 1;
2512 } else if (strncmp(options, "to=", 3) == 0) {
2513 to_port = atoi(options+3) + 5900;
2514 #ifdef CONFIG_VNC_SASL
2515 } else if (strncmp(options, "sasl", 4) == 0) {
2516 sasl = 1; /* Require SASL auth */
2517 #endif
2518 #ifdef CONFIG_VNC_TLS
2519 } else if (strncmp(options, "tls", 3) == 0) {
2520 tls = 1; /* Require TLS */
2521 } else if (strncmp(options, "x509", 4) == 0) {
2522 char *start, *end;
2523 x509 = 1; /* Require x509 certificates */
2524 if (strncmp(options, "x509verify", 10) == 0)
2525 vs->tls.x509verify = 1; /* ...and verify client certs */
2527 /* Now check for 'x509=/some/path' postfix
2528 * and use that to setup x509 certificate/key paths */
2529 start = strchr(options, '=');
2530 end = strchr(options, ',');
2531 if (start && (!end || (start < end))) {
2532 int len = end ? end-(start+1) : strlen(start+1);
2533 char *path = qemu_strndup(start + 1, len);
2535 VNC_DEBUG("Trying certificate path '%s'\n", path);
2536 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2537 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2538 qemu_free(path);
2539 qemu_free(vs->display);
2540 vs->display = NULL;
2541 return -1;
2543 qemu_free(path);
2544 } else {
2545 fprintf(stderr, "No certificate path provided\n");
2546 qemu_free(vs->display);
2547 vs->display = NULL;
2548 return -1;
2550 #endif
2551 } else if (strncmp(options, "acl", 3) == 0) {
2552 acl = 1;
2556 #ifdef CONFIG_VNC_TLS
2557 if (acl && x509 && vs->tls.x509verify) {
2558 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2559 fprintf(stderr, "Failed to create x509 dname ACL\n");
2560 exit(1);
2563 #endif
2564 #ifdef CONFIG_VNC_SASL
2565 if (acl && sasl) {
2566 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2567 fprintf(stderr, "Failed to create username ACL\n");
2568 exit(1);
2571 #endif
2574 * Combinations we support here:
2576 * - no-auth (clear text, no auth)
2577 * - password (clear text, weak auth)
2578 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
2579 * - tls (encrypt, weak anonymous creds, no auth)
2580 * - tls + password (encrypt, weak anonymous creds, weak auth)
2581 * - tls + sasl (encrypt, weak anonymous creds, good auth)
2582 * - tls + x509 (encrypt, good x509 creds, no auth)
2583 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
2584 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
2586 * NB1. TLS is a stackable auth scheme.
2587 * NB2. the x509 schemes have option to validate a client cert dname
2589 if (password) {
2590 #ifdef CONFIG_VNC_TLS
2591 if (tls) {
2592 vs->auth = VNC_AUTH_VENCRYPT;
2593 if (x509) {
2594 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2595 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2596 } else {
2597 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2598 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2600 } else {
2601 #endif /* CONFIG_VNC_TLS */
2602 VNC_DEBUG("Initializing VNC server with password auth\n");
2603 vs->auth = VNC_AUTH_VNC;
2604 #ifdef CONFIG_VNC_TLS
2605 vs->subauth = VNC_AUTH_INVALID;
2607 #endif /* CONFIG_VNC_TLS */
2608 #ifdef CONFIG_VNC_SASL
2609 } else if (sasl) {
2610 #ifdef CONFIG_VNC_TLS
2611 if (tls) {
2612 vs->auth = VNC_AUTH_VENCRYPT;
2613 if (x509) {
2614 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2615 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2616 } else {
2617 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2618 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2620 } else {
2621 #endif /* CONFIG_VNC_TLS */
2622 VNC_DEBUG("Initializing VNC server with SASL auth\n");
2623 vs->auth = VNC_AUTH_SASL;
2624 #ifdef CONFIG_VNC_TLS
2625 vs->subauth = VNC_AUTH_INVALID;
2627 #endif /* CONFIG_VNC_TLS */
2628 #endif /* CONFIG_VNC_SASL */
2629 } else {
2630 #ifdef CONFIG_VNC_TLS
2631 if (tls) {
2632 vs->auth = VNC_AUTH_VENCRYPT;
2633 if (x509) {
2634 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2635 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2636 } else {
2637 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2638 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2640 } else {
2641 #endif
2642 VNC_DEBUG("Initializing VNC server with no auth\n");
2643 vs->auth = VNC_AUTH_NONE;
2644 #ifdef CONFIG_VNC_TLS
2645 vs->subauth = VNC_AUTH_INVALID;
2647 #endif
2650 #ifdef CONFIG_VNC_SASL
2651 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2652 fprintf(stderr, "Failed to initialize SASL auth %s",
2653 sasl_errstring(saslErr, NULL, NULL));
2654 free(vs->display);
2655 vs->display = NULL;
2656 return -1;
2658 #endif
2660 if (reverse) {
2661 /* connect to viewer */
2662 if (strncmp(display, "unix:", 5) == 0)
2663 vs->lsock = unix_connect(display+5);
2664 else
2665 vs->lsock = inet_connect(display, SOCK_STREAM);
2666 if (-1 == vs->lsock) {
2667 free(vs->display);
2668 vs->display = NULL;
2669 return -1;
2670 } else {
2671 int csock = vs->lsock;
2672 vs->lsock = -1;
2673 vnc_connect(vs, csock);
2675 return 0;
2677 } else {
2678 /* listen for connects */
2679 char *dpy;
2680 dpy = qemu_malloc(256);
2681 if (strncmp(display, "unix:", 5) == 0) {
2682 pstrcpy(dpy, 256, "unix:");
2683 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2684 } else {
2685 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2687 if (-1 == vs->lsock) {
2688 free(dpy);
2689 return -1;
2690 } else {
2691 free(vs->display);
2692 vs->display = dpy;
2695 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);