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