]> git.proxmox.com Git - qemu.git/blob - ui/vnc.c
vnc: added initial websocket protocol support
[qemu.git] / ui / vnc.c
1 /*
2 * QEMU VNC display driver
3 *
4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5 * Copyright (C) 2006 Fabrice Bellard
6 * Copyright (C) 2009 Red Hat, Inc
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
27 #include "vnc.h"
28 #include "vnc-jobs.h"
29 #include "sysemu/sysemu.h"
30 #include "qemu/sockets.h"
31 #include "qemu/timer.h"
32 #include "qemu/acl.h"
33 #include "qapi/qmp/types.h"
34 #include "qmp-commands.h"
35 #include "qemu/osdep.h"
36
37 #define VNC_REFRESH_INTERVAL_BASE 30
38 #define VNC_REFRESH_INTERVAL_INC 50
39 #define VNC_REFRESH_INTERVAL_MAX 2000
40 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
41 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
42
43 #include "vnc_keysym.h"
44 #include "d3des.h"
45
46 static VncDisplay *vnc_display; /* needed for info vnc */
47 static DisplayChangeListener *dcl;
48
49 static int vnc_cursor_define(VncState *vs);
50 static void vnc_release_modifiers(VncState *vs);
51
52 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
53 {
54 #ifdef _VNC_DEBUG
55 static const char *mn[] = {
56 [0] = "undefined",
57 [VNC_SHARE_MODE_CONNECTING] = "connecting",
58 [VNC_SHARE_MODE_SHARED] = "shared",
59 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
60 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
61 };
62 fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
63 vs->csock, mn[vs->share_mode], mn[mode]);
64 #endif
65
66 if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
67 vs->vd->num_exclusive--;
68 }
69 vs->share_mode = mode;
70 if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
71 vs->vd->num_exclusive++;
72 }
73 }
74
75 static char *addr_to_string(const char *format,
76 struct sockaddr_storage *sa,
77 socklen_t salen) {
78 char *addr;
79 char host[NI_MAXHOST];
80 char serv[NI_MAXSERV];
81 int err;
82 size_t addrlen;
83
84 if ((err = getnameinfo((struct sockaddr *)sa, salen,
85 host, sizeof(host),
86 serv, sizeof(serv),
87 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
88 VNC_DEBUG("Cannot resolve address %d: %s\n",
89 err, gai_strerror(err));
90 return NULL;
91 }
92
93 /* Enough for the existing format + the 2 vars we're
94 * substituting in. */
95 addrlen = strlen(format) + strlen(host) + strlen(serv);
96 addr = g_malloc(addrlen + 1);
97 snprintf(addr, addrlen, format, host, serv);
98 addr[addrlen] = '\0';
99
100 return addr;
101 }
102
103
104 char *vnc_socket_local_addr(const char *format, int fd) {
105 struct sockaddr_storage sa;
106 socklen_t salen;
107
108 salen = sizeof(sa);
109 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
110 return NULL;
111
112 return addr_to_string(format, &sa, salen);
113 }
114
115 char *vnc_socket_remote_addr(const char *format, int fd) {
116 struct sockaddr_storage sa;
117 socklen_t salen;
118
119 salen = sizeof(sa);
120 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
121 return NULL;
122
123 return addr_to_string(format, &sa, salen);
124 }
125
126 static int put_addr_qdict(QDict *qdict, struct sockaddr_storage *sa,
127 socklen_t salen)
128 {
129 char host[NI_MAXHOST];
130 char serv[NI_MAXSERV];
131 int err;
132
133 if ((err = getnameinfo((struct sockaddr *)sa, salen,
134 host, sizeof(host),
135 serv, sizeof(serv),
136 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
137 VNC_DEBUG("Cannot resolve address %d: %s\n",
138 err, gai_strerror(err));
139 return -1;
140 }
141
142 qdict_put(qdict, "host", qstring_from_str(host));
143 qdict_put(qdict, "service", qstring_from_str(serv));
144 qdict_put(qdict, "family",qstring_from_str(inet_strfamily(sa->ss_family)));
145
146 return 0;
147 }
148
149 static int vnc_server_addr_put(QDict *qdict, int fd)
150 {
151 struct sockaddr_storage sa;
152 socklen_t salen;
153
154 salen = sizeof(sa);
155 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
156 return -1;
157 }
158
159 return put_addr_qdict(qdict, &sa, salen);
160 }
161
162 static int vnc_qdict_remote_addr(QDict *qdict, int fd)
163 {
164 struct sockaddr_storage sa;
165 socklen_t salen;
166
167 salen = sizeof(sa);
168 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
169 return -1;
170 }
171
172 return put_addr_qdict(qdict, &sa, salen);
173 }
174
175 static const char *vnc_auth_name(VncDisplay *vd) {
176 switch (vd->auth) {
177 case VNC_AUTH_INVALID:
178 return "invalid";
179 case VNC_AUTH_NONE:
180 return "none";
181 case VNC_AUTH_VNC:
182 return "vnc";
183 case VNC_AUTH_RA2:
184 return "ra2";
185 case VNC_AUTH_RA2NE:
186 return "ra2ne";
187 case VNC_AUTH_TIGHT:
188 return "tight";
189 case VNC_AUTH_ULTRA:
190 return "ultra";
191 case VNC_AUTH_TLS:
192 return "tls";
193 case VNC_AUTH_VENCRYPT:
194 #ifdef CONFIG_VNC_TLS
195 switch (vd->subauth) {
196 case VNC_AUTH_VENCRYPT_PLAIN:
197 return "vencrypt+plain";
198 case VNC_AUTH_VENCRYPT_TLSNONE:
199 return "vencrypt+tls+none";
200 case VNC_AUTH_VENCRYPT_TLSVNC:
201 return "vencrypt+tls+vnc";
202 case VNC_AUTH_VENCRYPT_TLSPLAIN:
203 return "vencrypt+tls+plain";
204 case VNC_AUTH_VENCRYPT_X509NONE:
205 return "vencrypt+x509+none";
206 case VNC_AUTH_VENCRYPT_X509VNC:
207 return "vencrypt+x509+vnc";
208 case VNC_AUTH_VENCRYPT_X509PLAIN:
209 return "vencrypt+x509+plain";
210 case VNC_AUTH_VENCRYPT_TLSSASL:
211 return "vencrypt+tls+sasl";
212 case VNC_AUTH_VENCRYPT_X509SASL:
213 return "vencrypt+x509+sasl";
214 default:
215 return "vencrypt";
216 }
217 #else
218 return "vencrypt";
219 #endif
220 case VNC_AUTH_SASL:
221 return "sasl";
222 }
223 return "unknown";
224 }
225
226 static int vnc_server_info_put(QDict *qdict)
227 {
228 if (vnc_server_addr_put(qdict, vnc_display->lsock) < 0) {
229 return -1;
230 }
231
232 qdict_put(qdict, "auth", qstring_from_str(vnc_auth_name(vnc_display)));
233 return 0;
234 }
235
236 static void vnc_client_cache_auth(VncState *client)
237 {
238 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
239 QDict *qdict;
240 #endif
241
242 if (!client->info) {
243 return;
244 }
245
246 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
247 qdict = qobject_to_qdict(client->info);
248 #endif
249
250 #ifdef CONFIG_VNC_TLS
251 if (client->tls.session &&
252 client->tls.dname) {
253 qdict_put(qdict, "x509_dname", qstring_from_str(client->tls.dname));
254 }
255 #endif
256 #ifdef CONFIG_VNC_SASL
257 if (client->sasl.conn &&
258 client->sasl.username) {
259 qdict_put(qdict, "sasl_username",
260 qstring_from_str(client->sasl.username));
261 }
262 #endif
263 }
264
265 static void vnc_client_cache_addr(VncState *client)
266 {
267 QDict *qdict;
268
269 qdict = qdict_new();
270 if (vnc_qdict_remote_addr(qdict, client->csock) < 0) {
271 QDECREF(qdict);
272 /* XXX: how to report the error? */
273 return;
274 }
275
276 client->info = QOBJECT(qdict);
277 }
278
279 static void vnc_qmp_event(VncState *vs, MonitorEvent event)
280 {
281 QDict *server;
282 QObject *data;
283
284 if (!vs->info) {
285 return;
286 }
287
288 server = qdict_new();
289 if (vnc_server_info_put(server) < 0) {
290 QDECREF(server);
291 return;
292 }
293
294 data = qobject_from_jsonf("{ 'client': %p, 'server': %p }",
295 vs->info, QOBJECT(server));
296
297 monitor_protocol_event(event, data);
298
299 qobject_incref(vs->info);
300 qobject_decref(data);
301 }
302
303 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
304 {
305 struct sockaddr_storage sa;
306 socklen_t salen = sizeof(sa);
307 char host[NI_MAXHOST];
308 char serv[NI_MAXSERV];
309 VncClientInfo *info;
310
311 if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
312 return NULL;
313 }
314
315 if (getnameinfo((struct sockaddr *)&sa, salen,
316 host, sizeof(host),
317 serv, sizeof(serv),
318 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
319 return NULL;
320 }
321
322 info = g_malloc0(sizeof(*info));
323 info->host = g_strdup(host);
324 info->service = g_strdup(serv);
325 info->family = g_strdup(inet_strfamily(sa.ss_family));
326
327 #ifdef CONFIG_VNC_TLS
328 if (client->tls.session && client->tls.dname) {
329 info->has_x509_dname = true;
330 info->x509_dname = g_strdup(client->tls.dname);
331 }
332 #endif
333 #ifdef CONFIG_VNC_SASL
334 if (client->sasl.conn && client->sasl.username) {
335 info->has_sasl_username = true;
336 info->sasl_username = g_strdup(client->sasl.username);
337 }
338 #endif
339
340 return info;
341 }
342
343 VncInfo *qmp_query_vnc(Error **errp)
344 {
345 VncInfo *info = g_malloc0(sizeof(*info));
346
347 if (vnc_display == NULL || vnc_display->display == NULL) {
348 info->enabled = false;
349 } else {
350 VncClientInfoList *cur_item = NULL;
351 struct sockaddr_storage sa;
352 socklen_t salen = sizeof(sa);
353 char host[NI_MAXHOST];
354 char serv[NI_MAXSERV];
355 VncState *client;
356
357 info->enabled = true;
358
359 /* for compatibility with the original command */
360 info->has_clients = true;
361
362 QTAILQ_FOREACH(client, &vnc_display->clients, next) {
363 VncClientInfoList *cinfo = g_malloc0(sizeof(*info));
364 cinfo->value = qmp_query_vnc_client(client);
365
366 /* XXX: waiting for the qapi to support GSList */
367 if (!cur_item) {
368 info->clients = cur_item = cinfo;
369 } else {
370 cur_item->next = cinfo;
371 cur_item = cinfo;
372 }
373 }
374
375 if (vnc_display->lsock == -1) {
376 return info;
377 }
378
379 if (getsockname(vnc_display->lsock, (struct sockaddr *)&sa,
380 &salen) == -1) {
381 error_set(errp, QERR_UNDEFINED_ERROR);
382 goto out_error;
383 }
384
385 if (getnameinfo((struct sockaddr *)&sa, salen,
386 host, sizeof(host),
387 serv, sizeof(serv),
388 NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
389 error_set(errp, QERR_UNDEFINED_ERROR);
390 goto out_error;
391 }
392
393 info->has_host = true;
394 info->host = g_strdup(host);
395
396 info->has_service = true;
397 info->service = g_strdup(serv);
398
399 info->has_family = true;
400 info->family = g_strdup(inet_strfamily(sa.ss_family));
401
402 info->has_auth = true;
403 info->auth = g_strdup(vnc_auth_name(vnc_display));
404 }
405
406 return info;
407
408 out_error:
409 qapi_free_VncInfo(info);
410 return NULL;
411 }
412
413 /* TODO
414 1) Get the queue working for IO.
415 2) there is some weirdness when using the -S option (the screen is grey
416 and not totally invalidated
417 3) resolutions > 1024
418 */
419
420 static int vnc_update_client(VncState *vs, int has_dirty);
421 static int vnc_update_client_sync(VncState *vs, int has_dirty);
422 static void vnc_disconnect_start(VncState *vs);
423 static void vnc_init_timer(VncDisplay *vd);
424 static void vnc_remove_timer(VncDisplay *vd);
425
426 static void vnc_colordepth(VncState *vs);
427 static void framebuffer_update_request(VncState *vs, int incremental,
428 int x_position, int y_position,
429 int w, int h);
430 static void vnc_refresh(void *opaque);
431 static int vnc_refresh_server_surface(VncDisplay *vd);
432
433 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
434 {
435 int i;
436 VncDisplay *vd = ds->opaque;
437 struct VncSurface *s = &vd->guest;
438 int width = ds_get_width(ds);
439 int height = ds_get_height(ds);
440
441 h += y;
442
443 /* round x down to ensure the loop only spans one 16-pixel block per,
444 iteration. otherwise, if (x % 16) != 0, the last iteration may span
445 two 16-pixel blocks but we only mark the first as dirty
446 */
447 w += (x % 16);
448 x -= (x % 16);
449
450 x = MIN(x, width);
451 y = MIN(y, height);
452 w = MIN(x + w, width) - x;
453 h = MIN(h, height);
454
455 for (; y < h; y++)
456 for (i = 0; i < w; i += 16)
457 set_bit((x + i) / 16, s->dirty[y]);
458 }
459
460 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
461 int32_t encoding)
462 {
463 vnc_write_u16(vs, x);
464 vnc_write_u16(vs, y);
465 vnc_write_u16(vs, w);
466 vnc_write_u16(vs, h);
467
468 vnc_write_s32(vs, encoding);
469 }
470
471 void buffer_reserve(Buffer *buffer, size_t len)
472 {
473 if ((buffer->capacity - buffer->offset) < len) {
474 buffer->capacity += (len + 1024);
475 buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
476 if (buffer->buffer == NULL) {
477 fprintf(stderr, "vnc: out of memory\n");
478 exit(1);
479 }
480 }
481 }
482
483 static int buffer_empty(Buffer *buffer)
484 {
485 return buffer->offset == 0;
486 }
487
488 uint8_t *buffer_end(Buffer *buffer)
489 {
490 return buffer->buffer + buffer->offset;
491 }
492
493 void buffer_reset(Buffer *buffer)
494 {
495 buffer->offset = 0;
496 }
497
498 void buffer_free(Buffer *buffer)
499 {
500 g_free(buffer->buffer);
501 buffer->offset = 0;
502 buffer->capacity = 0;
503 buffer->buffer = NULL;
504 }
505
506 void buffer_append(Buffer *buffer, const void *data, size_t len)
507 {
508 memcpy(buffer->buffer + buffer->offset, data, len);
509 buffer->offset += len;
510 }
511
512 void buffer_advance(Buffer *buf, size_t len)
513 {
514 memmove(buf->buffer, buf->buffer + len,
515 (buf->offset - len));
516 buf->offset -= len;
517 }
518
519 static void vnc_desktop_resize(VncState *vs)
520 {
521 DisplayState *ds = vs->ds;
522
523 if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
524 return;
525 }
526 if (vs->client_width == ds_get_width(ds) &&
527 vs->client_height == ds_get_height(ds)) {
528 return;
529 }
530 vs->client_width = ds_get_width(ds);
531 vs->client_height = ds_get_height(ds);
532 vnc_lock_output(vs);
533 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
534 vnc_write_u8(vs, 0);
535 vnc_write_u16(vs, 1); /* number of rects */
536 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
537 VNC_ENCODING_DESKTOPRESIZE);
538 vnc_unlock_output(vs);
539 vnc_flush(vs);
540 }
541
542 static void vnc_abort_display_jobs(VncDisplay *vd)
543 {
544 VncState *vs;
545
546 QTAILQ_FOREACH(vs, &vd->clients, next) {
547 vnc_lock_output(vs);
548 vs->abort = true;
549 vnc_unlock_output(vs);
550 }
551 QTAILQ_FOREACH(vs, &vd->clients, next) {
552 vnc_jobs_join(vs);
553 }
554 QTAILQ_FOREACH(vs, &vd->clients, next) {
555 vnc_lock_output(vs);
556 vs->abort = false;
557 vnc_unlock_output(vs);
558 }
559 }
560
561 int vnc_server_fb_stride(VncDisplay *vd)
562 {
563 return pixman_image_get_stride(vd->server);
564 }
565
566 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
567 {
568 uint8_t *ptr;
569
570 ptr = (uint8_t *)pixman_image_get_data(vd->server);
571 ptr += y * vnc_server_fb_stride(vd);
572 ptr += x * VNC_SERVER_FB_BYTES;
573 return ptr;
574 }
575
576 static void vnc_dpy_resize(DisplayState *ds)
577 {
578 VncDisplay *vd = ds->opaque;
579 VncState *vs;
580
581 vnc_abort_display_jobs(vd);
582
583 /* server surface */
584 qemu_pixman_image_unref(vd->server);
585 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
586 ds_get_width(ds),
587 ds_get_height(ds),
588 NULL, 0);
589
590 /* guest surface */
591 #if 0 /* FIXME */
592 if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
593 console_color_init(ds);
594 #endif
595 qemu_pixman_image_unref(vd->guest.fb);
596 vd->guest.fb = pixman_image_ref(ds->surface->image);
597 vd->guest.format = ds->surface->format;
598 memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
599
600 QTAILQ_FOREACH(vs, &vd->clients, next) {
601 vnc_colordepth(vs);
602 vnc_desktop_resize(vs);
603 if (vs->vd->cursor) {
604 vnc_cursor_define(vs);
605 }
606 memset(vs->dirty, 0xFF, sizeof(vs->dirty));
607 }
608 }
609
610 /* fastest code */
611 static void vnc_write_pixels_copy(VncState *vs,
612 void *pixels, int size)
613 {
614 vnc_write(vs, pixels, size);
615 }
616
617 /* slowest but generic code. */
618 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
619 {
620 uint8_t r, g, b;
621
622 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
623 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
624 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
625 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
626 #else
627 # error need some bits here if you change VNC_SERVER_FB_FORMAT
628 #endif
629 v = (r << vs->client_pf.rshift) |
630 (g << vs->client_pf.gshift) |
631 (b << vs->client_pf.bshift);
632 switch (vs->client_pf.bytes_per_pixel) {
633 case 1:
634 buf[0] = v;
635 break;
636 case 2:
637 if (vs->client_be) {
638 buf[0] = v >> 8;
639 buf[1] = v;
640 } else {
641 buf[1] = v >> 8;
642 buf[0] = v;
643 }
644 break;
645 default:
646 case 4:
647 if (vs->client_be) {
648 buf[0] = v >> 24;
649 buf[1] = v >> 16;
650 buf[2] = v >> 8;
651 buf[3] = v;
652 } else {
653 buf[3] = v >> 24;
654 buf[2] = v >> 16;
655 buf[1] = v >> 8;
656 buf[0] = v;
657 }
658 break;
659 }
660 }
661
662 static void vnc_write_pixels_generic(VncState *vs,
663 void *pixels1, int size)
664 {
665 uint8_t buf[4];
666
667 if (VNC_SERVER_FB_BYTES == 4) {
668 uint32_t *pixels = pixels1;
669 int n, i;
670 n = size >> 2;
671 for (i = 0; i < n; i++) {
672 vnc_convert_pixel(vs, buf, pixels[i]);
673 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
674 }
675 }
676 }
677
678 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
679 {
680 int i;
681 uint8_t *row;
682 VncDisplay *vd = vs->vd;
683
684 row = vnc_server_fb_ptr(vd, x, y);
685 for (i = 0; i < h; i++) {
686 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
687 row += vnc_server_fb_stride(vd);
688 }
689 return 1;
690 }
691
692 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
693 {
694 int n = 0;
695
696 switch(vs->vnc_encoding) {
697 case VNC_ENCODING_ZLIB:
698 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
699 break;
700 case VNC_ENCODING_HEXTILE:
701 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
702 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
703 break;
704 case VNC_ENCODING_TIGHT:
705 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
706 break;
707 case VNC_ENCODING_TIGHT_PNG:
708 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
709 break;
710 case VNC_ENCODING_ZRLE:
711 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
712 break;
713 case VNC_ENCODING_ZYWRLE:
714 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
715 break;
716 default:
717 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
718 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
719 break;
720 }
721 return n;
722 }
723
724 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
725 {
726 /* send bitblit op to the vnc client */
727 vnc_lock_output(vs);
728 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
729 vnc_write_u8(vs, 0);
730 vnc_write_u16(vs, 1); /* number of rects */
731 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
732 vnc_write_u16(vs, src_x);
733 vnc_write_u16(vs, src_y);
734 vnc_unlock_output(vs);
735 vnc_flush(vs);
736 }
737
738 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
739 {
740 VncDisplay *vd = ds->opaque;
741 VncState *vs, *vn;
742 uint8_t *src_row;
743 uint8_t *dst_row;
744 int i, x, y, pitch, inc, w_lim, s;
745 int cmp_bytes;
746
747 vnc_refresh_server_surface(vd);
748 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
749 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
750 vs->force_update = 1;
751 vnc_update_client_sync(vs, 1);
752 /* vs might be free()ed here */
753 }
754 }
755
756 /* do bitblit op on the local surface too */
757 pitch = vnc_server_fb_stride(vd);
758 src_row = vnc_server_fb_ptr(vd, src_x, src_y);
759 dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
760 y = dst_y;
761 inc = 1;
762 if (dst_y > src_y) {
763 /* copy backwards */
764 src_row += pitch * (h-1);
765 dst_row += pitch * (h-1);
766 pitch = -pitch;
767 y = dst_y + h - 1;
768 inc = -1;
769 }
770 w_lim = w - (16 - (dst_x % 16));
771 if (w_lim < 0)
772 w_lim = w;
773 else
774 w_lim = w - (w_lim % 16);
775 for (i = 0; i < h; i++) {
776 for (x = 0; x <= w_lim;
777 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
778 if (x == w_lim) {
779 if ((s = w - w_lim) == 0)
780 break;
781 } else if (!x) {
782 s = (16 - (dst_x % 16));
783 s = MIN(s, w_lim);
784 } else {
785 s = 16;
786 }
787 cmp_bytes = s * VNC_SERVER_FB_BYTES;
788 if (memcmp(src_row, dst_row, cmp_bytes) == 0)
789 continue;
790 memmove(dst_row, src_row, cmp_bytes);
791 QTAILQ_FOREACH(vs, &vd->clients, next) {
792 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
793 set_bit(((x + dst_x) / 16), vs->dirty[y]);
794 }
795 }
796 }
797 src_row += pitch - w * VNC_SERVER_FB_BYTES;
798 dst_row += pitch - w * VNC_SERVER_FB_BYTES;
799 y += inc;
800 }
801
802 QTAILQ_FOREACH(vs, &vd->clients, next) {
803 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
804 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
805 }
806 }
807 }
808
809 static void vnc_mouse_set(DisplayState *ds, int x, int y, int visible)
810 {
811 /* can we ask the client(s) to move the pointer ??? */
812 }
813
814 static int vnc_cursor_define(VncState *vs)
815 {
816 QEMUCursor *c = vs->vd->cursor;
817 int isize;
818
819 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
820 vnc_lock_output(vs);
821 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
822 vnc_write_u8(vs, 0); /* padding */
823 vnc_write_u16(vs, 1); /* # of rects */
824 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
825 VNC_ENCODING_RICH_CURSOR);
826 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
827 vnc_write_pixels_generic(vs, c->data, isize);
828 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
829 vnc_unlock_output(vs);
830 return 0;
831 }
832 return -1;
833 }
834
835 static void vnc_dpy_cursor_define(DisplayState *ds, QEMUCursor *c)
836 {
837 VncDisplay *vd = vnc_display;
838 VncState *vs;
839
840 cursor_put(vd->cursor);
841 g_free(vd->cursor_mask);
842
843 vd->cursor = c;
844 cursor_get(vd->cursor);
845 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
846 vd->cursor_mask = g_malloc0(vd->cursor_msize);
847 cursor_get_mono_mask(c, 0, vd->cursor_mask);
848
849 QTAILQ_FOREACH(vs, &vd->clients, next) {
850 vnc_cursor_define(vs);
851 }
852 }
853
854 static int find_and_clear_dirty_height(struct VncState *vs,
855 int y, int last_x, int x, int height)
856 {
857 int h;
858
859 for (h = 1; h < (height - y); h++) {
860 int tmp_x;
861 if (!test_bit(last_x, vs->dirty[y + h])) {
862 break;
863 }
864 for (tmp_x = last_x; tmp_x < x; tmp_x++) {
865 clear_bit(tmp_x, vs->dirty[y + h]);
866 }
867 }
868
869 return h;
870 }
871
872 static int vnc_update_client_sync(VncState *vs, int has_dirty)
873 {
874 int ret = vnc_update_client(vs, has_dirty);
875 vnc_jobs_join(vs);
876 return ret;
877 }
878
879 static int vnc_update_client(VncState *vs, int has_dirty)
880 {
881 if (vs->need_update && vs->csock != -1) {
882 VncDisplay *vd = vs->vd;
883 VncJob *job;
884 int y;
885 int width, height;
886 int n = 0;
887
888
889 if (vs->output.offset && !vs->audio_cap && !vs->force_update)
890 /* kernel send buffers are full -> drop frames to throttle */
891 return 0;
892
893 if (!has_dirty && !vs->audio_cap && !vs->force_update)
894 return 0;
895
896 /*
897 * Send screen updates to the vnc client using the server
898 * surface and server dirty map. guest surface updates
899 * happening in parallel don't disturb us, the next pass will
900 * send them to the client.
901 */
902 job = vnc_job_new(vs);
903
904 width = MIN(pixman_image_get_width(vd->server), vs->client_width);
905 height = MIN(pixman_image_get_height(vd->server), vs->client_height);
906
907 for (y = 0; y < height; y++) {
908 int x;
909 int last_x = -1;
910 for (x = 0; x < width / 16; x++) {
911 if (test_and_clear_bit(x, vs->dirty[y])) {
912 if (last_x == -1) {
913 last_x = x;
914 }
915 } else {
916 if (last_x != -1) {
917 int h = find_and_clear_dirty_height(vs, y, last_x, x,
918 height);
919
920 n += vnc_job_add_rect(job, last_x * 16, y,
921 (x - last_x) * 16, h);
922 }
923 last_x = -1;
924 }
925 }
926 if (last_x != -1) {
927 int h = find_and_clear_dirty_height(vs, y, last_x, x, height);
928 n += vnc_job_add_rect(job, last_x * 16, y,
929 (x - last_x) * 16, h);
930 }
931 }
932
933 vnc_job_push(job);
934 vs->force_update = 0;
935 return n;
936 }
937
938 if (vs->csock == -1)
939 vnc_disconnect_finish(vs);
940
941 return 0;
942 }
943
944 /* audio */
945 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
946 {
947 VncState *vs = opaque;
948
949 switch (cmd) {
950 case AUD_CNOTIFY_DISABLE:
951 vnc_lock_output(vs);
952 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
953 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
954 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
955 vnc_unlock_output(vs);
956 vnc_flush(vs);
957 break;
958
959 case AUD_CNOTIFY_ENABLE:
960 vnc_lock_output(vs);
961 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
962 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
963 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
964 vnc_unlock_output(vs);
965 vnc_flush(vs);
966 break;
967 }
968 }
969
970 static void audio_capture_destroy(void *opaque)
971 {
972 }
973
974 static void audio_capture(void *opaque, void *buf, int size)
975 {
976 VncState *vs = opaque;
977
978 vnc_lock_output(vs);
979 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
980 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
981 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
982 vnc_write_u32(vs, size);
983 vnc_write(vs, buf, size);
984 vnc_unlock_output(vs);
985 vnc_flush(vs);
986 }
987
988 static void audio_add(VncState *vs)
989 {
990 struct audio_capture_ops ops;
991
992 if (vs->audio_cap) {
993 monitor_printf(default_mon, "audio already running\n");
994 return;
995 }
996
997 ops.notify = audio_capture_notify;
998 ops.destroy = audio_capture_destroy;
999 ops.capture = audio_capture;
1000
1001 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1002 if (!vs->audio_cap) {
1003 monitor_printf(default_mon, "Failed to add audio capture\n");
1004 }
1005 }
1006
1007 static void audio_del(VncState *vs)
1008 {
1009 if (vs->audio_cap) {
1010 AUD_del_capture(vs->audio_cap, vs);
1011 vs->audio_cap = NULL;
1012 }
1013 }
1014
1015 static void vnc_disconnect_start(VncState *vs)
1016 {
1017 if (vs->csock == -1)
1018 return;
1019 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1020 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1021 closesocket(vs->csock);
1022 vs->csock = -1;
1023 }
1024
1025 void vnc_disconnect_finish(VncState *vs)
1026 {
1027 int i;
1028
1029 vnc_jobs_join(vs); /* Wait encoding jobs */
1030
1031 vnc_lock_output(vs);
1032 vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
1033
1034 buffer_free(&vs->input);
1035 buffer_free(&vs->output);
1036 #ifdef CONFIG_VNC_WS
1037 buffer_free(&vs->ws_input);
1038 buffer_free(&vs->ws_output);
1039 #endif /* CONFIG_VNC_WS */
1040
1041 qobject_decref(vs->info);
1042
1043 vnc_zlib_clear(vs);
1044 vnc_tight_clear(vs);
1045 vnc_zrle_clear(vs);
1046
1047 #ifdef CONFIG_VNC_TLS
1048 vnc_tls_client_cleanup(vs);
1049 #endif /* CONFIG_VNC_TLS */
1050 #ifdef CONFIG_VNC_SASL
1051 vnc_sasl_client_cleanup(vs);
1052 #endif /* CONFIG_VNC_SASL */
1053 audio_del(vs);
1054 vnc_release_modifiers(vs);
1055
1056 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1057
1058 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1059 dcl->idle = 1;
1060 }
1061
1062 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1063 vnc_remove_timer(vs->vd);
1064 if (vs->vd->lock_key_sync)
1065 qemu_remove_led_event_handler(vs->led);
1066 vnc_unlock_output(vs);
1067
1068 qemu_mutex_destroy(&vs->output_mutex);
1069 qemu_bh_delete(vs->bh);
1070 buffer_free(&vs->jobs_buffer);
1071
1072 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1073 g_free(vs->lossy_rect[i]);
1074 }
1075 g_free(vs->lossy_rect);
1076 g_free(vs);
1077 }
1078
1079 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1080 {
1081 if (ret == 0 || ret == -1) {
1082 if (ret == -1) {
1083 switch (last_errno) {
1084 case EINTR:
1085 case EAGAIN:
1086 #ifdef _WIN32
1087 case WSAEWOULDBLOCK:
1088 #endif
1089 return 0;
1090 default:
1091 break;
1092 }
1093 }
1094
1095 VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1096 ret, ret < 0 ? last_errno : 0);
1097 vnc_disconnect_start(vs);
1098
1099 return 0;
1100 }
1101 return ret;
1102 }
1103
1104
1105 void vnc_client_error(VncState *vs)
1106 {
1107 VNC_DEBUG("Closing down client sock: protocol error\n");
1108 vnc_disconnect_start(vs);
1109 }
1110
1111
1112 /*
1113 * Called to write a chunk of data to the client socket. The data may
1114 * be the raw data, or may have already been encoded by SASL.
1115 * The data will be written either straight onto the socket, or
1116 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1117 *
1118 * NB, it is theoretically possible to have 2 layers of encryption,
1119 * both SASL, and this TLS layer. It is highly unlikely in practice
1120 * though, since SASL encryption will typically be a no-op if TLS
1121 * is active
1122 *
1123 * Returns the number of bytes written, which may be less than
1124 * the requested 'datalen' if the socket would block. Returns
1125 * -1 on error, and disconnects the client socket.
1126 */
1127 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1128 {
1129 long ret;
1130 #ifdef CONFIG_VNC_TLS
1131 if (vs->tls.session) {
1132 ret = gnutls_write(vs->tls.session, data, datalen);
1133 if (ret < 0) {
1134 if (ret == GNUTLS_E_AGAIN)
1135 errno = EAGAIN;
1136 else
1137 errno = EIO;
1138 ret = -1;
1139 }
1140 } else
1141 #endif /* CONFIG_VNC_TLS */
1142 ret = send(vs->csock, (const void *)data, datalen, 0);
1143 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1144 return vnc_client_io_error(vs, ret, socket_error());
1145 }
1146
1147
1148 /*
1149 * Called to write buffered data to the client socket, when not
1150 * using any SASL SSF encryption layers. Will write as much data
1151 * as possible without blocking. If all buffered data is written,
1152 * will switch the FD poll() handler back to read monitoring.
1153 *
1154 * Returns the number of bytes written, which may be less than
1155 * the buffered output data if the socket would block. Returns
1156 * -1 on error, and disconnects the client socket.
1157 */
1158 static long vnc_client_write_plain(VncState *vs)
1159 {
1160 long ret;
1161
1162 #ifdef CONFIG_VNC_SASL
1163 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1164 vs->output.buffer, vs->output.capacity, vs->output.offset,
1165 vs->sasl.waitWriteSSF);
1166
1167 if (vs->sasl.conn &&
1168 vs->sasl.runSSF &&
1169 vs->sasl.waitWriteSSF) {
1170 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1171 if (ret)
1172 vs->sasl.waitWriteSSF -= ret;
1173 } else
1174 #endif /* CONFIG_VNC_SASL */
1175 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1176 if (!ret)
1177 return 0;
1178
1179 buffer_advance(&vs->output, ret);
1180
1181 if (vs->output.offset == 0) {
1182 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1183 }
1184
1185 return ret;
1186 }
1187
1188
1189 /*
1190 * First function called whenever there is data to be written to
1191 * the client socket. Will delegate actual work according to whether
1192 * SASL SSF layers are enabled (thus requiring encryption calls)
1193 */
1194 static void vnc_client_write_locked(void *opaque)
1195 {
1196 VncState *vs = opaque;
1197
1198 #ifdef CONFIG_VNC_SASL
1199 if (vs->sasl.conn &&
1200 vs->sasl.runSSF &&
1201 !vs->sasl.waitWriteSSF) {
1202 vnc_client_write_sasl(vs);
1203 } else
1204 #endif /* CONFIG_VNC_SASL */
1205 {
1206 #ifdef CONFIG_VNC_WS
1207 if (vs->encode_ws) {
1208 vnc_client_write_ws(vs);
1209 } else
1210 #endif /* CONFIG_VNC_WS */
1211 {
1212 vnc_client_write_plain(vs);
1213 }
1214 }
1215 }
1216
1217 void vnc_client_write(void *opaque)
1218 {
1219 VncState *vs = opaque;
1220
1221 vnc_lock_output(vs);
1222 if (vs->output.offset
1223 #ifdef CONFIG_VNC_WS
1224 || vs->ws_output.offset
1225 #endif
1226 ) {
1227 vnc_client_write_locked(opaque);
1228 } else if (vs->csock != -1) {
1229 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1230 }
1231 vnc_unlock_output(vs);
1232 }
1233
1234 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1235 {
1236 vs->read_handler = func;
1237 vs->read_handler_expect = expecting;
1238 }
1239
1240
1241 /*
1242 * Called to read a chunk of data from the client socket. The data may
1243 * be the raw data, or may need to be further decoded by SASL.
1244 * The data will be read either straight from to the socket, or
1245 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1246 *
1247 * NB, it is theoretically possible to have 2 layers of encryption,
1248 * both SASL, and this TLS layer. It is highly unlikely in practice
1249 * though, since SASL encryption will typically be a no-op if TLS
1250 * is active
1251 *
1252 * Returns the number of bytes read, which may be less than
1253 * the requested 'datalen' if the socket would block. Returns
1254 * -1 on error, and disconnects the client socket.
1255 */
1256 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1257 {
1258 long ret;
1259 #ifdef CONFIG_VNC_TLS
1260 if (vs->tls.session) {
1261 ret = gnutls_read(vs->tls.session, data, datalen);
1262 if (ret < 0) {
1263 if (ret == GNUTLS_E_AGAIN)
1264 errno = EAGAIN;
1265 else
1266 errno = EIO;
1267 ret = -1;
1268 }
1269 } else
1270 #endif /* CONFIG_VNC_TLS */
1271 ret = qemu_recv(vs->csock, data, datalen, 0);
1272 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1273 return vnc_client_io_error(vs, ret, socket_error());
1274 }
1275
1276
1277 /*
1278 * Called to read data from the client socket to the input buffer,
1279 * when not using any SASL SSF encryption layers. Will read as much
1280 * data as possible without blocking.
1281 *
1282 * Returns the number of bytes read. Returns -1 on error, and
1283 * disconnects the client socket.
1284 */
1285 static long vnc_client_read_plain(VncState *vs)
1286 {
1287 int ret;
1288 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1289 vs->input.buffer, vs->input.capacity, vs->input.offset);
1290 buffer_reserve(&vs->input, 4096);
1291 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1292 if (!ret)
1293 return 0;
1294 vs->input.offset += ret;
1295 return ret;
1296 }
1297
1298 static void vnc_jobs_bh(void *opaque)
1299 {
1300 VncState *vs = opaque;
1301
1302 vnc_jobs_consume_buffer(vs);
1303 }
1304
1305 /*
1306 * First function called whenever there is more data to be read from
1307 * the client socket. Will delegate actual work according to whether
1308 * SASL SSF layers are enabled (thus requiring decryption calls)
1309 */
1310 void vnc_client_read(void *opaque)
1311 {
1312 VncState *vs = opaque;
1313 long ret;
1314
1315 #ifdef CONFIG_VNC_SASL
1316 if (vs->sasl.conn && vs->sasl.runSSF)
1317 ret = vnc_client_read_sasl(vs);
1318 else
1319 #endif /* CONFIG_VNC_SASL */
1320 #ifdef CONFIG_VNC_WS
1321 if (vs->encode_ws) {
1322 ret = vnc_client_read_ws(vs);
1323 if (ret == -1) {
1324 vnc_disconnect_start(vs);
1325 return;
1326 } else if (ret == -2) {
1327 vnc_client_error(vs);
1328 return;
1329 }
1330 } else
1331 #endif /* CONFIG_VNC_WS */
1332 {
1333 ret = vnc_client_read_plain(vs);
1334 }
1335 if (!ret) {
1336 if (vs->csock == -1)
1337 vnc_disconnect_finish(vs);
1338 return;
1339 }
1340
1341 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1342 size_t len = vs->read_handler_expect;
1343 int ret;
1344
1345 ret = vs->read_handler(vs, vs->input.buffer, len);
1346 if (vs->csock == -1) {
1347 vnc_disconnect_finish(vs);
1348 return;
1349 }
1350
1351 if (!ret) {
1352 buffer_advance(&vs->input, len);
1353 } else {
1354 vs->read_handler_expect = ret;
1355 }
1356 }
1357 }
1358
1359 void vnc_write(VncState *vs, const void *data, size_t len)
1360 {
1361 buffer_reserve(&vs->output, len);
1362
1363 if (vs->csock != -1 && buffer_empty(&vs->output)) {
1364 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1365 }
1366
1367 buffer_append(&vs->output, data, len);
1368 }
1369
1370 void vnc_write_s32(VncState *vs, int32_t value)
1371 {
1372 vnc_write_u32(vs, *(uint32_t *)&value);
1373 }
1374
1375 void vnc_write_u32(VncState *vs, uint32_t value)
1376 {
1377 uint8_t buf[4];
1378
1379 buf[0] = (value >> 24) & 0xFF;
1380 buf[1] = (value >> 16) & 0xFF;
1381 buf[2] = (value >> 8) & 0xFF;
1382 buf[3] = value & 0xFF;
1383
1384 vnc_write(vs, buf, 4);
1385 }
1386
1387 void vnc_write_u16(VncState *vs, uint16_t value)
1388 {
1389 uint8_t buf[2];
1390
1391 buf[0] = (value >> 8) & 0xFF;
1392 buf[1] = value & 0xFF;
1393
1394 vnc_write(vs, buf, 2);
1395 }
1396
1397 void vnc_write_u8(VncState *vs, uint8_t value)
1398 {
1399 vnc_write(vs, (char *)&value, 1);
1400 }
1401
1402 void vnc_flush(VncState *vs)
1403 {
1404 vnc_lock_output(vs);
1405 if (vs->csock != -1 && (vs->output.offset
1406 #ifdef CONFIG_VNC_WS
1407 || vs->ws_output.offset
1408 #endif
1409 )) {
1410 vnc_client_write_locked(vs);
1411 }
1412 vnc_unlock_output(vs);
1413 }
1414
1415 static uint8_t read_u8(uint8_t *data, size_t offset)
1416 {
1417 return data[offset];
1418 }
1419
1420 static uint16_t read_u16(uint8_t *data, size_t offset)
1421 {
1422 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1423 }
1424
1425 static int32_t read_s32(uint8_t *data, size_t offset)
1426 {
1427 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1428 (data[offset + 2] << 8) | data[offset + 3]);
1429 }
1430
1431 uint32_t read_u32(uint8_t *data, size_t offset)
1432 {
1433 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1434 (data[offset + 2] << 8) | data[offset + 3]);
1435 }
1436
1437 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1438 {
1439 }
1440
1441 static void check_pointer_type_change(Notifier *notifier, void *data)
1442 {
1443 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1444 int absolute = kbd_mouse_is_absolute();
1445
1446 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1447 vnc_lock_output(vs);
1448 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1449 vnc_write_u8(vs, 0);
1450 vnc_write_u16(vs, 1);
1451 vnc_framebuffer_update(vs, absolute, 0,
1452 ds_get_width(vs->ds), ds_get_height(vs->ds),
1453 VNC_ENCODING_POINTER_TYPE_CHANGE);
1454 vnc_unlock_output(vs);
1455 vnc_flush(vs);
1456 }
1457 vs->absolute = absolute;
1458 }
1459
1460 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1461 {
1462 int buttons = 0;
1463 int dz = 0;
1464
1465 if (button_mask & 0x01)
1466 buttons |= MOUSE_EVENT_LBUTTON;
1467 if (button_mask & 0x02)
1468 buttons |= MOUSE_EVENT_MBUTTON;
1469 if (button_mask & 0x04)
1470 buttons |= MOUSE_EVENT_RBUTTON;
1471 if (button_mask & 0x08)
1472 dz = -1;
1473 if (button_mask & 0x10)
1474 dz = 1;
1475
1476 if (vs->absolute) {
1477 kbd_mouse_event(ds_get_width(vs->ds) > 1 ?
1478 x * 0x7FFF / (ds_get_width(vs->ds) - 1) : 0x4000,
1479 ds_get_height(vs->ds) > 1 ?
1480 y * 0x7FFF / (ds_get_height(vs->ds) - 1) : 0x4000,
1481 dz, buttons);
1482 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1483 x -= 0x7FFF;
1484 y -= 0x7FFF;
1485
1486 kbd_mouse_event(x, y, dz, buttons);
1487 } else {
1488 if (vs->last_x != -1)
1489 kbd_mouse_event(x - vs->last_x,
1490 y - vs->last_y,
1491 dz, buttons);
1492 vs->last_x = x;
1493 vs->last_y = y;
1494 }
1495 }
1496
1497 static void reset_keys(VncState *vs)
1498 {
1499 int i;
1500 for(i = 0; i < 256; i++) {
1501 if (vs->modifiers_state[i]) {
1502 if (i & SCANCODE_GREY)
1503 kbd_put_keycode(SCANCODE_EMUL0);
1504 kbd_put_keycode(i | SCANCODE_UP);
1505 vs->modifiers_state[i] = 0;
1506 }
1507 }
1508 }
1509
1510 static void press_key(VncState *vs, int keysym)
1511 {
1512 int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1513 if (keycode & SCANCODE_GREY)
1514 kbd_put_keycode(SCANCODE_EMUL0);
1515 kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1516 if (keycode & SCANCODE_GREY)
1517 kbd_put_keycode(SCANCODE_EMUL0);
1518 kbd_put_keycode(keycode | SCANCODE_UP);
1519 }
1520
1521 static void kbd_leds(void *opaque, int ledstate)
1522 {
1523 VncState *vs = opaque;
1524 int caps, num;
1525
1526 caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1527 num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
1528
1529 if (vs->modifiers_state[0x3a] != caps) {
1530 vs->modifiers_state[0x3a] = caps;
1531 }
1532 if (vs->modifiers_state[0x45] != num) {
1533 vs->modifiers_state[0x45] = num;
1534 }
1535 }
1536
1537 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1538 {
1539 /* QEMU console switch */
1540 switch(keycode) {
1541 case 0x2a: /* Left Shift */
1542 case 0x36: /* Right Shift */
1543 case 0x1d: /* Left CTRL */
1544 case 0x9d: /* Right CTRL */
1545 case 0x38: /* Left ALT */
1546 case 0xb8: /* Right ALT */
1547 if (down)
1548 vs->modifiers_state[keycode] = 1;
1549 else
1550 vs->modifiers_state[keycode] = 0;
1551 break;
1552 case 0x02 ... 0x0a: /* '1' to '9' keys */
1553 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1554 /* Reset the modifiers sent to the current console */
1555 reset_keys(vs);
1556 console_select(keycode - 0x02);
1557 return;
1558 }
1559 break;
1560 case 0x3a: /* CapsLock */
1561 case 0x45: /* NumLock */
1562 if (down)
1563 vs->modifiers_state[keycode] ^= 1;
1564 break;
1565 }
1566
1567 if (down && vs->vd->lock_key_sync &&
1568 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1569 /* If the numlock state needs to change then simulate an additional
1570 keypress before sending this one. This will happen if the user
1571 toggles numlock away from the VNC window.
1572 */
1573 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1574 if (!vs->modifiers_state[0x45]) {
1575 vs->modifiers_state[0x45] = 1;
1576 press_key(vs, 0xff7f);
1577 }
1578 } else {
1579 if (vs->modifiers_state[0x45]) {
1580 vs->modifiers_state[0x45] = 0;
1581 press_key(vs, 0xff7f);
1582 }
1583 }
1584 }
1585
1586 if (down && vs->vd->lock_key_sync &&
1587 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1588 /* If the capslock state needs to change then simulate an additional
1589 keypress before sending this one. This will happen if the user
1590 toggles capslock away from the VNC window.
1591 */
1592 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1593 int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1594 int capslock = !!(vs->modifiers_state[0x3a]);
1595 if (capslock) {
1596 if (uppercase == shift) {
1597 vs->modifiers_state[0x3a] = 0;
1598 press_key(vs, 0xffe5);
1599 }
1600 } else {
1601 if (uppercase != shift) {
1602 vs->modifiers_state[0x3a] = 1;
1603 press_key(vs, 0xffe5);
1604 }
1605 }
1606 }
1607
1608 if (is_graphic_console()) {
1609 if (keycode & SCANCODE_GREY)
1610 kbd_put_keycode(SCANCODE_EMUL0);
1611 if (down)
1612 kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1613 else
1614 kbd_put_keycode(keycode | SCANCODE_UP);
1615 } else {
1616 bool numlock = vs->modifiers_state[0x45];
1617 bool control = (vs->modifiers_state[0x1d] ||
1618 vs->modifiers_state[0x9d]);
1619 /* QEMU console emulation */
1620 if (down) {
1621 switch (keycode) {
1622 case 0x2a: /* Left Shift */
1623 case 0x36: /* Right Shift */
1624 case 0x1d: /* Left CTRL */
1625 case 0x9d: /* Right CTRL */
1626 case 0x38: /* Left ALT */
1627 case 0xb8: /* Right ALT */
1628 break;
1629 case 0xc8:
1630 kbd_put_keysym(QEMU_KEY_UP);
1631 break;
1632 case 0xd0:
1633 kbd_put_keysym(QEMU_KEY_DOWN);
1634 break;
1635 case 0xcb:
1636 kbd_put_keysym(QEMU_KEY_LEFT);
1637 break;
1638 case 0xcd:
1639 kbd_put_keysym(QEMU_KEY_RIGHT);
1640 break;
1641 case 0xd3:
1642 kbd_put_keysym(QEMU_KEY_DELETE);
1643 break;
1644 case 0xc7:
1645 kbd_put_keysym(QEMU_KEY_HOME);
1646 break;
1647 case 0xcf:
1648 kbd_put_keysym(QEMU_KEY_END);
1649 break;
1650 case 0xc9:
1651 kbd_put_keysym(QEMU_KEY_PAGEUP);
1652 break;
1653 case 0xd1:
1654 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1655 break;
1656
1657 case 0x47:
1658 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1659 break;
1660 case 0x48:
1661 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1662 break;
1663 case 0x49:
1664 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1665 break;
1666 case 0x4b:
1667 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1668 break;
1669 case 0x4c:
1670 kbd_put_keysym('5');
1671 break;
1672 case 0x4d:
1673 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1674 break;
1675 case 0x4f:
1676 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1677 break;
1678 case 0x50:
1679 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1680 break;
1681 case 0x51:
1682 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1683 break;
1684 case 0x52:
1685 kbd_put_keysym('0');
1686 break;
1687 case 0x53:
1688 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1689 break;
1690
1691 case 0xb5:
1692 kbd_put_keysym('/');
1693 break;
1694 case 0x37:
1695 kbd_put_keysym('*');
1696 break;
1697 case 0x4a:
1698 kbd_put_keysym('-');
1699 break;
1700 case 0x4e:
1701 kbd_put_keysym('+');
1702 break;
1703 case 0x9c:
1704 kbd_put_keysym('\n');
1705 break;
1706
1707 default:
1708 if (control) {
1709 kbd_put_keysym(sym & 0x1f);
1710 } else {
1711 kbd_put_keysym(sym);
1712 }
1713 break;
1714 }
1715 }
1716 }
1717 }
1718
1719 static void vnc_release_modifiers(VncState *vs)
1720 {
1721 static const int keycodes[] = {
1722 /* shift, control, alt keys, both left & right */
1723 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1724 };
1725 int i, keycode;
1726
1727 if (!is_graphic_console()) {
1728 return;
1729 }
1730 for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1731 keycode = keycodes[i];
1732 if (!vs->modifiers_state[keycode]) {
1733 continue;
1734 }
1735 if (keycode & SCANCODE_GREY) {
1736 kbd_put_keycode(SCANCODE_EMUL0);
1737 }
1738 kbd_put_keycode(keycode | SCANCODE_UP);
1739 }
1740 }
1741
1742 static void key_event(VncState *vs, int down, uint32_t sym)
1743 {
1744 int keycode;
1745 int lsym = sym;
1746
1747 if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1748 lsym = lsym - 'A' + 'a';
1749 }
1750
1751 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1752 do_key_event(vs, down, keycode, sym);
1753 }
1754
1755 static void ext_key_event(VncState *vs, int down,
1756 uint32_t sym, uint16_t keycode)
1757 {
1758 /* if the user specifies a keyboard layout, always use it */
1759 if (keyboard_layout)
1760 key_event(vs, down, sym);
1761 else
1762 do_key_event(vs, down, keycode, sym);
1763 }
1764
1765 static void framebuffer_update_request(VncState *vs, int incremental,
1766 int x_position, int y_position,
1767 int w, int h)
1768 {
1769 int i;
1770 const size_t width = ds_get_width(vs->ds) / 16;
1771
1772 if (y_position > ds_get_height(vs->ds))
1773 y_position = ds_get_height(vs->ds);
1774 if (y_position + h >= ds_get_height(vs->ds))
1775 h = ds_get_height(vs->ds) - y_position;
1776
1777 vs->need_update = 1;
1778 if (!incremental) {
1779 vs->force_update = 1;
1780 for (i = 0; i < h; i++) {
1781 bitmap_set(vs->dirty[y_position + i], 0, width);
1782 bitmap_clear(vs->dirty[y_position + i], width,
1783 VNC_DIRTY_BITS - width);
1784 }
1785 }
1786 }
1787
1788 static void send_ext_key_event_ack(VncState *vs)
1789 {
1790 vnc_lock_output(vs);
1791 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1792 vnc_write_u8(vs, 0);
1793 vnc_write_u16(vs, 1);
1794 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1795 VNC_ENCODING_EXT_KEY_EVENT);
1796 vnc_unlock_output(vs);
1797 vnc_flush(vs);
1798 }
1799
1800 static void send_ext_audio_ack(VncState *vs)
1801 {
1802 vnc_lock_output(vs);
1803 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1804 vnc_write_u8(vs, 0);
1805 vnc_write_u16(vs, 1);
1806 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1807 VNC_ENCODING_AUDIO);
1808 vnc_unlock_output(vs);
1809 vnc_flush(vs);
1810 }
1811
1812 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1813 {
1814 int i;
1815 unsigned int enc = 0;
1816
1817 vs->features = 0;
1818 vs->vnc_encoding = 0;
1819 vs->tight.compression = 9;
1820 vs->tight.quality = -1; /* Lossless by default */
1821 vs->absolute = -1;
1822
1823 /*
1824 * Start from the end because the encodings are sent in order of preference.
1825 * This way the preferred encoding (first encoding defined in the array)
1826 * will be set at the end of the loop.
1827 */
1828 for (i = n_encodings - 1; i >= 0; i--) {
1829 enc = encodings[i];
1830 switch (enc) {
1831 case VNC_ENCODING_RAW:
1832 vs->vnc_encoding = enc;
1833 break;
1834 case VNC_ENCODING_COPYRECT:
1835 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1836 break;
1837 case VNC_ENCODING_HEXTILE:
1838 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1839 vs->vnc_encoding = enc;
1840 break;
1841 case VNC_ENCODING_TIGHT:
1842 vs->features |= VNC_FEATURE_TIGHT_MASK;
1843 vs->vnc_encoding = enc;
1844 break;
1845 #ifdef CONFIG_VNC_PNG
1846 case VNC_ENCODING_TIGHT_PNG:
1847 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
1848 vs->vnc_encoding = enc;
1849 break;
1850 #endif
1851 case VNC_ENCODING_ZLIB:
1852 vs->features |= VNC_FEATURE_ZLIB_MASK;
1853 vs->vnc_encoding = enc;
1854 break;
1855 case VNC_ENCODING_ZRLE:
1856 vs->features |= VNC_FEATURE_ZRLE_MASK;
1857 vs->vnc_encoding = enc;
1858 break;
1859 case VNC_ENCODING_ZYWRLE:
1860 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
1861 vs->vnc_encoding = enc;
1862 break;
1863 case VNC_ENCODING_DESKTOPRESIZE:
1864 vs->features |= VNC_FEATURE_RESIZE_MASK;
1865 break;
1866 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1867 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1868 break;
1869 case VNC_ENCODING_RICH_CURSOR:
1870 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1871 break;
1872 case VNC_ENCODING_EXT_KEY_EVENT:
1873 send_ext_key_event_ack(vs);
1874 break;
1875 case VNC_ENCODING_AUDIO:
1876 send_ext_audio_ack(vs);
1877 break;
1878 case VNC_ENCODING_WMVi:
1879 vs->features |= VNC_FEATURE_WMVI_MASK;
1880 break;
1881 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1882 vs->tight.compression = (enc & 0x0F);
1883 break;
1884 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1885 if (vs->vd->lossy) {
1886 vs->tight.quality = (enc & 0x0F);
1887 }
1888 break;
1889 default:
1890 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1891 break;
1892 }
1893 }
1894 vnc_desktop_resize(vs);
1895 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
1896 }
1897
1898 static void set_pixel_conversion(VncState *vs)
1899 {
1900 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
1901
1902 if (fmt == VNC_SERVER_FB_FORMAT) {
1903 vs->write_pixels = vnc_write_pixels_copy;
1904 vnc_hextile_set_pixel_conversion(vs, 0);
1905 } else {
1906 vs->write_pixels = vnc_write_pixels_generic;
1907 vnc_hextile_set_pixel_conversion(vs, 1);
1908 }
1909 }
1910
1911 static void set_pixel_format(VncState *vs,
1912 int bits_per_pixel, int depth,
1913 int big_endian_flag, int true_color_flag,
1914 int red_max, int green_max, int blue_max,
1915 int red_shift, int green_shift, int blue_shift)
1916 {
1917 if (!true_color_flag) {
1918 vnc_client_error(vs);
1919 return;
1920 }
1921
1922 vs->client_pf.rmax = red_max;
1923 vs->client_pf.rbits = hweight_long(red_max);
1924 vs->client_pf.rshift = red_shift;
1925 vs->client_pf.rmask = red_max << red_shift;
1926 vs->client_pf.gmax = green_max;
1927 vs->client_pf.gbits = hweight_long(green_max);
1928 vs->client_pf.gshift = green_shift;
1929 vs->client_pf.gmask = green_max << green_shift;
1930 vs->client_pf.bmax = blue_max;
1931 vs->client_pf.bbits = hweight_long(blue_max);
1932 vs->client_pf.bshift = blue_shift;
1933 vs->client_pf.bmask = blue_max << blue_shift;
1934 vs->client_pf.bits_per_pixel = bits_per_pixel;
1935 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
1936 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1937 vs->client_be = big_endian_flag;
1938
1939 set_pixel_conversion(vs);
1940
1941 vga_hw_invalidate();
1942 vga_hw_update();
1943 }
1944
1945 static void pixel_format_message (VncState *vs) {
1946 char pad[3] = { 0, 0, 0 };
1947
1948 vs->client_pf = qemu_default_pixelformat(32);
1949
1950 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
1951 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
1952
1953 #ifdef HOST_WORDS_BIGENDIAN
1954 vnc_write_u8(vs, 1); /* big-endian-flag */
1955 #else
1956 vnc_write_u8(vs, 0); /* big-endian-flag */
1957 #endif
1958 vnc_write_u8(vs, 1); /* true-color-flag */
1959 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
1960 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
1961 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
1962 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
1963 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
1964 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
1965 vnc_write(vs, pad, 3); /* padding */
1966
1967 vnc_hextile_set_pixel_conversion(vs, 0);
1968 vs->write_pixels = vnc_write_pixels_copy;
1969 }
1970
1971 static void vnc_dpy_setdata(DisplayState *ds)
1972 {
1973 VncDisplay *vd = ds->opaque;
1974
1975 qemu_pixman_image_unref(vd->guest.fb);
1976 vd->guest.fb = pixman_image_ref(ds->surface->image);
1977 vd->guest.format = ds->surface->format;
1978 vnc_dpy_update(ds, 0, 0, ds_get_width(ds), ds_get_height(ds));
1979 }
1980
1981 static void vnc_colordepth(VncState *vs)
1982 {
1983 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1984 /* Sending a WMVi message to notify the client*/
1985 vnc_lock_output(vs);
1986 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1987 vnc_write_u8(vs, 0);
1988 vnc_write_u16(vs, 1); /* number of rects */
1989 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1990 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1991 pixel_format_message(vs);
1992 vnc_unlock_output(vs);
1993 vnc_flush(vs);
1994 } else {
1995 set_pixel_conversion(vs);
1996 }
1997 }
1998
1999 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2000 {
2001 int i;
2002 uint16_t limit;
2003 VncDisplay *vd = vs->vd;
2004
2005 if (data[0] > 3) {
2006 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2007 if (!qemu_timer_expired(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval))
2008 qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval);
2009 }
2010
2011 switch (data[0]) {
2012 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2013 if (len == 1)
2014 return 20;
2015
2016 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
2017 read_u8(data, 6), read_u8(data, 7),
2018 read_u16(data, 8), read_u16(data, 10),
2019 read_u16(data, 12), read_u8(data, 14),
2020 read_u8(data, 15), read_u8(data, 16));
2021 break;
2022 case VNC_MSG_CLIENT_SET_ENCODINGS:
2023 if (len == 1)
2024 return 4;
2025
2026 if (len == 4) {
2027 limit = read_u16(data, 2);
2028 if (limit > 0)
2029 return 4 + (limit * 4);
2030 } else
2031 limit = read_u16(data, 2);
2032
2033 for (i = 0; i < limit; i++) {
2034 int32_t val = read_s32(data, 4 + (i * 4));
2035 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2036 }
2037
2038 set_encodings(vs, (int32_t *)(data + 4), limit);
2039 break;
2040 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2041 if (len == 1)
2042 return 10;
2043
2044 framebuffer_update_request(vs,
2045 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2046 read_u16(data, 6), read_u16(data, 8));
2047 break;
2048 case VNC_MSG_CLIENT_KEY_EVENT:
2049 if (len == 1)
2050 return 8;
2051
2052 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2053 break;
2054 case VNC_MSG_CLIENT_POINTER_EVENT:
2055 if (len == 1)
2056 return 6;
2057
2058 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2059 break;
2060 case VNC_MSG_CLIENT_CUT_TEXT:
2061 if (len == 1)
2062 return 8;
2063
2064 if (len == 8) {
2065 uint32_t dlen = read_u32(data, 4);
2066 if (dlen > 0)
2067 return 8 + dlen;
2068 }
2069
2070 client_cut_text(vs, read_u32(data, 4), data + 8);
2071 break;
2072 case VNC_MSG_CLIENT_QEMU:
2073 if (len == 1)
2074 return 2;
2075
2076 switch (read_u8(data, 1)) {
2077 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2078 if (len == 2)
2079 return 12;
2080
2081 ext_key_event(vs, read_u16(data, 2),
2082 read_u32(data, 4), read_u32(data, 8));
2083 break;
2084 case VNC_MSG_CLIENT_QEMU_AUDIO:
2085 if (len == 2)
2086 return 4;
2087
2088 switch (read_u16 (data, 2)) {
2089 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2090 audio_add(vs);
2091 break;
2092 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2093 audio_del(vs);
2094 break;
2095 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2096 if (len == 4)
2097 return 10;
2098 switch (read_u8(data, 4)) {
2099 case 0: vs->as.fmt = AUD_FMT_U8; break;
2100 case 1: vs->as.fmt = AUD_FMT_S8; break;
2101 case 2: vs->as.fmt = AUD_FMT_U16; break;
2102 case 3: vs->as.fmt = AUD_FMT_S16; break;
2103 case 4: vs->as.fmt = AUD_FMT_U32; break;
2104 case 5: vs->as.fmt = AUD_FMT_S32; break;
2105 default:
2106 printf("Invalid audio format %d\n", read_u8(data, 4));
2107 vnc_client_error(vs);
2108 break;
2109 }
2110 vs->as.nchannels = read_u8(data, 5);
2111 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2112 printf("Invalid audio channel coount %d\n",
2113 read_u8(data, 5));
2114 vnc_client_error(vs);
2115 break;
2116 }
2117 vs->as.freq = read_u32(data, 6);
2118 break;
2119 default:
2120 printf ("Invalid audio message %d\n", read_u8(data, 4));
2121 vnc_client_error(vs);
2122 break;
2123 }
2124 break;
2125
2126 default:
2127 printf("Msg: %d\n", read_u16(data, 0));
2128 vnc_client_error(vs);
2129 break;
2130 }
2131 break;
2132 default:
2133 printf("Msg: %d\n", data[0]);
2134 vnc_client_error(vs);
2135 break;
2136 }
2137
2138 vnc_read_when(vs, protocol_client_msg, 1);
2139 return 0;
2140 }
2141
2142 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2143 {
2144 char buf[1024];
2145 VncShareMode mode;
2146 int size;
2147
2148 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2149 switch (vs->vd->share_policy) {
2150 case VNC_SHARE_POLICY_IGNORE:
2151 /*
2152 * Ignore the shared flag. Nothing to do here.
2153 *
2154 * Doesn't conform to the rfb spec but is traditional qemu
2155 * behavior, thus left here as option for compatibility
2156 * reasons.
2157 */
2158 break;
2159 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2160 /*
2161 * Policy: Allow clients ask for exclusive access.
2162 *
2163 * Implementation: When a client asks for exclusive access,
2164 * disconnect all others. Shared connects are allowed as long
2165 * as no exclusive connection exists.
2166 *
2167 * This is how the rfb spec suggests to handle the shared flag.
2168 */
2169 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2170 VncState *client;
2171 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2172 if (vs == client) {
2173 continue;
2174 }
2175 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2176 client->share_mode != VNC_SHARE_MODE_SHARED) {
2177 continue;
2178 }
2179 vnc_disconnect_start(client);
2180 }
2181 }
2182 if (mode == VNC_SHARE_MODE_SHARED) {
2183 if (vs->vd->num_exclusive > 0) {
2184 vnc_disconnect_start(vs);
2185 return 0;
2186 }
2187 }
2188 break;
2189 case VNC_SHARE_POLICY_FORCE_SHARED:
2190 /*
2191 * Policy: Shared connects only.
2192 * Implementation: Disallow clients asking for exclusive access.
2193 *
2194 * Useful for shared desktop sessions where you don't want
2195 * someone forgetting to say -shared when running the vnc
2196 * client disconnect everybody else.
2197 */
2198 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2199 vnc_disconnect_start(vs);
2200 return 0;
2201 }
2202 break;
2203 }
2204 vnc_set_share_mode(vs, mode);
2205
2206 vs->client_width = ds_get_width(vs->ds);
2207 vs->client_height = ds_get_height(vs->ds);
2208 vnc_write_u16(vs, vs->client_width);
2209 vnc_write_u16(vs, vs->client_height);
2210
2211 pixel_format_message(vs);
2212
2213 if (qemu_name)
2214 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2215 else
2216 size = snprintf(buf, sizeof(buf), "QEMU");
2217
2218 vnc_write_u32(vs, size);
2219 vnc_write(vs, buf, size);
2220 vnc_flush(vs);
2221
2222 vnc_client_cache_auth(vs);
2223 vnc_qmp_event(vs, QEVENT_VNC_INITIALIZED);
2224
2225 vnc_read_when(vs, protocol_client_msg, 1);
2226
2227 return 0;
2228 }
2229
2230 void start_client_init(VncState *vs)
2231 {
2232 vnc_read_when(vs, protocol_client_init, 1);
2233 }
2234
2235 static void make_challenge(VncState *vs)
2236 {
2237 int i;
2238
2239 srand(time(NULL)+getpid()+getpid()*987654+rand());
2240
2241 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2242 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2243 }
2244
2245 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2246 {
2247 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2248 int i, j, pwlen;
2249 unsigned char key[8];
2250 time_t now = time(NULL);
2251
2252 if (!vs->vd->password) {
2253 VNC_DEBUG("No password configured on server");
2254 goto reject;
2255 }
2256 if (vs->vd->expires < now) {
2257 VNC_DEBUG("Password is expired");
2258 goto reject;
2259 }
2260
2261 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2262
2263 /* Calculate the expected challenge response */
2264 pwlen = strlen(vs->vd->password);
2265 for (i=0; i<sizeof(key); i++)
2266 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2267 deskey(key, EN0);
2268 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2269 des(response+j, response+j);
2270
2271 /* Compare expected vs actual challenge response */
2272 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2273 VNC_DEBUG("Client challenge response did not match\n");
2274 goto reject;
2275 } else {
2276 VNC_DEBUG("Accepting VNC challenge response\n");
2277 vnc_write_u32(vs, 0); /* Accept auth */
2278 vnc_flush(vs);
2279
2280 start_client_init(vs);
2281 }
2282 return 0;
2283
2284 reject:
2285 vnc_write_u32(vs, 1); /* Reject auth */
2286 if (vs->minor >= 8) {
2287 static const char err[] = "Authentication failed";
2288 vnc_write_u32(vs, sizeof(err));
2289 vnc_write(vs, err, sizeof(err));
2290 }
2291 vnc_flush(vs);
2292 vnc_client_error(vs);
2293 return 0;
2294 }
2295
2296 void start_auth_vnc(VncState *vs)
2297 {
2298 make_challenge(vs);
2299 /* Send client a 'random' challenge */
2300 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2301 vnc_flush(vs);
2302
2303 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2304 }
2305
2306
2307 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2308 {
2309 /* We only advertise 1 auth scheme at a time, so client
2310 * must pick the one we sent. Verify this */
2311 if (data[0] != vs->auth) { /* Reject auth */
2312 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2313 vnc_write_u32(vs, 1);
2314 if (vs->minor >= 8) {
2315 static const char err[] = "Authentication failed";
2316 vnc_write_u32(vs, sizeof(err));
2317 vnc_write(vs, err, sizeof(err));
2318 }
2319 vnc_client_error(vs);
2320 } else { /* Accept requested auth */
2321 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2322 switch (vs->auth) {
2323 case VNC_AUTH_NONE:
2324 VNC_DEBUG("Accept auth none\n");
2325 if (vs->minor >= 8) {
2326 vnc_write_u32(vs, 0); /* Accept auth completion */
2327 vnc_flush(vs);
2328 }
2329 start_client_init(vs);
2330 break;
2331
2332 case VNC_AUTH_VNC:
2333 VNC_DEBUG("Start VNC auth\n");
2334 start_auth_vnc(vs);
2335 break;
2336
2337 #ifdef CONFIG_VNC_TLS
2338 case VNC_AUTH_VENCRYPT:
2339 VNC_DEBUG("Accept VeNCrypt auth\n");
2340 start_auth_vencrypt(vs);
2341 break;
2342 #endif /* CONFIG_VNC_TLS */
2343
2344 #ifdef CONFIG_VNC_SASL
2345 case VNC_AUTH_SASL:
2346 VNC_DEBUG("Accept SASL auth\n");
2347 start_auth_sasl(vs);
2348 break;
2349 #endif /* CONFIG_VNC_SASL */
2350
2351 default: /* Should not be possible, but just in case */
2352 VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2353 vnc_write_u8(vs, 1);
2354 if (vs->minor >= 8) {
2355 static const char err[] = "Authentication failed";
2356 vnc_write_u32(vs, sizeof(err));
2357 vnc_write(vs, err, sizeof(err));
2358 }
2359 vnc_client_error(vs);
2360 }
2361 }
2362 return 0;
2363 }
2364
2365 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2366 {
2367 char local[13];
2368
2369 memcpy(local, version, 12);
2370 local[12] = 0;
2371
2372 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2373 VNC_DEBUG("Malformed protocol version %s\n", local);
2374 vnc_client_error(vs);
2375 return 0;
2376 }
2377 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2378 if (vs->major != 3 ||
2379 (vs->minor != 3 &&
2380 vs->minor != 4 &&
2381 vs->minor != 5 &&
2382 vs->minor != 7 &&
2383 vs->minor != 8)) {
2384 VNC_DEBUG("Unsupported client version\n");
2385 vnc_write_u32(vs, VNC_AUTH_INVALID);
2386 vnc_flush(vs);
2387 vnc_client_error(vs);
2388 return 0;
2389 }
2390 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2391 * as equivalent to v3.3 by servers
2392 */
2393 if (vs->minor == 4 || vs->minor == 5)
2394 vs->minor = 3;
2395
2396 if (vs->minor == 3) {
2397 if (vs->auth == VNC_AUTH_NONE) {
2398 VNC_DEBUG("Tell client auth none\n");
2399 vnc_write_u32(vs, vs->auth);
2400 vnc_flush(vs);
2401 start_client_init(vs);
2402 } else if (vs->auth == VNC_AUTH_VNC) {
2403 VNC_DEBUG("Tell client VNC auth\n");
2404 vnc_write_u32(vs, vs->auth);
2405 vnc_flush(vs);
2406 start_auth_vnc(vs);
2407 } else {
2408 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2409 vnc_write_u32(vs, VNC_AUTH_INVALID);
2410 vnc_flush(vs);
2411 vnc_client_error(vs);
2412 }
2413 } else {
2414 VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2415 vnc_write_u8(vs, 1); /* num auth */
2416 vnc_write_u8(vs, vs->auth);
2417 vnc_read_when(vs, protocol_client_auth, 1);
2418 vnc_flush(vs);
2419 }
2420
2421 return 0;
2422 }
2423
2424 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2425 {
2426 struct VncSurface *vs = &vd->guest;
2427
2428 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2429 }
2430
2431 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2432 {
2433 int i, j;
2434
2435 w = (x + w) / VNC_STAT_RECT;
2436 h = (y + h) / VNC_STAT_RECT;
2437 x /= VNC_STAT_RECT;
2438 y /= VNC_STAT_RECT;
2439
2440 for (j = y; j <= h; j++) {
2441 for (i = x; i <= w; i++) {
2442 vs->lossy_rect[j][i] = 1;
2443 }
2444 }
2445 }
2446
2447 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2448 {
2449 VncState *vs;
2450 int sty = y / VNC_STAT_RECT;
2451 int stx = x / VNC_STAT_RECT;
2452 int has_dirty = 0;
2453
2454 y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2455 x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2456
2457 QTAILQ_FOREACH(vs, &vd->clients, next) {
2458 int j;
2459
2460 /* kernel send buffers are full -> refresh later */
2461 if (vs->output.offset) {
2462 continue;
2463 }
2464
2465 if (!vs->lossy_rect[sty][stx]) {
2466 continue;
2467 }
2468
2469 vs->lossy_rect[sty][stx] = 0;
2470 for (j = 0; j < VNC_STAT_RECT; ++j) {
2471 bitmap_set(vs->dirty[y + j], x / 16, VNC_STAT_RECT / 16);
2472 }
2473 has_dirty++;
2474 }
2475
2476 return has_dirty;
2477 }
2478
2479 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2480 {
2481 int width = pixman_image_get_width(vd->guest.fb);
2482 int height = pixman_image_get_height(vd->guest.fb);
2483 int x, y;
2484 struct timeval res;
2485 int has_dirty = 0;
2486
2487 for (y = 0; y < height; y += VNC_STAT_RECT) {
2488 for (x = 0; x < width; x += VNC_STAT_RECT) {
2489 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2490
2491 rect->updated = false;
2492 }
2493 }
2494
2495 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2496
2497 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2498 return has_dirty;
2499 }
2500 vd->guest.last_freq_check = *tv;
2501
2502 for (y = 0; y < height; y += VNC_STAT_RECT) {
2503 for (x = 0; x < width; x += VNC_STAT_RECT) {
2504 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2505 int count = ARRAY_SIZE(rect->times);
2506 struct timeval min, max;
2507
2508 if (!timerisset(&rect->times[count - 1])) {
2509 continue ;
2510 }
2511
2512 max = rect->times[(rect->idx + count - 1) % count];
2513 qemu_timersub(tv, &max, &res);
2514
2515 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2516 rect->freq = 0;
2517 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2518 memset(rect->times, 0, sizeof (rect->times));
2519 continue ;
2520 }
2521
2522 min = rect->times[rect->idx];
2523 max = rect->times[(rect->idx + count - 1) % count];
2524 qemu_timersub(&max, &min, &res);
2525
2526 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2527 rect->freq /= count;
2528 rect->freq = 1. / rect->freq;
2529 }
2530 }
2531 return has_dirty;
2532 }
2533
2534 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2535 {
2536 int i, j;
2537 double total = 0;
2538 int num = 0;
2539
2540 x = (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2541 y = (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2542
2543 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2544 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2545 total += vnc_stat_rect(vs->vd, i, j)->freq;
2546 num++;
2547 }
2548 }
2549
2550 if (num) {
2551 return total / num;
2552 } else {
2553 return 0;
2554 }
2555 }
2556
2557 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2558 {
2559 VncRectStat *rect;
2560
2561 rect = vnc_stat_rect(vd, x, y);
2562 if (rect->updated) {
2563 return ;
2564 }
2565 rect->times[rect->idx] = *tv;
2566 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2567 rect->updated = true;
2568 }
2569
2570 static int vnc_refresh_server_surface(VncDisplay *vd)
2571 {
2572 int width = pixman_image_get_width(vd->guest.fb);
2573 int height = pixman_image_get_height(vd->guest.fb);
2574 int y;
2575 uint8_t *guest_row;
2576 uint8_t *server_row;
2577 int cmp_bytes;
2578 VncState *vs;
2579 int has_dirty = 0;
2580 pixman_image_t *tmpbuf = NULL;
2581
2582 struct timeval tv = { 0, 0 };
2583
2584 if (!vd->non_adaptive) {
2585 gettimeofday(&tv, NULL);
2586 has_dirty = vnc_update_stats(vd, &tv);
2587 }
2588
2589 /*
2590 * Walk through the guest dirty map.
2591 * Check and copy modified bits from guest to server surface.
2592 * Update server dirty map.
2593 */
2594 cmp_bytes = 64;
2595 if (cmp_bytes > vnc_server_fb_stride(vd)) {
2596 cmp_bytes = vnc_server_fb_stride(vd);
2597 }
2598 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2599 int width = pixman_image_get_width(vd->server);
2600 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2601 }
2602 guest_row = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2603 server_row = (uint8_t *)pixman_image_get_data(vd->server);
2604 for (y = 0; y < height; y++) {
2605 if (!bitmap_empty(vd->guest.dirty[y], VNC_DIRTY_BITS)) {
2606 int x;
2607 uint8_t *guest_ptr;
2608 uint8_t *server_ptr;
2609
2610 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2611 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2612 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2613 } else {
2614 guest_ptr = guest_row;
2615 }
2616 server_ptr = server_row;
2617
2618 for (x = 0; x + 15 < width;
2619 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2620 if (!test_and_clear_bit((x / 16), vd->guest.dirty[y]))
2621 continue;
2622 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2623 continue;
2624 memcpy(server_ptr, guest_ptr, cmp_bytes);
2625 if (!vd->non_adaptive)
2626 vnc_rect_updated(vd, x, y, &tv);
2627 QTAILQ_FOREACH(vs, &vd->clients, next) {
2628 set_bit((x / 16), vs->dirty[y]);
2629 }
2630 has_dirty++;
2631 }
2632 }
2633 guest_row += pixman_image_get_stride(vd->guest.fb);
2634 server_row += pixman_image_get_stride(vd->server);
2635 }
2636 qemu_pixman_image_unref(tmpbuf);
2637 return has_dirty;
2638 }
2639
2640 static void vnc_refresh(void *opaque)
2641 {
2642 VncDisplay *vd = opaque;
2643 VncState *vs, *vn;
2644 int has_dirty, rects = 0;
2645
2646 vga_hw_update();
2647
2648 if (vnc_trylock_display(vd)) {
2649 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2650 qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) +
2651 vd->timer_interval);
2652 return;
2653 }
2654
2655 has_dirty = vnc_refresh_server_surface(vd);
2656 vnc_unlock_display(vd);
2657
2658 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2659 rects += vnc_update_client(vs, has_dirty);
2660 /* vs might be free()ed here */
2661 }
2662
2663 /* vd->timer could be NULL now if the last client disconnected,
2664 * in this case don't update the timer */
2665 if (vd->timer == NULL)
2666 return;
2667
2668 if (has_dirty && rects) {
2669 vd->timer_interval /= 2;
2670 if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2671 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2672 } else {
2673 vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2674 if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2675 vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2676 }
2677 qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval);
2678 }
2679
2680 static void vnc_init_timer(VncDisplay *vd)
2681 {
2682 vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2683 if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {
2684 vd->timer = qemu_new_timer_ms(rt_clock, vnc_refresh, vd);
2685 vnc_dpy_resize(vd->ds);
2686 vnc_refresh(vd);
2687 }
2688 }
2689
2690 static void vnc_remove_timer(VncDisplay *vd)
2691 {
2692 if (vd->timer != NULL && QTAILQ_EMPTY(&vd->clients)) {
2693 qemu_del_timer(vd->timer);
2694 qemu_free_timer(vd->timer);
2695 vd->timer = NULL;
2696 }
2697 }
2698
2699 static void vnc_connect(VncDisplay *vd, int csock, int skipauth, bool websocket)
2700 {
2701 VncState *vs = g_malloc0(sizeof(VncState));
2702 int i;
2703
2704 vs->csock = csock;
2705
2706 if (skipauth) {
2707 vs->auth = VNC_AUTH_NONE;
2708 #ifdef CONFIG_VNC_TLS
2709 vs->subauth = VNC_AUTH_INVALID;
2710 #endif
2711 } else {
2712 vs->auth = vd->auth;
2713 #ifdef CONFIG_VNC_TLS
2714 vs->subauth = vd->subauth;
2715 #endif
2716 }
2717
2718 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
2719 for (i = 0; i < VNC_STAT_ROWS; ++i) {
2720 vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
2721 }
2722
2723 VNC_DEBUG("New client on socket %d\n", csock);
2724 dcl->idle = 0;
2725 socket_set_nonblock(vs->csock);
2726 #ifdef CONFIG_VNC_WS
2727 if (websocket) {
2728 vs->websocket = 1;
2729 qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read, NULL, vs);
2730 } else
2731 #endif /* CONFIG_VNC_WS */
2732 {
2733 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2734 }
2735
2736 vnc_client_cache_addr(vs);
2737 vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
2738 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
2739
2740 vs->vd = vd;
2741
2742 #ifdef CONFIG_VNC_WS
2743 if (!vs->websocket)
2744 #endif
2745 {
2746 vnc_init_state(vs);
2747 }
2748 }
2749
2750 void vnc_init_state(VncState *vs)
2751 {
2752 VncDisplay *vd = vs->vd;
2753
2754 vs->ds = vd->ds;
2755 vs->last_x = -1;
2756 vs->last_y = -1;
2757
2758 vs->as.freq = 44100;
2759 vs->as.nchannels = 2;
2760 vs->as.fmt = AUD_FMT_S16;
2761 vs->as.endianness = 0;
2762
2763 qemu_mutex_init(&vs->output_mutex);
2764 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
2765
2766 QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2767
2768 vga_hw_update();
2769
2770 vnc_write(vs, "RFB 003.008\n", 12);
2771 vnc_flush(vs);
2772 vnc_read_when(vs, protocol_version, 12);
2773 reset_keys(vs);
2774 if (vs->vd->lock_key_sync)
2775 vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2776
2777 vs->mouse_mode_notifier.notify = check_pointer_type_change;
2778 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2779
2780 vnc_init_timer(vd);
2781
2782 /* vs might be free()ed here */
2783 }
2784
2785 static void vnc_listen_read(void *opaque, bool websocket)
2786 {
2787 VncDisplay *vs = opaque;
2788 struct sockaddr_in addr;
2789 socklen_t addrlen = sizeof(addr);
2790 int csock;
2791
2792 /* Catch-up */
2793 vga_hw_update();
2794 #ifdef CONFIG_VNC_WS
2795 if (websocket) {
2796 csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
2797 } else
2798 #endif /* CONFIG_VNC_WS */
2799 {
2800 csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2801 }
2802
2803 if (csock != -1) {
2804 vnc_connect(vs, csock, 0, websocket);
2805 }
2806 }
2807
2808 static void vnc_listen_regular_read(void *opaque)
2809 {
2810 vnc_listen_read(opaque, 0);
2811 }
2812
2813 #ifdef CONFIG_VNC_WS
2814 static void vnc_listen_websocket_read(void *opaque)
2815 {
2816 vnc_listen_read(opaque, 1);
2817 }
2818 #endif /* CONFIG_VNC_WS */
2819
2820 void vnc_display_init(DisplayState *ds)
2821 {
2822 VncDisplay *vs = g_malloc0(sizeof(*vs));
2823
2824 dcl = g_malloc0(sizeof(DisplayChangeListener));
2825
2826 ds->opaque = vs;
2827 dcl->idle = 1;
2828 vnc_display = vs;
2829
2830 vs->lsock = -1;
2831 #ifdef CONFIG_VNC_WS
2832 vs->lwebsock = -1;
2833 #endif
2834
2835 vs->ds = ds;
2836 QTAILQ_INIT(&vs->clients);
2837 vs->expires = TIME_MAX;
2838
2839 if (keyboard_layout)
2840 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2841 else
2842 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2843
2844 if (!vs->kbd_layout)
2845 exit(1);
2846
2847 qemu_mutex_init(&vs->mutex);
2848 vnc_start_worker_thread();
2849
2850 dcl->dpy_gfx_copy = vnc_dpy_copy;
2851 dcl->dpy_gfx_update = vnc_dpy_update;
2852 dcl->dpy_gfx_resize = vnc_dpy_resize;
2853 dcl->dpy_gfx_setdata = vnc_dpy_setdata;
2854 dcl->dpy_mouse_set = vnc_mouse_set;
2855 dcl->dpy_cursor_define = vnc_dpy_cursor_define;
2856 register_displaychangelistener(ds, dcl);
2857 }
2858
2859
2860 static void vnc_display_close(DisplayState *ds)
2861 {
2862 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2863
2864 if (!vs)
2865 return;
2866 if (vs->display) {
2867 g_free(vs->display);
2868 vs->display = NULL;
2869 }
2870 if (vs->lsock != -1) {
2871 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2872 close(vs->lsock);
2873 vs->lsock = -1;
2874 }
2875 #ifdef CONFIG_VNC_WS
2876 g_free(vs->ws_display);
2877 vs->ws_display = NULL;
2878 if (vs->lwebsock != -1) {
2879 qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
2880 close(vs->lwebsock);
2881 vs->lwebsock = -1;
2882 }
2883 #endif /* CONFIG_VNC_WS */
2884 vs->auth = VNC_AUTH_INVALID;
2885 #ifdef CONFIG_VNC_TLS
2886 vs->subauth = VNC_AUTH_INVALID;
2887 vs->tls.x509verify = 0;
2888 #endif
2889 }
2890
2891 static int vnc_display_disable_login(DisplayState *ds)
2892 {
2893 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2894
2895 if (!vs) {
2896 return -1;
2897 }
2898
2899 if (vs->password) {
2900 g_free(vs->password);
2901 }
2902
2903 vs->password = NULL;
2904 if (vs->auth == VNC_AUTH_NONE) {
2905 vs->auth = VNC_AUTH_VNC;
2906 }
2907
2908 return 0;
2909 }
2910
2911 int vnc_display_password(DisplayState *ds, const char *password)
2912 {
2913 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2914
2915 if (!vs) {
2916 return -EINVAL;
2917 }
2918
2919 if (!password) {
2920 /* This is not the intention of this interface but err on the side
2921 of being safe */
2922 return vnc_display_disable_login(ds);
2923 }
2924
2925 if (vs->password) {
2926 g_free(vs->password);
2927 vs->password = NULL;
2928 }
2929 vs->password = g_strdup(password);
2930 if (vs->auth == VNC_AUTH_NONE) {
2931 vs->auth = VNC_AUTH_VNC;
2932 }
2933
2934 return 0;
2935 }
2936
2937 int vnc_display_pw_expire(DisplayState *ds, time_t expires)
2938 {
2939 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2940
2941 if (!vs) {
2942 return -EINVAL;
2943 }
2944
2945 vs->expires = expires;
2946 return 0;
2947 }
2948
2949 char *vnc_display_local_addr(DisplayState *ds)
2950 {
2951 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2952
2953 return vnc_socket_local_addr("%s:%s", vs->lsock);
2954 }
2955
2956 void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
2957 {
2958 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2959 const char *options;
2960 int password = 0;
2961 int reverse = 0;
2962 #ifdef CONFIG_VNC_TLS
2963 int tls = 0, x509 = 0;
2964 #endif
2965 #ifdef CONFIG_VNC_SASL
2966 int sasl = 0;
2967 int saslErr;
2968 #endif
2969 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
2970 int acl = 0;
2971 #endif
2972 int lock_key_sync = 1;
2973
2974 if (!vnc_display) {
2975 error_setg(errp, "VNC display not active");
2976 return;
2977 }
2978 vnc_display_close(ds);
2979 if (strcmp(display, "none") == 0)
2980 return;
2981
2982 vs->display = g_strdup(display);
2983 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
2984
2985 options = display;
2986 while ((options = strchr(options, ','))) {
2987 options++;
2988 if (strncmp(options, "password", 8) == 0) {
2989 if (fips_get_state()) {
2990 error_setg(errp,
2991 "VNC password auth disabled due to FIPS mode, "
2992 "consider using the VeNCrypt or SASL authentication "
2993 "methods as an alternative");
2994 goto fail;
2995 }
2996 password = 1; /* Require password auth */
2997 } else if (strncmp(options, "reverse", 7) == 0) {
2998 reverse = 1;
2999 } else if (strncmp(options, "no-lock-key-sync", 16) == 0) {
3000 lock_key_sync = 0;
3001 #ifdef CONFIG_VNC_SASL
3002 } else if (strncmp(options, "sasl", 4) == 0) {
3003 sasl = 1; /* Require SASL auth */
3004 #endif
3005 #ifdef CONFIG_VNC_WS
3006 } else if (strncmp(options, "websocket", 9) == 0) {
3007 char *start, *end;
3008 vs->websocket = 1;
3009
3010 /* Check for 'websocket=<port>' */
3011 start = strchr(options, '=');
3012 end = strchr(options, ',');
3013 if (start && (!end || (start < end))) {
3014 int len = end ? end-(start+1) : strlen(start+1);
3015 if (len < 6) {
3016 /* extract the host specification from display */
3017 char *host = NULL, *port = NULL, *host_end = NULL;
3018 port = g_strndup(start + 1, len);
3019
3020 /* ipv6 hosts have colons */
3021 end = strchr(display, ',');
3022 host_end = g_strrstr_len(display, end - display, ":");
3023
3024 if (host_end) {
3025 host = g_strndup(display, host_end - display + 1);
3026 } else {
3027 host = g_strndup(":", 1);
3028 }
3029 vs->ws_display = g_strconcat(host, port, NULL);
3030 g_free(host);
3031 g_free(port);
3032 }
3033 }
3034 #endif /* CONFIG_VNC_WS */
3035 #ifdef CONFIG_VNC_TLS
3036 } else if (strncmp(options, "tls", 3) == 0) {
3037 tls = 1; /* Require TLS */
3038 } else if (strncmp(options, "x509", 4) == 0) {
3039 char *start, *end;
3040 x509 = 1; /* Require x509 certificates */
3041 if (strncmp(options, "x509verify", 10) == 0)
3042 vs->tls.x509verify = 1; /* ...and verify client certs */
3043
3044 /* Now check for 'x509=/some/path' postfix
3045 * and use that to setup x509 certificate/key paths */
3046 start = strchr(options, '=');
3047 end = strchr(options, ',');
3048 if (start && (!end || (start < end))) {
3049 int len = end ? end-(start+1) : strlen(start+1);
3050 char *path = g_strndup(start + 1, len);
3051
3052 VNC_DEBUG("Trying certificate path '%s'\n", path);
3053 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
3054 error_setg(errp, "Failed to find x509 certificates/keys in %s", path);
3055 g_free(path);
3056 goto fail;
3057 }
3058 g_free(path);
3059 } else {
3060 error_setg(errp, "No certificate path provided");
3061 goto fail;
3062 }
3063 #endif
3064 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
3065 } else if (strncmp(options, "acl", 3) == 0) {
3066 acl = 1;
3067 #endif
3068 } else if (strncmp(options, "lossy", 5) == 0) {
3069 vs->lossy = true;
3070 } else if (strncmp(options, "non-adaptive", 12) == 0) {
3071 vs->non_adaptive = true;
3072 } else if (strncmp(options, "share=", 6) == 0) {
3073 if (strncmp(options+6, "ignore", 6) == 0) {
3074 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
3075 } else if (strncmp(options+6, "allow-exclusive", 15) == 0) {
3076 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3077 } else if (strncmp(options+6, "force-shared", 12) == 0) {
3078 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3079 } else {
3080 error_setg(errp, "unknown vnc share= option");
3081 goto fail;
3082 }
3083 }
3084 }
3085
3086 #ifdef CONFIG_VNC_TLS
3087 if (acl && x509 && vs->tls.x509verify) {
3088 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
3089 fprintf(stderr, "Failed to create x509 dname ACL\n");
3090 exit(1);
3091 }
3092 }
3093 #endif
3094 #ifdef CONFIG_VNC_SASL
3095 if (acl && sasl) {
3096 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
3097 fprintf(stderr, "Failed to create username ACL\n");
3098 exit(1);
3099 }
3100 }
3101 #endif
3102
3103 /*
3104 * Combinations we support here:
3105 *
3106 * - no-auth (clear text, no auth)
3107 * - password (clear text, weak auth)
3108 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
3109 * - tls (encrypt, weak anonymous creds, no auth)
3110 * - tls + password (encrypt, weak anonymous creds, weak auth)
3111 * - tls + sasl (encrypt, weak anonymous creds, good auth)
3112 * - tls + x509 (encrypt, good x509 creds, no auth)
3113 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
3114 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
3115 *
3116 * NB1. TLS is a stackable auth scheme.
3117 * NB2. the x509 schemes have option to validate a client cert dname
3118 */
3119 if (password) {
3120 #ifdef CONFIG_VNC_TLS
3121 if (tls) {
3122 vs->auth = VNC_AUTH_VENCRYPT;
3123 if (x509) {
3124 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3125 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
3126 } else {
3127 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3128 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3129 }
3130 } else {
3131 #endif /* CONFIG_VNC_TLS */
3132 VNC_DEBUG("Initializing VNC server with password auth\n");
3133 vs->auth = VNC_AUTH_VNC;
3134 #ifdef CONFIG_VNC_TLS
3135 vs->subauth = VNC_AUTH_INVALID;
3136 }
3137 #endif /* CONFIG_VNC_TLS */
3138 #ifdef CONFIG_VNC_SASL
3139 } else if (sasl) {
3140 #ifdef CONFIG_VNC_TLS
3141 if (tls) {
3142 vs->auth = VNC_AUTH_VENCRYPT;
3143 if (x509) {
3144 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3145 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3146 } else {
3147 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3148 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3149 }
3150 } else {
3151 #endif /* CONFIG_VNC_TLS */
3152 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3153 vs->auth = VNC_AUTH_SASL;
3154 #ifdef CONFIG_VNC_TLS
3155 vs->subauth = VNC_AUTH_INVALID;
3156 }
3157 #endif /* CONFIG_VNC_TLS */
3158 #endif /* CONFIG_VNC_SASL */
3159 } else {
3160 #ifdef CONFIG_VNC_TLS
3161 if (tls) {
3162 vs->auth = VNC_AUTH_VENCRYPT;
3163 if (x509) {
3164 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3165 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3166 } else {
3167 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3168 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3169 }
3170 } else {
3171 #endif
3172 VNC_DEBUG("Initializing VNC server with no auth\n");
3173 vs->auth = VNC_AUTH_NONE;
3174 #ifdef CONFIG_VNC_TLS
3175 vs->subauth = VNC_AUTH_INVALID;
3176 }
3177 #endif
3178 }
3179
3180 #ifdef CONFIG_VNC_SASL
3181 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3182 error_setg(errp, "Failed to initialize SASL auth: %s",
3183 sasl_errstring(saslErr, NULL, NULL));
3184 goto fail;
3185 }
3186 #endif
3187 vs->lock_key_sync = lock_key_sync;
3188
3189 if (reverse) {
3190 /* connect to viewer */
3191 int csock;
3192 vs->lsock = -1;
3193 #ifdef CONFIG_VNC_WS
3194 vs->lwebsock = -1;
3195 #endif
3196 if (strncmp(display, "unix:", 5) == 0) {
3197 csock = unix_connect(display+5, errp);
3198 } else {
3199 csock = inet_connect(display, errp);
3200 }
3201 if (csock < 0) {
3202 goto fail;
3203 }
3204 vnc_connect(vs, csock, 0, 0);
3205 } else {
3206 /* listen for connects */
3207 char *dpy;
3208 dpy = g_malloc(256);
3209 if (strncmp(display, "unix:", 5) == 0) {
3210 pstrcpy(dpy, 256, "unix:");
3211 vs->lsock = unix_listen(display+5, dpy+5, 256-5, errp);
3212 } else {
3213 vs->lsock = inet_listen(display, dpy, 256,
3214 SOCK_STREAM, 5900, errp);
3215 if (vs->lsock < 0) {
3216 g_free(dpy);
3217 goto fail;
3218 }
3219 #ifdef CONFIG_VNC_WS
3220 if (vs->websocket) {
3221 if (vs->ws_display) {
3222 vs->lwebsock = inet_listen(vs->ws_display, NULL, 256,
3223 SOCK_STREAM, 0, errp);
3224 } else {
3225 vs->lwebsock = inet_listen(vs->display, NULL, 256,
3226 SOCK_STREAM, 5700, errp);
3227 }
3228
3229 if (vs->lwebsock < 0) {
3230 if (vs->lsock) {
3231 close(vs->lsock);
3232 vs->lsock = -1;
3233 }
3234 g_free(dpy);
3235 goto fail;
3236 }
3237 }
3238 #endif /* CONFIG_VNC_WS */
3239 }
3240 g_free(vs->display);
3241 vs->display = dpy;
3242 qemu_set_fd_handler2(vs->lsock, NULL,
3243 vnc_listen_regular_read, NULL, vs);
3244 #ifdef CONFIG_VNC_WS
3245 if (vs->websocket) {
3246 qemu_set_fd_handler2(vs->lwebsock, NULL,
3247 vnc_listen_websocket_read, NULL, vs);
3248 }
3249 #endif /* CONFIG_VNC_WS */
3250 }
3251 return;
3252
3253 fail:
3254 g_free(vs->display);
3255 vs->display = NULL;
3256 #ifdef CONFIG_VNC_WS
3257 g_free(vs->ws_display);
3258 vs->ws_display = NULL;
3259 #endif /* CONFIG_VNC_WS */
3260 }
3261
3262 void vnc_display_add_client(DisplayState *ds, int csock, int skipauth)
3263 {
3264 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
3265
3266 vnc_connect(vs, csock, skipauth, 0);
3267 }