vnc: factor out vnc_desktop_resize()
[qemu/kraxel.git] / vnc.c
blob4fb13ba88658c9377d92259bddb60a076fe79fc5
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 int vnc_cursor_define(VncState *vs);
54 static char *addr_to_string(const char *format,
55 struct sockaddr_storage *sa,
56 socklen_t salen) {
57 char *addr;
58 char host[NI_MAXHOST];
59 char serv[NI_MAXSERV];
60 int err;
61 size_t addrlen;
63 if ((err = getnameinfo((struct sockaddr *)sa, salen,
64 host, sizeof(host),
65 serv, sizeof(serv),
66 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
67 VNC_DEBUG("Cannot resolve address %d: %s\n",
68 err, gai_strerror(err));
69 return NULL;
72 /* Enough for the existing format + the 2 vars we're
73 * substituting in. */
74 addrlen = strlen(format) + strlen(host) + strlen(serv);
75 addr = qemu_malloc(addrlen + 1);
76 snprintf(addr, addrlen, format, host, serv);
77 addr[addrlen] = '\0';
79 return addr;
83 char *vnc_socket_local_addr(const char *format, int fd) {
84 struct sockaddr_storage sa;
85 socklen_t salen;
87 salen = sizeof(sa);
88 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
89 return NULL;
91 return addr_to_string(format, &sa, salen);
94 char *vnc_socket_remote_addr(const char *format, int fd) {
95 struct sockaddr_storage sa;
96 socklen_t salen;
98 salen = sizeof(sa);
99 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
100 return NULL;
102 return addr_to_string(format, &sa, salen);
105 static int put_addr_qdict(QDict *qdict, struct sockaddr_storage *sa,
106 socklen_t salen)
108 char host[NI_MAXHOST];
109 char serv[NI_MAXSERV];
110 int err;
112 if ((err = getnameinfo((struct sockaddr *)sa, salen,
113 host, sizeof(host),
114 serv, sizeof(serv),
115 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
116 VNC_DEBUG("Cannot resolve address %d: %s\n",
117 err, gai_strerror(err));
118 return -1;
121 qdict_put(qdict, "host", qstring_from_str(host));
122 qdict_put(qdict, "service", qstring_from_str(serv));
123 qdict_put(qdict, "family",qstring_from_str(inet_strfamily(sa->ss_family)));
125 return 0;
128 static int vnc_server_addr_put(QDict *qdict, int fd)
130 struct sockaddr_storage sa;
131 socklen_t salen;
133 salen = sizeof(sa);
134 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
135 return -1;
138 return put_addr_qdict(qdict, &sa, salen);
141 static int vnc_qdict_remote_addr(QDict *qdict, int fd)
143 struct sockaddr_storage sa;
144 socklen_t salen;
146 salen = sizeof(sa);
147 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
148 return -1;
151 return put_addr_qdict(qdict, &sa, salen);
154 static const char *vnc_auth_name(VncDisplay *vd) {
155 switch (vd->auth) {
156 case VNC_AUTH_INVALID:
157 return "invalid";
158 case VNC_AUTH_NONE:
159 return "none";
160 case VNC_AUTH_VNC:
161 return "vnc";
162 case VNC_AUTH_RA2:
163 return "ra2";
164 case VNC_AUTH_RA2NE:
165 return "ra2ne";
166 case VNC_AUTH_TIGHT:
167 return "tight";
168 case VNC_AUTH_ULTRA:
169 return "ultra";
170 case VNC_AUTH_TLS:
171 return "tls";
172 case VNC_AUTH_VENCRYPT:
173 #ifdef CONFIG_VNC_TLS
174 switch (vd->subauth) {
175 case VNC_AUTH_VENCRYPT_PLAIN:
176 return "vencrypt+plain";
177 case VNC_AUTH_VENCRYPT_TLSNONE:
178 return "vencrypt+tls+none";
179 case VNC_AUTH_VENCRYPT_TLSVNC:
180 return "vencrypt+tls+vnc";
181 case VNC_AUTH_VENCRYPT_TLSPLAIN:
182 return "vencrypt+tls+plain";
183 case VNC_AUTH_VENCRYPT_X509NONE:
184 return "vencrypt+x509+none";
185 case VNC_AUTH_VENCRYPT_X509VNC:
186 return "vencrypt+x509+vnc";
187 case VNC_AUTH_VENCRYPT_X509PLAIN:
188 return "vencrypt+x509+plain";
189 case VNC_AUTH_VENCRYPT_TLSSASL:
190 return "vencrypt+tls+sasl";
191 case VNC_AUTH_VENCRYPT_X509SASL:
192 return "vencrypt+x509+sasl";
193 default:
194 return "vencrypt";
196 #else
197 return "vencrypt";
198 #endif
199 case VNC_AUTH_SASL:
200 return "sasl";
202 return "unknown";
205 static int vnc_server_info_put(QDict *qdict)
207 if (vnc_server_addr_put(qdict, vnc_display->lsock) < 0) {
208 return -1;
211 qdict_put(qdict, "auth", qstring_from_str(vnc_auth_name(vnc_display)));
212 return 0;
215 static void vnc_client_cache_auth(VncState *client)
217 QDict *qdict;
219 if (!client->info) {
220 return;
223 qdict = qobject_to_qdict(client->info);
225 #ifdef CONFIG_VNC_TLS
226 if (client->tls.session &&
227 client->tls.dname) {
228 qdict_put(qdict, "x509_dname", qstring_from_str(client->tls.dname));
230 #endif
231 #ifdef CONFIG_VNC_SASL
232 if (client->sasl.conn &&
233 client->sasl.username) {
234 qdict_put(qdict, "sasl_username",
235 qstring_from_str(client->sasl.username));
237 #endif
240 static void vnc_client_cache_addr(VncState *client)
242 QDict *qdict;
244 qdict = qdict_new();
245 if (vnc_qdict_remote_addr(qdict, client->csock) < 0) {
246 QDECREF(qdict);
247 /* XXX: how to report the error? */
248 return;
251 client->info = QOBJECT(qdict);
254 static void vnc_qmp_event(VncState *vs, MonitorEvent event)
256 QDict *server;
257 QObject *data;
259 if (!vs->info) {
260 return;
263 server = qdict_new();
264 if (vnc_server_info_put(server) < 0) {
265 QDECREF(server);
266 return;
269 data = qobject_from_jsonf("{ 'client': %p, 'server': %p }",
270 vs->info, QOBJECT(server));
272 monitor_protocol_event(event, data);
274 qobject_incref(vs->info);
275 qobject_decref(data);
278 static void info_vnc_iter(QObject *obj, void *opaque)
280 QDict *client;
281 Monitor *mon = opaque;
283 client = qobject_to_qdict(obj);
284 monitor_printf(mon, "Client:\n");
285 monitor_printf(mon, " address: %s:%s\n",
286 qdict_get_str(client, "host"),
287 qdict_get_str(client, "service"));
289 #ifdef CONFIG_VNC_TLS
290 monitor_printf(mon, " x509_dname: %s\n",
291 qdict_haskey(client, "x509_dname") ?
292 qdict_get_str(client, "x509_dname") : "none");
293 #endif
294 #ifdef CONFIG_VNC_SASL
295 monitor_printf(mon, " username: %s\n",
296 qdict_haskey(client, "sasl_username") ?
297 qdict_get_str(client, "sasl_username") : "none");
298 #endif
301 void do_info_vnc_print(Monitor *mon, const QObject *data)
303 QDict *server;
304 QList *clients;
306 server = qobject_to_qdict(data);
307 if (qdict_get_bool(server, "enabled") == 0) {
308 monitor_printf(mon, "Server: disabled\n");
309 return;
312 monitor_printf(mon, "Server:\n");
313 monitor_printf(mon, " address: %s:%s\n",
314 qdict_get_str(server, "host"),
315 qdict_get_str(server, "service"));
316 monitor_printf(mon, " auth: %s\n", qdict_get_str(server, "auth"));
318 clients = qdict_get_qlist(server, "clients");
319 if (qlist_empty(clients)) {
320 monitor_printf(mon, "Client: none\n");
321 } else {
322 qlist_iter(clients, info_vnc_iter, mon);
327 * do_info_vnc(): Show VNC server information
329 * Return a QDict with server information. Connected clients are returned
330 * as a QList of QDicts.
332 * The main QDict contains the following:
334 * - "enabled": true or false
335 * - "host": server's IP address
336 * - "family": address family ("ipv4" or "ipv6")
337 * - "service": server's port number
338 * - "auth": authentication method
339 * - "clients": a QList of all connected clients
341 * Clients are described by a QDict, with the following information:
343 * - "host": client's IP address
344 * - "family": address family ("ipv4" or "ipv6")
345 * - "service": client's port number
346 * - "x509_dname": TLS dname (optional)
347 * - "sasl_username": SASL username (optional)
349 * Example:
351 * { "enabled": true, "host": "0.0.0.0", "service": "50402", "auth": "vnc",
352 * "family": "ipv4",
353 * "clients": [{ "host": "127.0.0.1", "service": "50401", "family": "ipv4" }]}
355 void do_info_vnc(Monitor *mon, QObject **ret_data)
357 if (vnc_display == NULL || vnc_display->display == NULL) {
358 *ret_data = qobject_from_jsonf("{ 'enabled': false }");
359 } else {
360 QList *clist;
361 VncState *client;
363 clist = qlist_new();
364 QTAILQ_FOREACH(client, &vnc_display->clients, next) {
365 if (client->info) {
366 /* incref so that it's not freed by upper layers */
367 qobject_incref(client->info);
368 qlist_append_obj(clist, client->info);
372 *ret_data = qobject_from_jsonf("{ 'enabled': true, 'clients': %p }",
373 QOBJECT(clist));
374 assert(*ret_data != NULL);
376 if (vnc_server_info_put(qobject_to_qdict(*ret_data)) < 0) {
377 qobject_decref(*ret_data);
378 *ret_data = NULL;
383 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
384 return (vs->features & (1 << feature));
387 /* TODO
388 1) Get the queue working for IO.
389 2) there is some weirdness when using the -S option (the screen is grey
390 and not totally invalidated
391 3) resolutions > 1024
394 static int vnc_update_client(VncState *vs, int has_dirty);
395 static void vnc_disconnect_start(VncState *vs);
396 static void vnc_disconnect_finish(VncState *vs);
397 static void vnc_init_timer(VncDisplay *vd);
398 static void vnc_remove_timer(VncDisplay *vd);
400 static void vnc_colordepth(VncState *vs);
401 static void framebuffer_update_request(VncState *vs, int incremental,
402 int x_position, int y_position,
403 int w, int h);
404 static void vnc_refresh(void *opaque);
405 static int vnc_refresh_server_surface(VncDisplay *vd);
407 static inline void vnc_set_bit(uint32_t *d, int k)
409 d[k >> 5] |= 1 << (k & 0x1f);
412 static inline void vnc_clear_bit(uint32_t *d, int k)
414 d[k >> 5] &= ~(1 << (k & 0x1f));
417 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
419 int j;
421 j = 0;
422 while (n >= 32) {
423 d[j++] = -1;
424 n -= 32;
426 if (n > 0)
427 d[j++] = (1 << n) - 1;
428 while (j < nb_words)
429 d[j++] = 0;
432 static inline int vnc_get_bit(const uint32_t *d, int k)
434 return (d[k >> 5] >> (k & 0x1f)) & 1;
437 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
438 int nb_words)
440 int i;
441 for(i = 0; i < nb_words; i++) {
442 if ((d1[i] & d2[i]) != 0)
443 return 1;
445 return 0;
448 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
450 int i;
451 VncDisplay *vd = ds->opaque;
452 struct VncSurface *s = &vd->guest;
454 h += y;
456 /* round x down to ensure the loop only spans one 16-pixel block per,
457 iteration. otherwise, if (x % 16) != 0, the last iteration may span
458 two 16-pixel blocks but we only mark the first as dirty
460 w += (x % 16);
461 x -= (x % 16);
463 x = MIN(x, s->ds->width);
464 y = MIN(y, s->ds->height);
465 w = MIN(x + w, s->ds->width) - x;
466 h = MIN(h, s->ds->height);
468 for (; y < h; y++)
469 for (i = 0; i < w; i += 16)
470 vnc_set_bit(s->dirty[y], (x + i) / 16);
473 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
474 int32_t encoding)
476 vnc_write_u16(vs, x);
477 vnc_write_u16(vs, y);
478 vnc_write_u16(vs, w);
479 vnc_write_u16(vs, h);
481 vnc_write_s32(vs, encoding);
484 void buffer_reserve(Buffer *buffer, size_t len)
486 if ((buffer->capacity - buffer->offset) < len) {
487 buffer->capacity += (len + 1024);
488 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
489 if (buffer->buffer == NULL) {
490 fprintf(stderr, "vnc: out of memory\n");
491 exit(1);
496 int buffer_empty(Buffer *buffer)
498 return buffer->offset == 0;
501 uint8_t *buffer_end(Buffer *buffer)
503 return buffer->buffer + buffer->offset;
506 void buffer_reset(Buffer *buffer)
508 buffer->offset = 0;
511 void buffer_free(Buffer *buffer)
513 qemu_free(buffer->buffer);
514 buffer->offset = 0;
515 buffer->capacity = 0;
516 buffer->buffer = NULL;
519 void buffer_append(Buffer *buffer, const void *data, size_t len)
521 memcpy(buffer->buffer + buffer->offset, data, len);
522 buffer->offset += len;
525 static void vnc_desktop_resize(VncState *vs)
527 DisplayState *ds = vs->ds;
529 if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
530 return;
532 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
533 vnc_write_u8(vs, 0);
534 vnc_write_u16(vs, 1); /* number of rects */
535 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
536 VNC_ENCODING_DESKTOPRESIZE);
537 vnc_flush(vs);
540 static void vnc_dpy_resize(DisplayState *ds)
542 int size_changed;
543 VncDisplay *vd = ds->opaque;
544 VncState *vs;
546 /* server surface */
547 if (!vd->server)
548 vd->server = qemu_mallocz(sizeof(*vd->server));
549 if (vd->server->data)
550 qemu_free(vd->server->data);
551 *(vd->server) = *(ds->surface);
552 vd->server->data = qemu_mallocz(vd->server->linesize *
553 vd->server->height);
555 /* guest surface */
556 if (!vd->guest.ds)
557 vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
558 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
559 console_color_init(ds);
560 size_changed = ds_get_width(ds) != vd->guest.ds->width ||
561 ds_get_height(ds) != vd->guest.ds->height;
562 *(vd->guest.ds) = *(ds->surface);
563 memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
565 QTAILQ_FOREACH(vs, &vd->clients, next) {
566 vnc_colordepth(vs);
567 if (size_changed) {
568 vnc_desktop_resize(vs);
570 if (vs->vd->cursor) {
571 vnc_cursor_define(vs);
573 memset(vs->dirty, 0xFF, sizeof(vs->dirty));
577 /* fastest code */
578 static void vnc_write_pixels_copy(VncState *vs, struct PixelFormat *pf,
579 void *pixels, int size)
581 vnc_write(vs, pixels, size);
584 /* slowest but generic code. */
585 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
587 uint8_t r, g, b;
588 VncDisplay *vd = vs->vd;
590 r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>
591 vd->server->pf.rbits);
592 g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>
593 vd->server->pf.gbits);
594 b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>
595 vd->server->pf.bbits);
596 v = (r << vs->clientds.pf.rshift) |
597 (g << vs->clientds.pf.gshift) |
598 (b << vs->clientds.pf.bshift);
599 switch(vs->clientds.pf.bytes_per_pixel) {
600 case 1:
601 buf[0] = v;
602 break;
603 case 2:
604 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
605 buf[0] = v >> 8;
606 buf[1] = v;
607 } else {
608 buf[1] = v >> 8;
609 buf[0] = v;
611 break;
612 default:
613 case 4:
614 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
615 buf[0] = v >> 24;
616 buf[1] = v >> 16;
617 buf[2] = v >> 8;
618 buf[3] = v;
619 } else {
620 buf[3] = v >> 24;
621 buf[2] = v >> 16;
622 buf[1] = v >> 8;
623 buf[0] = v;
625 break;
629 static void vnc_write_pixels_generic(VncState *vs, struct PixelFormat *pf,
630 void *pixels1, int size)
632 uint8_t buf[4];
634 if (pf->bytes_per_pixel == 4) {
635 uint32_t *pixels = pixels1;
636 int n, i;
637 n = size >> 2;
638 for(i = 0; i < n; i++) {
639 vnc_convert_pixel(vs, buf, pixels[i]);
640 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
642 } else if (pf->bytes_per_pixel == 2) {
643 uint16_t *pixels = pixels1;
644 int n, i;
645 n = size >> 1;
646 for(i = 0; i < n; i++) {
647 vnc_convert_pixel(vs, buf, pixels[i]);
648 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
650 } else if (pf->bytes_per_pixel == 1) {
651 uint8_t *pixels = pixels1;
652 int n, i;
653 n = size;
654 for(i = 0; i < n; i++) {
655 vnc_convert_pixel(vs, buf, pixels[i]);
656 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
658 } else {
659 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
663 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
665 int i;
666 uint8_t *row;
667 VncDisplay *vd = vs->vd;
669 row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
670 for (i = 0; i < h; i++) {
671 vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds));
672 row += ds_get_linesize(vs->ds);
674 return 1;
677 static int send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
679 int n = 0;
681 switch(vs->vnc_encoding) {
682 case VNC_ENCODING_ZLIB:
683 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
684 break;
685 case VNC_ENCODING_HEXTILE:
686 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
687 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
688 break;
689 case VNC_ENCODING_TIGHT:
690 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
691 break;
692 default:
693 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
694 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
695 break;
697 return n;
700 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
702 /* send bitblit op to the vnc client */
703 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
704 vnc_write_u8(vs, 0);
705 vnc_write_u16(vs, 1); /* number of rects */
706 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
707 vnc_write_u16(vs, src_x);
708 vnc_write_u16(vs, src_y);
709 vnc_flush(vs);
712 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
714 VncDisplay *vd = ds->opaque;
715 VncState *vs, *vn;
716 uint8_t *src_row;
717 uint8_t *dst_row;
718 int i,x,y,pitch,depth,inc,w_lim,s;
719 int cmp_bytes;
721 vnc_refresh_server_surface(vd);
722 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
723 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
724 vs->force_update = 1;
725 vnc_update_client(vs, 1);
726 /* vs might be free()ed here */
730 /* do bitblit op on the local surface too */
731 pitch = ds_get_linesize(vd->ds);
732 depth = ds_get_bytes_per_pixel(vd->ds);
733 src_row = vd->server->data + pitch * src_y + depth * src_x;
734 dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
735 y = dst_y;
736 inc = 1;
737 if (dst_y > src_y) {
738 /* copy backwards */
739 src_row += pitch * (h-1);
740 dst_row += pitch * (h-1);
741 pitch = -pitch;
742 y = dst_y + h - 1;
743 inc = -1;
745 w_lim = w - (16 - (dst_x % 16));
746 if (w_lim < 0)
747 w_lim = w;
748 else
749 w_lim = w - (w_lim % 16);
750 for (i = 0; i < h; i++) {
751 for (x = 0; x <= w_lim;
752 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
753 if (x == w_lim) {
754 if ((s = w - w_lim) == 0)
755 break;
756 } else if (!x) {
757 s = (16 - (dst_x % 16));
758 s = MIN(s, w_lim);
759 } else {
760 s = 16;
762 cmp_bytes = s * depth;
763 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
764 continue;
765 memmove(dst_row, src_row, cmp_bytes);
766 QTAILQ_FOREACH(vs, &vd->clients, next) {
767 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
768 vnc_set_bit(vs->dirty[y], ((x + dst_x) / 16));
772 src_row += pitch - w * depth;
773 dst_row += pitch - w * depth;
774 y += inc;
777 QTAILQ_FOREACH(vs, &vd->clients, next) {
778 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
779 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
784 static void vnc_mouse_set(int x, int y, int visible)
786 /* can we ask the client(s) to move the pointer ??? */
789 static int vnc_cursor_define(VncState *vs)
791 QEMUCursor *c = vs->vd->cursor;
792 PixelFormat pf = qemu_default_pixelformat(32);
793 int isize;
795 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
796 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
797 vnc_write_u8(vs, 0); /* padding */
798 vnc_write_u16(vs, 1); /* # of rects */
799 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
800 VNC_ENCODING_RICH_CURSOR);
801 isize = c->width * c->height * vs->clientds.pf.bytes_per_pixel;
802 vnc_write_pixels_generic(vs, &pf, c->data, isize);
803 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
804 return 0;
806 return -1;
809 static void vnc_dpy_cursor_define(QEMUCursor *c)
811 VncDisplay *vd = vnc_display;
812 VncState *vs;
814 cursor_put(vd->cursor);
815 qemu_free(vd->cursor_mask);
817 vd->cursor = c;
818 cursor_get(vd->cursor);
819 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
820 vd->cursor_mask = qemu_mallocz(vd->cursor_msize);
821 cursor_get_mono_mask(c, 0, vd->cursor_mask);
823 QTAILQ_FOREACH(vs, &vd->clients, next) {
824 vnc_cursor_define(vs);
828 static int find_and_clear_dirty_height(struct VncState *vs,
829 int y, int last_x, int x)
831 int h;
832 VncDisplay *vd = vs->vd;
834 for (h = 1; h < (vd->server->height - y); h++) {
835 int tmp_x;
836 if (!vnc_get_bit(vs->dirty[y + h], last_x))
837 break;
838 for (tmp_x = last_x; tmp_x < x; tmp_x++)
839 vnc_clear_bit(vs->dirty[y + h], tmp_x);
842 return h;
845 static int vnc_update_client(VncState *vs, int has_dirty)
847 if (vs->need_update && vs->csock != -1) {
848 VncDisplay *vd = vs->vd;
849 int y;
850 int n_rectangles;
851 int saved_offset;
852 int n;
854 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
855 /* kernel send buffers are full -> drop frames to throttle */
856 return 0;
858 if (!has_dirty && !vs->audio_cap && !vs->force_update)
859 return 0;
862 * Send screen updates to the vnc client using the server
863 * surface and server dirty map. guest surface updates
864 * happening in parallel don't disturb us, the next pass will
865 * send them to the client.
867 n_rectangles = 0;
868 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
869 vnc_write_u8(vs, 0);
870 saved_offset = vs->output.offset;
871 vnc_write_u16(vs, 0);
873 for (y = 0; y < vd->server->height; y++) {
874 int x;
875 int last_x = -1;
876 for (x = 0; x < vd->server->width / 16; x++) {
877 if (vnc_get_bit(vs->dirty[y], x)) {
878 if (last_x == -1) {
879 last_x = x;
881 vnc_clear_bit(vs->dirty[y], x);
882 } else {
883 if (last_x != -1) {
884 int h = find_and_clear_dirty_height(vs, y, last_x, x);
885 n = send_framebuffer_update(vs, last_x * 16, y,
886 (x - last_x) * 16, h);
887 n_rectangles += n;
889 last_x = -1;
892 if (last_x != -1) {
893 int h = find_and_clear_dirty_height(vs, y, last_x, x);
894 n = send_framebuffer_update(vs, last_x * 16, y,
895 (x - last_x) * 16, h);
896 n_rectangles += n;
899 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
900 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
901 vnc_flush(vs);
902 vs->force_update = 0;
903 return n_rectangles;
906 if (vs->csock == -1)
907 vnc_disconnect_finish(vs);
909 return 0;
912 /* audio */
913 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
915 VncState *vs = opaque;
917 switch (cmd) {
918 case AUD_CNOTIFY_DISABLE:
919 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
920 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
921 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
922 vnc_flush(vs);
923 break;
925 case AUD_CNOTIFY_ENABLE:
926 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
927 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
928 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
929 vnc_flush(vs);
930 break;
934 static void audio_capture_destroy(void *opaque)
938 static void audio_capture(void *opaque, void *buf, int size)
940 VncState *vs = opaque;
942 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
943 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
944 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
945 vnc_write_u32(vs, size);
946 vnc_write(vs, buf, size);
947 vnc_flush(vs);
950 static void audio_add(VncState *vs)
952 struct audio_capture_ops ops;
954 if (vs->audio_cap) {
955 monitor_printf(default_mon, "audio already running\n");
956 return;
959 ops.notify = audio_capture_notify;
960 ops.destroy = audio_capture_destroy;
961 ops.capture = audio_capture;
963 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
964 if (!vs->audio_cap) {
965 monitor_printf(default_mon, "Failed to add audio capture\n");
969 static void audio_del(VncState *vs)
971 if (vs->audio_cap) {
972 AUD_del_capture(vs->audio_cap, vs);
973 vs->audio_cap = NULL;
977 static void vnc_disconnect_start(VncState *vs)
979 if (vs->csock == -1)
980 return;
981 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
982 closesocket(vs->csock);
983 vs->csock = -1;
986 static void vnc_disconnect_finish(VncState *vs)
988 vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
990 buffer_free(&vs->input);
991 buffer_free(&vs->output);
993 qobject_decref(vs->info);
995 vnc_zlib_clear(vs);
996 vnc_tight_clear(vs);
998 #ifdef CONFIG_VNC_TLS
999 vnc_tls_client_cleanup(vs);
1000 #endif /* CONFIG_VNC_TLS */
1001 #ifdef CONFIG_VNC_SASL
1002 vnc_sasl_client_cleanup(vs);
1003 #endif /* CONFIG_VNC_SASL */
1004 audio_del(vs);
1006 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1008 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1009 dcl->idle = 1;
1012 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1013 vnc_remove_timer(vs->vd);
1014 if (vs->vd->lock_key_sync)
1015 qemu_remove_led_event_handler(vs->led);
1016 qemu_free(vs);
1019 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1021 if (ret == 0 || ret == -1) {
1022 if (ret == -1) {
1023 switch (last_errno) {
1024 case EINTR:
1025 case EAGAIN:
1026 #ifdef _WIN32
1027 case WSAEWOULDBLOCK:
1028 #endif
1029 return 0;
1030 default:
1031 break;
1035 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1036 ret, ret < 0 ? last_errno : 0);
1037 vnc_disconnect_start(vs);
1039 return 0;
1041 return ret;
1045 void vnc_client_error(VncState *vs)
1047 VNC_DEBUG("Closing down client sock: protocol error\n");
1048 vnc_disconnect_start(vs);
1053 * Called to write a chunk of data to the client socket. The data may
1054 * be the raw data, or may have already been encoded by SASL.
1055 * The data will be written either straight onto the socket, or
1056 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1058 * NB, it is theoretically possible to have 2 layers of encryption,
1059 * both SASL, and this TLS layer. It is highly unlikely in practice
1060 * though, since SASL encryption will typically be a no-op if TLS
1061 * is active
1063 * Returns the number of bytes written, which may be less than
1064 * the requested 'datalen' if the socket would block. Returns
1065 * -1 on error, and disconnects the client socket.
1067 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1069 long ret;
1070 #ifdef CONFIG_VNC_TLS
1071 if (vs->tls.session) {
1072 ret = gnutls_write(vs->tls.session, data, datalen);
1073 if (ret < 0) {
1074 if (ret == GNUTLS_E_AGAIN)
1075 errno = EAGAIN;
1076 else
1077 errno = EIO;
1078 ret = -1;
1080 } else
1081 #endif /* CONFIG_VNC_TLS */
1082 ret = send(vs->csock, (const void *)data, datalen, 0);
1083 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1084 return vnc_client_io_error(vs, ret, socket_error());
1089 * Called to write buffered data to the client socket, when not
1090 * using any SASL SSF encryption layers. Will write as much data
1091 * as possible without blocking. If all buffered data is written,
1092 * will switch the FD poll() handler back to read monitoring.
1094 * Returns the number of bytes written, which may be less than
1095 * the buffered output data if the socket would block. Returns
1096 * -1 on error, and disconnects the client socket.
1098 static long vnc_client_write_plain(VncState *vs)
1100 long ret;
1102 #ifdef CONFIG_VNC_SASL
1103 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1104 vs->output.buffer, vs->output.capacity, vs->output.offset,
1105 vs->sasl.waitWriteSSF);
1107 if (vs->sasl.conn &&
1108 vs->sasl.runSSF &&
1109 vs->sasl.waitWriteSSF) {
1110 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1111 if (ret)
1112 vs->sasl.waitWriteSSF -= ret;
1113 } else
1114 #endif /* CONFIG_VNC_SASL */
1115 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1116 if (!ret)
1117 return 0;
1119 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1120 vs->output.offset -= ret;
1122 if (vs->output.offset == 0) {
1123 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1126 return ret;
1131 * First function called whenever there is data to be written to
1132 * the client socket. Will delegate actual work according to whether
1133 * SASL SSF layers are enabled (thus requiring encryption calls)
1135 void vnc_client_write(void *opaque)
1137 VncState *vs = opaque;
1139 #ifdef CONFIG_VNC_SASL
1140 if (vs->sasl.conn &&
1141 vs->sasl.runSSF &&
1142 !vs->sasl.waitWriteSSF) {
1143 vnc_client_write_sasl(vs);
1144 } else
1145 #endif /* CONFIG_VNC_SASL */
1146 vnc_client_write_plain(vs);
1149 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1151 vs->read_handler = func;
1152 vs->read_handler_expect = expecting;
1157 * Called to read a chunk of data from the client socket. The data may
1158 * be the raw data, or may need to be further decoded by SASL.
1159 * The data will be read either straight from to the socket, or
1160 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1162 * NB, it is theoretically possible to have 2 layers of encryption,
1163 * both SASL, and this TLS layer. It is highly unlikely in practice
1164 * though, since SASL encryption will typically be a no-op if TLS
1165 * is active
1167 * Returns the number of bytes read, which may be less than
1168 * the requested 'datalen' if the socket would block. Returns
1169 * -1 on error, and disconnects the client socket.
1171 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1173 long ret;
1174 #ifdef CONFIG_VNC_TLS
1175 if (vs->tls.session) {
1176 ret = gnutls_read(vs->tls.session, data, datalen);
1177 if (ret < 0) {
1178 if (ret == GNUTLS_E_AGAIN)
1179 errno = EAGAIN;
1180 else
1181 errno = EIO;
1182 ret = -1;
1184 } else
1185 #endif /* CONFIG_VNC_TLS */
1186 ret = recv(vs->csock, (void *)data, datalen, 0);
1187 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1188 return vnc_client_io_error(vs, ret, socket_error());
1193 * Called to read data from the client socket to the input buffer,
1194 * when not using any SASL SSF encryption layers. Will read as much
1195 * data as possible without blocking.
1197 * Returns the number of bytes read. Returns -1 on error, and
1198 * disconnects the client socket.
1200 static long vnc_client_read_plain(VncState *vs)
1202 int ret;
1203 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1204 vs->input.buffer, vs->input.capacity, vs->input.offset);
1205 buffer_reserve(&vs->input, 4096);
1206 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1207 if (!ret)
1208 return 0;
1209 vs->input.offset += ret;
1210 return ret;
1215 * First function called whenever there is more data to be read from
1216 * the client socket. Will delegate actual work according to whether
1217 * SASL SSF layers are enabled (thus requiring decryption calls)
1219 void vnc_client_read(void *opaque)
1221 VncState *vs = opaque;
1222 long ret;
1224 #ifdef CONFIG_VNC_SASL
1225 if (vs->sasl.conn && vs->sasl.runSSF)
1226 ret = vnc_client_read_sasl(vs);
1227 else
1228 #endif /* CONFIG_VNC_SASL */
1229 ret = vnc_client_read_plain(vs);
1230 if (!ret) {
1231 if (vs->csock == -1)
1232 vnc_disconnect_finish(vs);
1233 return;
1236 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1237 size_t len = vs->read_handler_expect;
1238 int ret;
1240 ret = vs->read_handler(vs, vs->input.buffer, len);
1241 if (vs->csock == -1) {
1242 vnc_disconnect_finish(vs);
1243 return;
1246 if (!ret) {
1247 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1248 vs->input.offset -= len;
1249 } else {
1250 vs->read_handler_expect = ret;
1255 void vnc_write(VncState *vs, const void *data, size_t len)
1257 buffer_reserve(&vs->output, len);
1259 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1260 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1263 buffer_append(&vs->output, data, len);
1266 void vnc_write_s32(VncState *vs, int32_t value)
1268 vnc_write_u32(vs, *(uint32_t *)&value);
1271 void vnc_write_u32(VncState *vs, uint32_t value)
1273 uint8_t buf[4];
1275 buf[0] = (value >> 24) & 0xFF;
1276 buf[1] = (value >> 16) & 0xFF;
1277 buf[2] = (value >> 8) & 0xFF;
1278 buf[3] = value & 0xFF;
1280 vnc_write(vs, buf, 4);
1283 void vnc_write_u16(VncState *vs, uint16_t value)
1285 uint8_t buf[2];
1287 buf[0] = (value >> 8) & 0xFF;
1288 buf[1] = value & 0xFF;
1290 vnc_write(vs, buf, 2);
1293 void vnc_write_u8(VncState *vs, uint8_t value)
1295 vnc_write(vs, (char *)&value, 1);
1298 void vnc_flush(VncState *vs)
1300 if (vs->csock != -1 && vs->output.offset)
1301 vnc_client_write(vs);
1304 uint8_t read_u8(uint8_t *data, size_t offset)
1306 return data[offset];
1309 uint16_t read_u16(uint8_t *data, size_t offset)
1311 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1314 int32_t read_s32(uint8_t *data, size_t offset)
1316 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1317 (data[offset + 2] << 8) | data[offset + 3]);
1320 uint32_t read_u32(uint8_t *data, size_t offset)
1322 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1323 (data[offset + 2] << 8) | data[offset + 3]);
1326 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1330 static void check_pointer_type_change(Notifier *notifier)
1332 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1333 int absolute = kbd_mouse_is_absolute();
1335 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1336 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1337 vnc_write_u8(vs, 0);
1338 vnc_write_u16(vs, 1);
1339 vnc_framebuffer_update(vs, absolute, 0,
1340 ds_get_width(vs->ds), ds_get_height(vs->ds),
1341 VNC_ENCODING_POINTER_TYPE_CHANGE);
1342 vnc_flush(vs);
1344 vs->absolute = absolute;
1347 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1349 int buttons = 0;
1350 int dz = 0;
1352 if (button_mask & 0x01)
1353 buttons |= MOUSE_EVENT_LBUTTON;
1354 if (button_mask & 0x02)
1355 buttons |= MOUSE_EVENT_MBUTTON;
1356 if (button_mask & 0x04)
1357 buttons |= MOUSE_EVENT_RBUTTON;
1358 if (button_mask & 0x08)
1359 dz = -1;
1360 if (button_mask & 0x10)
1361 dz = 1;
1363 if (vs->absolute) {
1364 kbd_mouse_event(ds_get_width(vs->ds) > 1 ?
1365 x * 0x7FFF / (ds_get_width(vs->ds) - 1) : 0x4000,
1366 ds_get_height(vs->ds) > 1 ?
1367 y * 0x7FFF / (ds_get_height(vs->ds) - 1) : 0x4000,
1368 dz, buttons);
1369 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1370 x -= 0x7FFF;
1371 y -= 0x7FFF;
1373 kbd_mouse_event(x, y, dz, buttons);
1374 } else {
1375 if (vs->last_x != -1)
1376 kbd_mouse_event(x - vs->last_x,
1377 y - vs->last_y,
1378 dz, buttons);
1379 vs->last_x = x;
1380 vs->last_y = y;
1384 static void reset_keys(VncState *vs)
1386 int i;
1387 for(i = 0; i < 256; i++) {
1388 if (vs->modifiers_state[i]) {
1389 if (i & SCANCODE_GREY)
1390 kbd_put_keycode(SCANCODE_EMUL0);
1391 kbd_put_keycode(i | SCANCODE_UP);
1392 vs->modifiers_state[i] = 0;
1397 static void press_key(VncState *vs, int keysym)
1399 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1400 if (keycode & SCANCODE_GREY)
1401 kbd_put_keycode(SCANCODE_EMUL0);
1402 kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1403 if (keycode & SCANCODE_GREY)
1404 kbd_put_keycode(SCANCODE_EMUL0);
1405 kbd_put_keycode(keycode | SCANCODE_UP);
1408 static void kbd_leds(void *opaque, int ledstate)
1410 VncState *vs = opaque;
1411 int caps, num;
1413 caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1414 num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
1416 if (vs->modifiers_state[0x3a] != caps) {
1417 vs->modifiers_state[0x3a] = caps;
1419 if (vs->modifiers_state[0x45] != num) {
1420 vs->modifiers_state[0x45] = num;
1424 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1426 /* QEMU console switch */
1427 switch(keycode) {
1428 case 0x2a: /* Left Shift */
1429 case 0x36: /* Right Shift */
1430 case 0x1d: /* Left CTRL */
1431 case 0x9d: /* Right CTRL */
1432 case 0x38: /* Left ALT */
1433 case 0xb8: /* Right ALT */
1434 if (down)
1435 vs->modifiers_state[keycode] = 1;
1436 else
1437 vs->modifiers_state[keycode] = 0;
1438 break;
1439 case 0x02 ... 0x0a: /* '1' to '9' keys */
1440 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1441 /* Reset the modifiers sent to the current console */
1442 reset_keys(vs);
1443 console_select(keycode - 0x02);
1444 return;
1446 break;
1447 case 0x3a: /* CapsLock */
1448 case 0x45: /* NumLock */
1449 if (down)
1450 vs->modifiers_state[keycode] ^= 1;
1451 break;
1454 if (vs->vd->lock_key_sync &&
1455 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1456 /* If the numlock state needs to change then simulate an additional
1457 keypress before sending this one. This will happen if the user
1458 toggles numlock away from the VNC window.
1460 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1461 if (!vs->modifiers_state[0x45]) {
1462 vs->modifiers_state[0x45] = 1;
1463 press_key(vs, 0xff7f);
1465 } else {
1466 if (vs->modifiers_state[0x45]) {
1467 vs->modifiers_state[0x45] = 0;
1468 press_key(vs, 0xff7f);
1473 if (vs->vd->lock_key_sync &&
1474 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1475 /* If the capslock state needs to change then simulate an additional
1476 keypress before sending this one. This will happen if the user
1477 toggles capslock away from the VNC window.
1479 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1480 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1481 int capslock = !!(vs->modifiers_state[0x3a]);
1482 if (capslock) {
1483 if (uppercase == shift) {
1484 vs->modifiers_state[0x3a] = 0;
1485 press_key(vs, 0xffe5);
1487 } else {
1488 if (uppercase != shift) {
1489 vs->modifiers_state[0x3a] = 1;
1490 press_key(vs, 0xffe5);
1495 if (is_graphic_console()) {
1496 if (keycode & SCANCODE_GREY)
1497 kbd_put_keycode(SCANCODE_EMUL0);
1498 if (down)
1499 kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1500 else
1501 kbd_put_keycode(keycode | SCANCODE_UP);
1502 } else {
1503 /* QEMU console emulation */
1504 if (down) {
1505 int numlock = vs->modifiers_state[0x45];
1506 switch (keycode) {
1507 case 0x2a: /* Left Shift */
1508 case 0x36: /* Right Shift */
1509 case 0x1d: /* Left CTRL */
1510 case 0x9d: /* Right CTRL */
1511 case 0x38: /* Left ALT */
1512 case 0xb8: /* Right ALT */
1513 break;
1514 case 0xc8:
1515 kbd_put_keysym(QEMU_KEY_UP);
1516 break;
1517 case 0xd0:
1518 kbd_put_keysym(QEMU_KEY_DOWN);
1519 break;
1520 case 0xcb:
1521 kbd_put_keysym(QEMU_KEY_LEFT);
1522 break;
1523 case 0xcd:
1524 kbd_put_keysym(QEMU_KEY_RIGHT);
1525 break;
1526 case 0xd3:
1527 kbd_put_keysym(QEMU_KEY_DELETE);
1528 break;
1529 case 0xc7:
1530 kbd_put_keysym(QEMU_KEY_HOME);
1531 break;
1532 case 0xcf:
1533 kbd_put_keysym(QEMU_KEY_END);
1534 break;
1535 case 0xc9:
1536 kbd_put_keysym(QEMU_KEY_PAGEUP);
1537 break;
1538 case 0xd1:
1539 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1540 break;
1542 case 0x47:
1543 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1544 break;
1545 case 0x48:
1546 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1547 break;
1548 case 0x49:
1549 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1550 break;
1551 case 0x4b:
1552 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1553 break;
1554 case 0x4c:
1555 kbd_put_keysym('5');
1556 break;
1557 case 0x4d:
1558 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1559 break;
1560 case 0x4f:
1561 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1562 break;
1563 case 0x50:
1564 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1565 break;
1566 case 0x51:
1567 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1568 break;
1569 case 0x52:
1570 kbd_put_keysym('0');
1571 break;
1572 case 0x53:
1573 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1574 break;
1576 case 0xb5:
1577 kbd_put_keysym('/');
1578 break;
1579 case 0x37:
1580 kbd_put_keysym('*');
1581 break;
1582 case 0x4a:
1583 kbd_put_keysym('-');
1584 break;
1585 case 0x4e:
1586 kbd_put_keysym('+');
1587 break;
1588 case 0x9c:
1589 kbd_put_keysym('\n');
1590 break;
1592 default:
1593 kbd_put_keysym(sym);
1594 break;
1600 static void key_event(VncState *vs, int down, uint32_t sym)
1602 int keycode;
1603 int lsym = sym;
1605 if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1606 lsym = lsym - 'A' + 'a';
1609 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1610 do_key_event(vs, down, keycode, sym);
1613 static void ext_key_event(VncState *vs, int down,
1614 uint32_t sym, uint16_t keycode)
1616 /* if the user specifies a keyboard layout, always use it */
1617 if (keyboard_layout)
1618 key_event(vs, down, sym);
1619 else
1620 do_key_event(vs, down, keycode, sym);
1623 static void framebuffer_update_request(VncState *vs, int incremental,
1624 int x_position, int y_position,
1625 int w, int h)
1627 if (y_position > ds_get_height(vs->ds))
1628 y_position = ds_get_height(vs->ds);
1629 if (y_position + h >= ds_get_height(vs->ds))
1630 h = ds_get_height(vs->ds) - y_position;
1632 int i;
1633 vs->need_update = 1;
1634 if (!incremental) {
1635 vs->force_update = 1;
1636 for (i = 0; i < h; i++) {
1637 vnc_set_bits(vs->dirty[y_position + i],
1638 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1643 static void send_ext_key_event_ack(VncState *vs)
1645 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1646 vnc_write_u8(vs, 0);
1647 vnc_write_u16(vs, 1);
1648 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1649 VNC_ENCODING_EXT_KEY_EVENT);
1650 vnc_flush(vs);
1653 static void send_ext_audio_ack(VncState *vs)
1655 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1656 vnc_write_u8(vs, 0);
1657 vnc_write_u16(vs, 1);
1658 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1659 VNC_ENCODING_AUDIO);
1660 vnc_flush(vs);
1663 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1665 int i;
1666 unsigned int enc = 0;
1668 vs->features = 0;
1669 vs->vnc_encoding = 0;
1670 vs->tight_compression = 9;
1671 vs->tight_quality = 9;
1672 vs->absolute = -1;
1675 * Start from the end because the encodings are sent in order of preference.
1676 * This way the prefered encoding (first encoding defined in the array)
1677 * will be set at the end of the loop.
1679 for (i = n_encodings - 1; i >= 0; i--) {
1680 enc = encodings[i];
1681 switch (enc) {
1682 case VNC_ENCODING_RAW:
1683 vs->vnc_encoding = enc;
1684 break;
1685 case VNC_ENCODING_COPYRECT:
1686 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1687 break;
1688 case VNC_ENCODING_HEXTILE:
1689 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1690 vs->vnc_encoding = enc;
1691 break;
1692 case VNC_ENCODING_TIGHT:
1693 vs->features |= VNC_FEATURE_TIGHT_MASK;
1694 vs->vnc_encoding = enc;
1695 break;
1696 case VNC_ENCODING_ZLIB:
1697 vs->features |= VNC_FEATURE_ZLIB_MASK;
1698 vs->vnc_encoding = enc;
1699 break;
1700 case VNC_ENCODING_DESKTOPRESIZE:
1701 vs->features |= VNC_FEATURE_RESIZE_MASK;
1702 break;
1703 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1704 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1705 break;
1706 case VNC_ENCODING_RICH_CURSOR:
1707 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1708 break;
1709 case VNC_ENCODING_EXT_KEY_EVENT:
1710 send_ext_key_event_ack(vs);
1711 break;
1712 case VNC_ENCODING_AUDIO:
1713 send_ext_audio_ack(vs);
1714 break;
1715 case VNC_ENCODING_WMVi:
1716 vs->features |= VNC_FEATURE_WMVI_MASK;
1717 break;
1718 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1719 vs->tight_compression = (enc & 0x0F);
1720 break;
1721 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1722 vs->tight_quality = (enc & 0x0F);
1723 break;
1724 default:
1725 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1726 break;
1729 check_pointer_type_change(&vs->mouse_mode_notifier);
1732 static void set_pixel_conversion(VncState *vs)
1734 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1735 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1736 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1737 vs->write_pixels = vnc_write_pixels_copy;
1738 vnc_hextile_set_pixel_conversion(vs, 0);
1739 } else {
1740 vs->write_pixels = vnc_write_pixels_generic;
1741 vnc_hextile_set_pixel_conversion(vs, 1);
1745 static void set_pixel_format(VncState *vs,
1746 int bits_per_pixel, int depth,
1747 int big_endian_flag, int true_color_flag,
1748 int red_max, int green_max, int blue_max,
1749 int red_shift, int green_shift, int blue_shift)
1751 if (!true_color_flag) {
1752 vnc_client_error(vs);
1753 return;
1756 vs->clientds = *(vs->vd->guest.ds);
1757 vs->clientds.pf.rmax = red_max;
1758 count_bits(vs->clientds.pf.rbits, red_max);
1759 vs->clientds.pf.rshift = red_shift;
1760 vs->clientds.pf.rmask = red_max << red_shift;
1761 vs->clientds.pf.gmax = green_max;
1762 count_bits(vs->clientds.pf.gbits, green_max);
1763 vs->clientds.pf.gshift = green_shift;
1764 vs->clientds.pf.gmask = green_max << green_shift;
1765 vs->clientds.pf.bmax = blue_max;
1766 count_bits(vs->clientds.pf.bbits, blue_max);
1767 vs->clientds.pf.bshift = blue_shift;
1768 vs->clientds.pf.bmask = blue_max << blue_shift;
1769 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1770 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1771 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1772 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1774 set_pixel_conversion(vs);
1776 vga_hw_invalidate();
1777 vga_hw_update();
1780 static void pixel_format_message (VncState *vs) {
1781 char pad[3] = { 0, 0, 0 };
1783 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1784 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1786 #ifdef HOST_WORDS_BIGENDIAN
1787 vnc_write_u8(vs, 1); /* big-endian-flag */
1788 #else
1789 vnc_write_u8(vs, 0); /* big-endian-flag */
1790 #endif
1791 vnc_write_u8(vs, 1); /* true-color-flag */
1792 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1793 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1794 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1795 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1796 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1797 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1799 vnc_hextile_set_pixel_conversion(vs, 0);
1801 vs->clientds = *(vs->ds->surface);
1802 vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1803 vs->write_pixels = vnc_write_pixels_copy;
1805 vnc_write(vs, pad, 3); /* padding */
1808 static void vnc_dpy_setdata(DisplayState *ds)
1810 /* We don't have to do anything */
1813 static void vnc_colordepth(VncState *vs)
1815 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1816 /* Sending a WMVi message to notify the client*/
1817 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1818 vnc_write_u8(vs, 0);
1819 vnc_write_u16(vs, 1); /* number of rects */
1820 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1821 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1822 pixel_format_message(vs);
1823 vnc_flush(vs);
1824 } else {
1825 set_pixel_conversion(vs);
1829 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1831 int i;
1832 uint16_t limit;
1833 VncDisplay *vd = vs->vd;
1835 if (data[0] > 3) {
1836 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1837 if (!qemu_timer_expired(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval))
1838 qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
1841 switch (data[0]) {
1842 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
1843 if (len == 1)
1844 return 20;
1846 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1847 read_u8(data, 6), read_u8(data, 7),
1848 read_u16(data, 8), read_u16(data, 10),
1849 read_u16(data, 12), read_u8(data, 14),
1850 read_u8(data, 15), read_u8(data, 16));
1851 break;
1852 case VNC_MSG_CLIENT_SET_ENCODINGS:
1853 if (len == 1)
1854 return 4;
1856 if (len == 4) {
1857 limit = read_u16(data, 2);
1858 if (limit > 0)
1859 return 4 + (limit * 4);
1860 } else
1861 limit = read_u16(data, 2);
1863 for (i = 0; i < limit; i++) {
1864 int32_t val = read_s32(data, 4 + (i * 4));
1865 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1868 set_encodings(vs, (int32_t *)(data + 4), limit);
1869 break;
1870 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
1871 if (len == 1)
1872 return 10;
1874 framebuffer_update_request(vs,
1875 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1876 read_u16(data, 6), read_u16(data, 8));
1877 break;
1878 case VNC_MSG_CLIENT_KEY_EVENT:
1879 if (len == 1)
1880 return 8;
1882 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1883 break;
1884 case VNC_MSG_CLIENT_POINTER_EVENT:
1885 if (len == 1)
1886 return 6;
1888 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1889 break;
1890 case VNC_MSG_CLIENT_CUT_TEXT:
1891 if (len == 1)
1892 return 8;
1894 if (len == 8) {
1895 uint32_t dlen = read_u32(data, 4);
1896 if (dlen > 0)
1897 return 8 + dlen;
1900 client_cut_text(vs, read_u32(data, 4), data + 8);
1901 break;
1902 case VNC_MSG_CLIENT_QEMU:
1903 if (len == 1)
1904 return 2;
1906 switch (read_u8(data, 1)) {
1907 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
1908 if (len == 2)
1909 return 12;
1911 ext_key_event(vs, read_u16(data, 2),
1912 read_u32(data, 4), read_u32(data, 8));
1913 break;
1914 case VNC_MSG_CLIENT_QEMU_AUDIO:
1915 if (len == 2)
1916 return 4;
1918 switch (read_u16 (data, 2)) {
1919 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
1920 audio_add(vs);
1921 break;
1922 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
1923 audio_del(vs);
1924 break;
1925 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
1926 if (len == 4)
1927 return 10;
1928 switch (read_u8(data, 4)) {
1929 case 0: vs->as.fmt = AUD_FMT_U8; break;
1930 case 1: vs->as.fmt = AUD_FMT_S8; break;
1931 case 2: vs->as.fmt = AUD_FMT_U16; break;
1932 case 3: vs->as.fmt = AUD_FMT_S16; break;
1933 case 4: vs->as.fmt = AUD_FMT_U32; break;
1934 case 5: vs->as.fmt = AUD_FMT_S32; break;
1935 default:
1936 printf("Invalid audio format %d\n", read_u8(data, 4));
1937 vnc_client_error(vs);
1938 break;
1940 vs->as.nchannels = read_u8(data, 5);
1941 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1942 printf("Invalid audio channel coount %d\n",
1943 read_u8(data, 5));
1944 vnc_client_error(vs);
1945 break;
1947 vs->as.freq = read_u32(data, 6);
1948 break;
1949 default:
1950 printf ("Invalid audio message %d\n", read_u8(data, 4));
1951 vnc_client_error(vs);
1952 break;
1954 break;
1956 default:
1957 printf("Msg: %d\n", read_u16(data, 0));
1958 vnc_client_error(vs);
1959 break;
1961 break;
1962 default:
1963 printf("Msg: %d\n", data[0]);
1964 vnc_client_error(vs);
1965 break;
1968 vnc_read_when(vs, protocol_client_msg, 1);
1969 return 0;
1972 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1974 char buf[1024];
1975 int size;
1977 vnc_write_u16(vs, ds_get_width(vs->ds));
1978 vnc_write_u16(vs, ds_get_height(vs->ds));
1980 pixel_format_message(vs);
1982 if (qemu_name)
1983 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1984 else
1985 size = snprintf(buf, sizeof(buf), "QEMU");
1987 vnc_write_u32(vs, size);
1988 vnc_write(vs, buf, size);
1989 vnc_flush(vs);
1991 vnc_client_cache_auth(vs);
1992 vnc_qmp_event(vs, QEVENT_VNC_INITIALIZED);
1994 vnc_read_when(vs, protocol_client_msg, 1);
1996 return 0;
1999 void start_client_init(VncState *vs)
2001 vnc_read_when(vs, protocol_client_init, 1);
2004 static void make_challenge(VncState *vs)
2006 int i;
2008 srand(time(NULL)+getpid()+getpid()*987654+rand());
2010 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2011 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2014 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2016 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2017 int i, j, pwlen;
2018 unsigned char key[8];
2020 if (!vs->vd->password || !vs->vd->password[0]) {
2021 VNC_DEBUG("No password configured on server");
2022 vnc_write_u32(vs, 1); /* Reject auth */
2023 if (vs->minor >= 8) {
2024 static const char err[] = "Authentication failed";
2025 vnc_write_u32(vs, sizeof(err));
2026 vnc_write(vs, err, sizeof(err));
2028 vnc_flush(vs);
2029 vnc_client_error(vs);
2030 return 0;
2033 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2035 /* Calculate the expected challenge response */
2036 pwlen = strlen(vs->vd->password);
2037 for (i=0; i<sizeof(key); i++)
2038 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2039 deskey(key, EN0);
2040 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2041 des(response+j, response+j);
2043 /* Compare expected vs actual challenge response */
2044 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2045 VNC_DEBUG("Client challenge reponse did not match\n");
2046 vnc_write_u32(vs, 1); /* Reject auth */
2047 if (vs->minor >= 8) {
2048 static const char err[] = "Authentication failed";
2049 vnc_write_u32(vs, sizeof(err));
2050 vnc_write(vs, err, sizeof(err));
2052 vnc_flush(vs);
2053 vnc_client_error(vs);
2054 } else {
2055 VNC_DEBUG("Accepting VNC challenge response\n");
2056 vnc_write_u32(vs, 0); /* Accept auth */
2057 vnc_flush(vs);
2059 start_client_init(vs);
2061 return 0;
2064 void start_auth_vnc(VncState *vs)
2066 make_challenge(vs);
2067 /* Send client a 'random' challenge */
2068 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2069 vnc_flush(vs);
2071 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2075 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2077 /* We only advertise 1 auth scheme at a time, so client
2078 * must pick the one we sent. Verify this */
2079 if (data[0] != vs->vd->auth) { /* Reject auth */
2080 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2081 vnc_write_u32(vs, 1);
2082 if (vs->minor >= 8) {
2083 static const char err[] = "Authentication failed";
2084 vnc_write_u32(vs, sizeof(err));
2085 vnc_write(vs, err, sizeof(err));
2087 vnc_client_error(vs);
2088 } else { /* Accept requested auth */
2089 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2090 switch (vs->vd->auth) {
2091 case VNC_AUTH_NONE:
2092 VNC_DEBUG("Accept auth none\n");
2093 if (vs->minor >= 8) {
2094 vnc_write_u32(vs, 0); /* Accept auth completion */
2095 vnc_flush(vs);
2097 start_client_init(vs);
2098 break;
2100 case VNC_AUTH_VNC:
2101 VNC_DEBUG("Start VNC auth\n");
2102 start_auth_vnc(vs);
2103 break;
2105 #ifdef CONFIG_VNC_TLS
2106 case VNC_AUTH_VENCRYPT:
2107 VNC_DEBUG("Accept VeNCrypt auth\n");;
2108 start_auth_vencrypt(vs);
2109 break;
2110 #endif /* CONFIG_VNC_TLS */
2112 #ifdef CONFIG_VNC_SASL
2113 case VNC_AUTH_SASL:
2114 VNC_DEBUG("Accept SASL auth\n");
2115 start_auth_sasl(vs);
2116 break;
2117 #endif /* CONFIG_VNC_SASL */
2119 default: /* Should not be possible, but just in case */
2120 VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
2121 vnc_write_u8(vs, 1);
2122 if (vs->minor >= 8) {
2123 static const char err[] = "Authentication failed";
2124 vnc_write_u32(vs, sizeof(err));
2125 vnc_write(vs, err, sizeof(err));
2127 vnc_client_error(vs);
2130 return 0;
2133 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2135 char local[13];
2137 memcpy(local, version, 12);
2138 local[12] = 0;
2140 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2141 VNC_DEBUG("Malformed protocol version %s\n", local);
2142 vnc_client_error(vs);
2143 return 0;
2145 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2146 if (vs->major != 3 ||
2147 (vs->minor != 3 &&
2148 vs->minor != 4 &&
2149 vs->minor != 5 &&
2150 vs->minor != 7 &&
2151 vs->minor != 8)) {
2152 VNC_DEBUG("Unsupported client version\n");
2153 vnc_write_u32(vs, VNC_AUTH_INVALID);
2154 vnc_flush(vs);
2155 vnc_client_error(vs);
2156 return 0;
2158 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2159 * as equivalent to v3.3 by servers
2161 if (vs->minor == 4 || vs->minor == 5)
2162 vs->minor = 3;
2164 if (vs->minor == 3) {
2165 if (vs->vd->auth == VNC_AUTH_NONE) {
2166 VNC_DEBUG("Tell client auth none\n");
2167 vnc_write_u32(vs, vs->vd->auth);
2168 vnc_flush(vs);
2169 start_client_init(vs);
2170 } else if (vs->vd->auth == VNC_AUTH_VNC) {
2171 VNC_DEBUG("Tell client VNC auth\n");
2172 vnc_write_u32(vs, vs->vd->auth);
2173 vnc_flush(vs);
2174 start_auth_vnc(vs);
2175 } else {
2176 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2177 vnc_write_u32(vs, VNC_AUTH_INVALID);
2178 vnc_flush(vs);
2179 vnc_client_error(vs);
2181 } else {
2182 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2183 vnc_write_u8(vs, 1); /* num auth */
2184 vnc_write_u8(vs, vs->vd->auth);
2185 vnc_read_when(vs, protocol_client_auth, 1);
2186 vnc_flush(vs);
2189 return 0;
2192 static int vnc_refresh_server_surface(VncDisplay *vd)
2194 int y;
2195 uint8_t *guest_row;
2196 uint8_t *server_row;
2197 int cmp_bytes;
2198 uint32_t width_mask[VNC_DIRTY_WORDS];
2199 VncState *vs;
2200 int has_dirty = 0;
2203 * Walk through the guest dirty map.
2204 * Check and copy modified bits from guest to server surface.
2205 * Update server dirty map.
2207 vnc_set_bits(width_mask, (ds_get_width(vd->ds) / 16), VNC_DIRTY_WORDS);
2208 cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2209 guest_row = vd->guest.ds->data;
2210 server_row = vd->server->data;
2211 for (y = 0; y < vd->guest.ds->height; y++) {
2212 if (vnc_and_bits(vd->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
2213 int x;
2214 uint8_t *guest_ptr;
2215 uint8_t *server_ptr;
2217 guest_ptr = guest_row;
2218 server_ptr = server_row;
2220 for (x = 0; x < vd->guest.ds->width;
2221 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2222 if (!vnc_get_bit(vd->guest.dirty[y], (x / 16)))
2223 continue;
2224 vnc_clear_bit(vd->guest.dirty[y], (x / 16));
2225 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2226 continue;
2227 memcpy(server_ptr, guest_ptr, cmp_bytes);
2228 QTAILQ_FOREACH(vs, &vd->clients, next) {
2229 vnc_set_bit(vs->dirty[y], (x / 16));
2231 has_dirty++;
2234 guest_row += ds_get_linesize(vd->ds);
2235 server_row += ds_get_linesize(vd->ds);
2237 return has_dirty;
2240 static void vnc_refresh(void *opaque)
2242 VncDisplay *vd = opaque;
2243 VncState *vs, *vn;
2244 int has_dirty, rects = 0;
2246 vga_hw_update();
2248 has_dirty = vnc_refresh_server_surface(vd);
2250 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2251 rects += vnc_update_client(vs, has_dirty);
2252 /* vs might be free()ed here */
2254 /* vd->timer could be NULL now if the last client disconnected,
2255 * in this case don't update the timer */
2256 if (vd->timer == NULL)
2257 return;
2259 if (has_dirty && rects) {
2260 vd->timer_interval /= 2;
2261 if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2262 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2263 } else {
2264 vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2265 if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2266 vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2268 qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
2271 static void vnc_init_timer(VncDisplay *vd)
2273 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2274 if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {
2275 vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
2276 vnc_refresh(vd);
2280 static void vnc_remove_timer(VncDisplay *vd)
2282 if (vd->timer != NULL && QTAILQ_EMPTY(&vd->clients)) {
2283 qemu_del_timer(vd->timer);
2284 qemu_free_timer(vd->timer);
2285 vd->timer = NULL;
2289 static void vnc_connect(VncDisplay *vd, int csock)
2291 VncState *vs = qemu_mallocz(sizeof(VncState));
2292 vs->csock = csock;
2294 VNC_DEBUG("New client on socket %d\n", csock);
2295 dcl->idle = 0;
2296 socket_set_nonblock(vs->csock);
2297 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2299 vnc_client_cache_addr(vs);
2300 vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
2302 vs->vd = vd;
2303 vs->ds = vd->ds;
2304 vs->last_x = -1;
2305 vs->last_y = -1;
2307 vs->as.freq = 44100;
2308 vs->as.nchannels = 2;
2309 vs->as.fmt = AUD_FMT_S16;
2310 vs->as.endianness = 0;
2312 QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2314 vga_hw_update();
2316 vnc_write(vs, "RFB 003.008\n", 12);
2317 vnc_flush(vs);
2318 vnc_read_when(vs, protocol_version, 12);
2319 reset_keys(vs);
2320 if (vs->vd->lock_key_sync)
2321 vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2323 vs->mouse_mode_notifier.notify = check_pointer_type_change;
2324 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2326 vnc_init_timer(vd);
2328 /* vs might be free()ed here */
2331 static void vnc_listen_read(void *opaque)
2333 VncDisplay *vs = opaque;
2334 struct sockaddr_in addr;
2335 socklen_t addrlen = sizeof(addr);
2337 /* Catch-up */
2338 vga_hw_update();
2340 int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2341 if (csock != -1) {
2342 vnc_connect(vs, csock);
2346 void vnc_display_init(DisplayState *ds)
2348 VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2350 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2352 ds->opaque = vs;
2353 dcl->idle = 1;
2354 vnc_display = vs;
2356 vs->lsock = -1;
2358 vs->ds = ds;
2359 QTAILQ_INIT(&vs->clients);
2361 if (keyboard_layout)
2362 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2363 else
2364 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2366 if (!vs->kbd_layout)
2367 exit(1);
2369 dcl->dpy_copy = vnc_dpy_copy;
2370 dcl->dpy_update = vnc_dpy_update;
2371 dcl->dpy_resize = vnc_dpy_resize;
2372 dcl->dpy_setdata = vnc_dpy_setdata;
2373 register_displaychangelistener(ds, dcl);
2374 ds->mouse_set = vnc_mouse_set;
2375 ds->cursor_define = vnc_dpy_cursor_define;
2379 void vnc_display_close(DisplayState *ds)
2381 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2383 if (!vs)
2384 return;
2385 if (vs->display) {
2386 qemu_free(vs->display);
2387 vs->display = NULL;
2389 if (vs->lsock != -1) {
2390 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2391 close(vs->lsock);
2392 vs->lsock = -1;
2394 vs->auth = VNC_AUTH_INVALID;
2395 #ifdef CONFIG_VNC_TLS
2396 vs->subauth = VNC_AUTH_INVALID;
2397 vs->tls.x509verify = 0;
2398 #endif
2401 int vnc_display_password(DisplayState *ds, const char *password)
2403 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2405 if (!vs) {
2406 return -1;
2409 if (vs->password) {
2410 qemu_free(vs->password);
2411 vs->password = NULL;
2413 if (password && password[0]) {
2414 if (!(vs->password = qemu_strdup(password)))
2415 return -1;
2416 if (vs->auth == VNC_AUTH_NONE) {
2417 vs->auth = VNC_AUTH_VNC;
2419 } else {
2420 vs->auth = VNC_AUTH_NONE;
2423 return 0;
2426 char *vnc_display_local_addr(DisplayState *ds)
2428 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2430 return vnc_socket_local_addr("%s:%s", vs->lsock);
2433 int vnc_display_open(DisplayState *ds, const char *display)
2435 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2436 const char *options;
2437 int password = 0;
2438 int reverse = 0;
2439 #ifdef CONFIG_VNC_TLS
2440 int tls = 0, x509 = 0;
2441 #endif
2442 #ifdef CONFIG_VNC_SASL
2443 int sasl = 0;
2444 int saslErr;
2445 #endif
2446 int acl = 0;
2447 int lock_key_sync = 1;
2449 if (!vnc_display)
2450 return -1;
2451 vnc_display_close(ds);
2452 if (strcmp(display, "none") == 0)
2453 return 0;
2455 if (!(vs->display = strdup(display)))
2456 return -1;
2458 options = display;
2459 while ((options = strchr(options, ','))) {
2460 options++;
2461 if (strncmp(options, "password", 8) == 0) {
2462 password = 1; /* Require password auth */
2463 } else if (strncmp(options, "reverse", 7) == 0) {
2464 reverse = 1;
2465 } else if (strncmp(options, "no-lock-key-sync", 9) == 0) {
2466 lock_key_sync = 0;
2467 #ifdef CONFIG_VNC_SASL
2468 } else if (strncmp(options, "sasl", 4) == 0) {
2469 sasl = 1; /* Require SASL auth */
2470 #endif
2471 #ifdef CONFIG_VNC_TLS
2472 } else if (strncmp(options, "tls", 3) == 0) {
2473 tls = 1; /* Require TLS */
2474 } else if (strncmp(options, "x509", 4) == 0) {
2475 char *start, *end;
2476 x509 = 1; /* Require x509 certificates */
2477 if (strncmp(options, "x509verify", 10) == 0)
2478 vs->tls.x509verify = 1; /* ...and verify client certs */
2480 /* Now check for 'x509=/some/path' postfix
2481 * and use that to setup x509 certificate/key paths */
2482 start = strchr(options, '=');
2483 end = strchr(options, ',');
2484 if (start && (!end || (start < end))) {
2485 int len = end ? end-(start+1) : strlen(start+1);
2486 char *path = qemu_strndup(start + 1, len);
2488 VNC_DEBUG("Trying certificate path '%s'\n", path);
2489 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2490 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2491 qemu_free(path);
2492 qemu_free(vs->display);
2493 vs->display = NULL;
2494 return -1;
2496 qemu_free(path);
2497 } else {
2498 fprintf(stderr, "No certificate path provided\n");
2499 qemu_free(vs->display);
2500 vs->display = NULL;
2501 return -1;
2503 #endif
2504 } else if (strncmp(options, "acl", 3) == 0) {
2505 acl = 1;
2509 #ifdef CONFIG_VNC_TLS
2510 if (acl && x509 && vs->tls.x509verify) {
2511 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2512 fprintf(stderr, "Failed to create x509 dname ACL\n");
2513 exit(1);
2516 #endif
2517 #ifdef CONFIG_VNC_SASL
2518 if (acl && sasl) {
2519 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2520 fprintf(stderr, "Failed to create username ACL\n");
2521 exit(1);
2524 #endif
2527 * Combinations we support here:
2529 * - no-auth (clear text, no auth)
2530 * - password (clear text, weak auth)
2531 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
2532 * - tls (encrypt, weak anonymous creds, no auth)
2533 * - tls + password (encrypt, weak anonymous creds, weak auth)
2534 * - tls + sasl (encrypt, weak anonymous creds, good auth)
2535 * - tls + x509 (encrypt, good x509 creds, no auth)
2536 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
2537 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
2539 * NB1. TLS is a stackable auth scheme.
2540 * NB2. the x509 schemes have option to validate a client cert dname
2542 if (password) {
2543 #ifdef CONFIG_VNC_TLS
2544 if (tls) {
2545 vs->auth = VNC_AUTH_VENCRYPT;
2546 if (x509) {
2547 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2548 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2549 } else {
2550 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2551 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2553 } else {
2554 #endif /* CONFIG_VNC_TLS */
2555 VNC_DEBUG("Initializing VNC server with password auth\n");
2556 vs->auth = VNC_AUTH_VNC;
2557 #ifdef CONFIG_VNC_TLS
2558 vs->subauth = VNC_AUTH_INVALID;
2560 #endif /* CONFIG_VNC_TLS */
2561 #ifdef CONFIG_VNC_SASL
2562 } else if (sasl) {
2563 #ifdef CONFIG_VNC_TLS
2564 if (tls) {
2565 vs->auth = VNC_AUTH_VENCRYPT;
2566 if (x509) {
2567 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2568 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2569 } else {
2570 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2571 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2573 } else {
2574 #endif /* CONFIG_VNC_TLS */
2575 VNC_DEBUG("Initializing VNC server with SASL auth\n");
2576 vs->auth = VNC_AUTH_SASL;
2577 #ifdef CONFIG_VNC_TLS
2578 vs->subauth = VNC_AUTH_INVALID;
2580 #endif /* CONFIG_VNC_TLS */
2581 #endif /* CONFIG_VNC_SASL */
2582 } else {
2583 #ifdef CONFIG_VNC_TLS
2584 if (tls) {
2585 vs->auth = VNC_AUTH_VENCRYPT;
2586 if (x509) {
2587 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2588 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2589 } else {
2590 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2591 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2593 } else {
2594 #endif
2595 VNC_DEBUG("Initializing VNC server with no auth\n");
2596 vs->auth = VNC_AUTH_NONE;
2597 #ifdef CONFIG_VNC_TLS
2598 vs->subauth = VNC_AUTH_INVALID;
2600 #endif
2603 #ifdef CONFIG_VNC_SASL
2604 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2605 fprintf(stderr, "Failed to initialize SASL auth %s",
2606 sasl_errstring(saslErr, NULL, NULL));
2607 free(vs->display);
2608 vs->display = NULL;
2609 return -1;
2611 #endif
2612 vs->lock_key_sync = lock_key_sync;
2614 if (reverse) {
2615 /* connect to viewer */
2616 if (strncmp(display, "unix:", 5) == 0)
2617 vs->lsock = unix_connect(display+5);
2618 else
2619 vs->lsock = inet_connect(display, SOCK_STREAM);
2620 if (-1 == vs->lsock) {
2621 free(vs->display);
2622 vs->display = NULL;
2623 return -1;
2624 } else {
2625 int csock = vs->lsock;
2626 vs->lsock = -1;
2627 vnc_connect(vs, csock);
2629 return 0;
2631 } else {
2632 /* listen for connects */
2633 char *dpy;
2634 dpy = qemu_malloc(256);
2635 if (strncmp(display, "unix:", 5) == 0) {
2636 pstrcpy(dpy, 256, "unix:");
2637 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2638 } else {
2639 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2641 if (-1 == vs->lsock) {
2642 free(dpy);
2643 return -1;
2644 } else {
2645 free(vs->display);
2646 vs->display = dpy;
2649 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);