]> git.proxmox.com Git - mirror_qemu.git/blob - ui/vnc.c
ui/vnc: Split out authentication_failed
[mirror_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 "sysemu/sysemu.h"
32 #include "qemu/error-report.h"
33 #include "qemu/option.h"
34 #include "qemu/sockets.h"
35 #include "qemu/timer.h"
36 #include "authz/list.h"
37 #include "qemu/config-file.h"
38 #include "qapi/qapi-emit-events.h"
39 #include "qapi/qapi-events-ui.h"
40 #include "qapi/error.h"
41 #include "qapi/qapi-commands-ui.h"
42 #include "ui/input.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 #include "io/dns-resolver.h"
49
50 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
51 #define VNC_REFRESH_INTERVAL_INC 50
52 #define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
53 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
54 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
55
56 #include "vnc_keysym.h"
57 #include "crypto/cipher.h"
58
59 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
60 QTAILQ_HEAD_INITIALIZER(vnc_displays);
61
62 static int vnc_cursor_define(VncState *vs);
63 static void vnc_update_throttle_offset(VncState *vs);
64
65 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
66 {
67 #ifdef _VNC_DEBUG
68 static const char *mn[] = {
69 [0] = "undefined",
70 [VNC_SHARE_MODE_CONNECTING] = "connecting",
71 [VNC_SHARE_MODE_SHARED] = "shared",
72 [VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
73 [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
74 };
75 fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
76 vs->ioc, mn[vs->share_mode], mn[mode]);
77 #endif
78
79 switch (vs->share_mode) {
80 case VNC_SHARE_MODE_CONNECTING:
81 vs->vd->num_connecting--;
82 break;
83 case VNC_SHARE_MODE_SHARED:
84 vs->vd->num_shared--;
85 break;
86 case VNC_SHARE_MODE_EXCLUSIVE:
87 vs->vd->num_exclusive--;
88 break;
89 default:
90 break;
91 }
92
93 vs->share_mode = mode;
94
95 switch (vs->share_mode) {
96 case VNC_SHARE_MODE_CONNECTING:
97 vs->vd->num_connecting++;
98 break;
99 case VNC_SHARE_MODE_SHARED:
100 vs->vd->num_shared++;
101 break;
102 case VNC_SHARE_MODE_EXCLUSIVE:
103 vs->vd->num_exclusive++;
104 break;
105 default:
106 break;
107 }
108 }
109
110
111 static void vnc_init_basic_info(SocketAddress *addr,
112 VncBasicInfo *info,
113 Error **errp)
114 {
115 switch (addr->type) {
116 case SOCKET_ADDRESS_TYPE_INET:
117 info->host = g_strdup(addr->u.inet.host);
118 info->service = g_strdup(addr->u.inet.port);
119 if (addr->u.inet.ipv6) {
120 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
121 } else {
122 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
123 }
124 break;
125
126 case SOCKET_ADDRESS_TYPE_UNIX:
127 info->host = g_strdup("");
128 info->service = g_strdup(addr->u.q_unix.path);
129 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
130 break;
131
132 case SOCKET_ADDRESS_TYPE_VSOCK:
133 case SOCKET_ADDRESS_TYPE_FD:
134 error_setg(errp, "Unsupported socket address type %s",
135 SocketAddressType_str(addr->type));
136 break;
137 default:
138 abort();
139 }
140
141 return;
142 }
143
144 static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
145 VncBasicInfo *info,
146 Error **errp)
147 {
148 SocketAddress *addr = NULL;
149
150 if (!ioc) {
151 error_setg(errp, "No listener socket available");
152 return;
153 }
154
155 addr = qio_channel_socket_get_local_address(ioc, errp);
156 if (!addr) {
157 return;
158 }
159
160 vnc_init_basic_info(addr, info, errp);
161 qapi_free_SocketAddress(addr);
162 }
163
164 static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
165 VncBasicInfo *info,
166 Error **errp)
167 {
168 SocketAddress *addr = NULL;
169
170 addr = qio_channel_socket_get_remote_address(ioc, errp);
171 if (!addr) {
172 return;
173 }
174
175 vnc_init_basic_info(addr, info, errp);
176 qapi_free_SocketAddress(addr);
177 }
178
179 static const char *vnc_auth_name(VncDisplay *vd) {
180 switch (vd->auth) {
181 case VNC_AUTH_INVALID:
182 return "invalid";
183 case VNC_AUTH_NONE:
184 return "none";
185 case VNC_AUTH_VNC:
186 return "vnc";
187 case VNC_AUTH_RA2:
188 return "ra2";
189 case VNC_AUTH_RA2NE:
190 return "ra2ne";
191 case VNC_AUTH_TIGHT:
192 return "tight";
193 case VNC_AUTH_ULTRA:
194 return "ultra";
195 case VNC_AUTH_TLS:
196 return "tls";
197 case VNC_AUTH_VENCRYPT:
198 switch (vd->subauth) {
199 case VNC_AUTH_VENCRYPT_PLAIN:
200 return "vencrypt+plain";
201 case VNC_AUTH_VENCRYPT_TLSNONE:
202 return "vencrypt+tls+none";
203 case VNC_AUTH_VENCRYPT_TLSVNC:
204 return "vencrypt+tls+vnc";
205 case VNC_AUTH_VENCRYPT_TLSPLAIN:
206 return "vencrypt+tls+plain";
207 case VNC_AUTH_VENCRYPT_X509NONE:
208 return "vencrypt+x509+none";
209 case VNC_AUTH_VENCRYPT_X509VNC:
210 return "vencrypt+x509+vnc";
211 case VNC_AUTH_VENCRYPT_X509PLAIN:
212 return "vencrypt+x509+plain";
213 case VNC_AUTH_VENCRYPT_TLSSASL:
214 return "vencrypt+tls+sasl";
215 case VNC_AUTH_VENCRYPT_X509SASL:
216 return "vencrypt+x509+sasl";
217 default:
218 return "vencrypt";
219 }
220 case VNC_AUTH_SASL:
221 return "sasl";
222 }
223 return "unknown";
224 }
225
226 static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
227 {
228 VncServerInfo *info;
229 Error *err = NULL;
230
231 if (!vd->listener || !vd->listener->nsioc) {
232 return NULL;
233 }
234
235 info = g_malloc0(sizeof(*info));
236 vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
237 qapi_VncServerInfo_base(info), &err);
238 info->has_auth = true;
239 info->auth = g_strdup(vnc_auth_name(vd));
240 if (err) {
241 qapi_free_VncServerInfo(info);
242 info = NULL;
243 error_free(err);
244 }
245 return info;
246 }
247
248 static void vnc_client_cache_auth(VncState *client)
249 {
250 if (!client->info) {
251 return;
252 }
253
254 if (client->tls) {
255 client->info->x509_dname =
256 qcrypto_tls_session_get_peer_name(client->tls);
257 client->info->has_x509_dname =
258 client->info->x509_dname != NULL;
259 }
260 #ifdef CONFIG_VNC_SASL
261 if (client->sasl.conn &&
262 client->sasl.username) {
263 client->info->has_sasl_username = true;
264 client->info->sasl_username = g_strdup(client->sasl.username);
265 }
266 #endif
267 }
268
269 static void vnc_client_cache_addr(VncState *client)
270 {
271 Error *err = NULL;
272
273 client->info = g_malloc0(sizeof(*client->info));
274 vnc_init_basic_info_from_remote_addr(client->sioc,
275 qapi_VncClientInfo_base(client->info),
276 &err);
277 if (err) {
278 qapi_free_VncClientInfo(client->info);
279 client->info = NULL;
280 error_free(err);
281 }
282 }
283
284 static void vnc_qmp_event(VncState *vs, QAPIEvent event)
285 {
286 VncServerInfo *si;
287
288 if (!vs->info) {
289 return;
290 }
291
292 si = vnc_server_info_get(vs->vd);
293 if (!si) {
294 return;
295 }
296
297 switch (event) {
298 case QAPI_EVENT_VNC_CONNECTED:
299 qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
300 break;
301 case QAPI_EVENT_VNC_INITIALIZED:
302 qapi_event_send_vnc_initialized(si, vs->info);
303 break;
304 case QAPI_EVENT_VNC_DISCONNECTED:
305 qapi_event_send_vnc_disconnected(si, vs->info);
306 break;
307 default:
308 break;
309 }
310
311 qapi_free_VncServerInfo(si);
312 }
313
314 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
315 {
316 VncClientInfo *info;
317 Error *err = NULL;
318
319 info = g_malloc0(sizeof(*info));
320
321 vnc_init_basic_info_from_remote_addr(client->sioc,
322 qapi_VncClientInfo_base(info),
323 &err);
324 if (err) {
325 error_free(err);
326 qapi_free_VncClientInfo(info);
327 return NULL;
328 }
329
330 info->websocket = client->websocket;
331
332 if (client->tls) {
333 info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
334 info->has_x509_dname = info->x509_dname != NULL;
335 }
336 #ifdef CONFIG_VNC_SASL
337 if (client->sasl.conn && client->sasl.username) {
338 info->has_sasl_username = true;
339 info->sasl_username = g_strdup(client->sasl.username);
340 }
341 #endif
342
343 return info;
344 }
345
346 static VncDisplay *vnc_display_find(const char *id)
347 {
348 VncDisplay *vd;
349
350 if (id == NULL) {
351 return QTAILQ_FIRST(&vnc_displays);
352 }
353 QTAILQ_FOREACH(vd, &vnc_displays, next) {
354 if (strcmp(id, vd->id) == 0) {
355 return vd;
356 }
357 }
358 return NULL;
359 }
360
361 static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
362 {
363 VncClientInfoList *cinfo, *prev = NULL;
364 VncState *client;
365
366 QTAILQ_FOREACH(client, &vd->clients, next) {
367 cinfo = g_new0(VncClientInfoList, 1);
368 cinfo->value = qmp_query_vnc_client(client);
369 cinfo->next = prev;
370 prev = cinfo;
371 }
372 return prev;
373 }
374
375 VncInfo *qmp_query_vnc(Error **errp)
376 {
377 VncInfo *info = g_malloc0(sizeof(*info));
378 VncDisplay *vd = vnc_display_find(NULL);
379 SocketAddress *addr = NULL;
380
381 if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
382 info->enabled = false;
383 } else {
384 info->enabled = true;
385
386 /* for compatibility with the original command */
387 info->has_clients = true;
388 info->clients = qmp_query_client_list(vd);
389
390 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
391 errp);
392 if (!addr) {
393 goto out_error;
394 }
395
396 switch (addr->type) {
397 case SOCKET_ADDRESS_TYPE_INET:
398 info->host = g_strdup(addr->u.inet.host);
399 info->service = g_strdup(addr->u.inet.port);
400 if (addr->u.inet.ipv6) {
401 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
402 } else {
403 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
404 }
405 break;
406
407 case SOCKET_ADDRESS_TYPE_UNIX:
408 info->host = g_strdup("");
409 info->service = g_strdup(addr->u.q_unix.path);
410 info->family = NETWORK_ADDRESS_FAMILY_UNIX;
411 break;
412
413 case SOCKET_ADDRESS_TYPE_VSOCK:
414 case SOCKET_ADDRESS_TYPE_FD:
415 error_setg(errp, "Unsupported socket address type %s",
416 SocketAddressType_str(addr->type));
417 goto out_error;
418 default:
419 abort();
420 }
421
422 info->has_host = true;
423 info->has_service = true;
424 info->has_family = true;
425
426 info->has_auth = true;
427 info->auth = g_strdup(vnc_auth_name(vd));
428 }
429
430 qapi_free_SocketAddress(addr);
431 return info;
432
433 out_error:
434 qapi_free_SocketAddress(addr);
435 qapi_free_VncInfo(info);
436 return NULL;
437 }
438
439
440 static void qmp_query_auth(int auth, int subauth,
441 VncPrimaryAuth *qmp_auth,
442 VncVencryptSubAuth *qmp_vencrypt,
443 bool *qmp_has_vencrypt);
444
445 static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
446 bool websocket,
447 int auth,
448 int subauth,
449 VncServerInfo2List *prev)
450 {
451 VncServerInfo2List *list;
452 VncServerInfo2 *info;
453 Error *err = NULL;
454 SocketAddress *addr;
455
456 addr = qio_channel_socket_get_local_address(ioc, &err);
457 if (!addr) {
458 error_free(err);
459 return prev;
460 }
461
462 info = g_new0(VncServerInfo2, 1);
463 vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
464 qapi_free_SocketAddress(addr);
465 if (err) {
466 qapi_free_VncServerInfo2(info);
467 error_free(err);
468 return prev;
469 }
470 info->websocket = websocket;
471
472 qmp_query_auth(auth, subauth, &info->auth,
473 &info->vencrypt, &info->has_vencrypt);
474
475 list = g_new0(VncServerInfo2List, 1);
476 list->value = info;
477 list->next = prev;
478 return list;
479 }
480
481 static void qmp_query_auth(int auth, int subauth,
482 VncPrimaryAuth *qmp_auth,
483 VncVencryptSubAuth *qmp_vencrypt,
484 bool *qmp_has_vencrypt)
485 {
486 switch (auth) {
487 case VNC_AUTH_VNC:
488 *qmp_auth = VNC_PRIMARY_AUTH_VNC;
489 break;
490 case VNC_AUTH_RA2:
491 *qmp_auth = VNC_PRIMARY_AUTH_RA2;
492 break;
493 case VNC_AUTH_RA2NE:
494 *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
495 break;
496 case VNC_AUTH_TIGHT:
497 *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
498 break;
499 case VNC_AUTH_ULTRA:
500 *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
501 break;
502 case VNC_AUTH_TLS:
503 *qmp_auth = VNC_PRIMARY_AUTH_TLS;
504 break;
505 case VNC_AUTH_VENCRYPT:
506 *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
507 *qmp_has_vencrypt = true;
508 switch (subauth) {
509 case VNC_AUTH_VENCRYPT_PLAIN:
510 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
511 break;
512 case VNC_AUTH_VENCRYPT_TLSNONE:
513 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
514 break;
515 case VNC_AUTH_VENCRYPT_TLSVNC:
516 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
517 break;
518 case VNC_AUTH_VENCRYPT_TLSPLAIN:
519 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
520 break;
521 case VNC_AUTH_VENCRYPT_X509NONE:
522 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
523 break;
524 case VNC_AUTH_VENCRYPT_X509VNC:
525 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
526 break;
527 case VNC_AUTH_VENCRYPT_X509PLAIN:
528 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
529 break;
530 case VNC_AUTH_VENCRYPT_TLSSASL:
531 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
532 break;
533 case VNC_AUTH_VENCRYPT_X509SASL:
534 *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
535 break;
536 default:
537 *qmp_has_vencrypt = false;
538 break;
539 }
540 break;
541 case VNC_AUTH_SASL:
542 *qmp_auth = VNC_PRIMARY_AUTH_SASL;
543 break;
544 case VNC_AUTH_NONE:
545 default:
546 *qmp_auth = VNC_PRIMARY_AUTH_NONE;
547 break;
548 }
549 }
550
551 VncInfo2List *qmp_query_vnc_servers(Error **errp)
552 {
553 VncInfo2List *item, *prev = NULL;
554 VncInfo2 *info;
555 VncDisplay *vd;
556 DeviceState *dev;
557 size_t i;
558
559 QTAILQ_FOREACH(vd, &vnc_displays, next) {
560 info = g_new0(VncInfo2, 1);
561 info->id = g_strdup(vd->id);
562 info->clients = qmp_query_client_list(vd);
563 qmp_query_auth(vd->auth, vd->subauth, &info->auth,
564 &info->vencrypt, &info->has_vencrypt);
565 if (vd->dcl.con) {
566 dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
567 "device", NULL));
568 info->has_display = true;
569 info->display = g_strdup(dev->id);
570 }
571 for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
572 info->server = qmp_query_server_entry(
573 vd->listener->sioc[i], false, vd->auth, vd->subauth,
574 info->server);
575 }
576 for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
577 info->server = qmp_query_server_entry(
578 vd->wslistener->sioc[i], true, vd->ws_auth,
579 vd->ws_subauth, info->server);
580 }
581
582 item = g_new0(VncInfo2List, 1);
583 item->value = info;
584 item->next = prev;
585 prev = item;
586 }
587 return prev;
588 }
589
590 /* TODO
591 1) Get the queue working for IO.
592 2) there is some weirdness when using the -S option (the screen is grey
593 and not totally invalidated
594 3) resolutions > 1024
595 */
596
597 static int vnc_update_client(VncState *vs, int has_dirty);
598 static void vnc_disconnect_start(VncState *vs);
599
600 static void vnc_colordepth(VncState *vs);
601 static void framebuffer_update_request(VncState *vs, int incremental,
602 int x_position, int y_position,
603 int w, int h);
604 static void vnc_refresh(DisplayChangeListener *dcl);
605 static int vnc_refresh_server_surface(VncDisplay *vd);
606
607 static int vnc_width(VncDisplay *vd)
608 {
609 return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
610 VNC_DIRTY_PIXELS_PER_BIT));
611 }
612
613 static int vnc_height(VncDisplay *vd)
614 {
615 return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
616 }
617
618 static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
619 VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
620 VncDisplay *vd,
621 int x, int y, int w, int h)
622 {
623 int width = vnc_width(vd);
624 int height = vnc_height(vd);
625
626 /* this is needed this to ensure we updated all affected
627 * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
628 w += (x % VNC_DIRTY_PIXELS_PER_BIT);
629 x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
630
631 x = MIN(x, width);
632 y = MIN(y, height);
633 w = MIN(x + w, width) - x;
634 h = MIN(y + h, height);
635
636 for (; y < h; y++) {
637 bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
638 DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
639 }
640 }
641
642 static void vnc_dpy_update(DisplayChangeListener *dcl,
643 int x, int y, int w, int h)
644 {
645 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
646 struct VncSurface *s = &vd->guest;
647
648 vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
649 }
650
651 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
652 int32_t encoding)
653 {
654 vnc_write_u16(vs, x);
655 vnc_write_u16(vs, y);
656 vnc_write_u16(vs, w);
657 vnc_write_u16(vs, h);
658
659 vnc_write_s32(vs, encoding);
660 }
661
662
663 static void vnc_desktop_resize(VncState *vs)
664 {
665 if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
666 return;
667 }
668 if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
669 vs->client_height == pixman_image_get_height(vs->vd->server)) {
670 return;
671 }
672
673 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
674 pixman_image_get_width(vs->vd->server) >= 0);
675 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
676 pixman_image_get_height(vs->vd->server) >= 0);
677 vs->client_width = pixman_image_get_width(vs->vd->server);
678 vs->client_height = pixman_image_get_height(vs->vd->server);
679 vnc_lock_output(vs);
680 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
681 vnc_write_u8(vs, 0);
682 vnc_write_u16(vs, 1); /* number of rects */
683 vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
684 VNC_ENCODING_DESKTOPRESIZE);
685 vnc_unlock_output(vs);
686 vnc_flush(vs);
687 }
688
689 static void vnc_abort_display_jobs(VncDisplay *vd)
690 {
691 VncState *vs;
692
693 QTAILQ_FOREACH(vs, &vd->clients, next) {
694 vnc_lock_output(vs);
695 vs->abort = true;
696 vnc_unlock_output(vs);
697 }
698 QTAILQ_FOREACH(vs, &vd->clients, next) {
699 vnc_jobs_join(vs);
700 }
701 QTAILQ_FOREACH(vs, &vd->clients, next) {
702 vnc_lock_output(vs);
703 if (vs->update == VNC_STATE_UPDATE_NONE &&
704 vs->job_update != VNC_STATE_UPDATE_NONE) {
705 /* job aborted before completion */
706 vs->update = vs->job_update;
707 vs->job_update = VNC_STATE_UPDATE_NONE;
708 }
709 vs->abort = false;
710 vnc_unlock_output(vs);
711 }
712 }
713
714 int vnc_server_fb_stride(VncDisplay *vd)
715 {
716 return pixman_image_get_stride(vd->server);
717 }
718
719 void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
720 {
721 uint8_t *ptr;
722
723 ptr = (uint8_t *)pixman_image_get_data(vd->server);
724 ptr += y * vnc_server_fb_stride(vd);
725 ptr += x * VNC_SERVER_FB_BYTES;
726 return ptr;
727 }
728
729 static void vnc_update_server_surface(VncDisplay *vd)
730 {
731 int width, height;
732
733 qemu_pixman_image_unref(vd->server);
734 vd->server = NULL;
735
736 if (QTAILQ_EMPTY(&vd->clients)) {
737 return;
738 }
739
740 width = vnc_width(vd);
741 height = vnc_height(vd);
742 vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
743 width, height,
744 NULL, 0);
745
746 memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
747 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
748 width, height);
749 }
750
751 static bool vnc_check_pageflip(DisplaySurface *s1,
752 DisplaySurface *s2)
753 {
754 return (s1 != NULL &&
755 s2 != NULL &&
756 surface_width(s1) == surface_width(s2) &&
757 surface_height(s1) == surface_height(s2) &&
758 surface_format(s1) == surface_format(s2));
759
760 }
761
762 static void vnc_dpy_switch(DisplayChangeListener *dcl,
763 DisplaySurface *surface)
764 {
765 static const char placeholder_msg[] =
766 "Display output is not active.";
767 static DisplaySurface *placeholder;
768 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
769 bool pageflip = vnc_check_pageflip(vd->ds, surface);
770 VncState *vs;
771
772 if (surface == NULL) {
773 if (placeholder == NULL) {
774 placeholder = qemu_create_message_surface(640, 480, placeholder_msg);
775 }
776 surface = placeholder;
777 }
778
779 vnc_abort_display_jobs(vd);
780 vd->ds = surface;
781
782 /* guest surface */
783 qemu_pixman_image_unref(vd->guest.fb);
784 vd->guest.fb = pixman_image_ref(surface->image);
785 vd->guest.format = surface->format;
786
787 if (pageflip) {
788 vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
789 surface_width(surface),
790 surface_height(surface));
791 return;
792 }
793
794 /* server surface */
795 vnc_update_server_surface(vd);
796
797 QTAILQ_FOREACH(vs, &vd->clients, next) {
798 vnc_colordepth(vs);
799 vnc_desktop_resize(vs);
800 if (vs->vd->cursor) {
801 vnc_cursor_define(vs);
802 }
803 memset(vs->dirty, 0x00, sizeof(vs->dirty));
804 vnc_set_area_dirty(vs->dirty, vd, 0, 0,
805 vnc_width(vd),
806 vnc_height(vd));
807 vnc_update_throttle_offset(vs);
808 }
809 }
810
811 /* fastest code */
812 static void vnc_write_pixels_copy(VncState *vs,
813 void *pixels, int size)
814 {
815 vnc_write(vs, pixels, size);
816 }
817
818 /* slowest but generic code. */
819 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
820 {
821 uint8_t r, g, b;
822
823 #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
824 r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
825 g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
826 b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
827 #else
828 # error need some bits here if you change VNC_SERVER_FB_FORMAT
829 #endif
830 v = (r << vs->client_pf.rshift) |
831 (g << vs->client_pf.gshift) |
832 (b << vs->client_pf.bshift);
833 switch (vs->client_pf.bytes_per_pixel) {
834 case 1:
835 buf[0] = v;
836 break;
837 case 2:
838 if (vs->client_be) {
839 buf[0] = v >> 8;
840 buf[1] = v;
841 } else {
842 buf[1] = v >> 8;
843 buf[0] = v;
844 }
845 break;
846 default:
847 case 4:
848 if (vs->client_be) {
849 buf[0] = v >> 24;
850 buf[1] = v >> 16;
851 buf[2] = v >> 8;
852 buf[3] = v;
853 } else {
854 buf[3] = v >> 24;
855 buf[2] = v >> 16;
856 buf[1] = v >> 8;
857 buf[0] = v;
858 }
859 break;
860 }
861 }
862
863 static void vnc_write_pixels_generic(VncState *vs,
864 void *pixels1, int size)
865 {
866 uint8_t buf[4];
867
868 if (VNC_SERVER_FB_BYTES == 4) {
869 uint32_t *pixels = pixels1;
870 int n, i;
871 n = size >> 2;
872 for (i = 0; i < n; i++) {
873 vnc_convert_pixel(vs, buf, pixels[i]);
874 vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
875 }
876 }
877 }
878
879 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
880 {
881 int i;
882 uint8_t *row;
883 VncDisplay *vd = vs->vd;
884
885 row = vnc_server_fb_ptr(vd, x, y);
886 for (i = 0; i < h; i++) {
887 vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
888 row += vnc_server_fb_stride(vd);
889 }
890 return 1;
891 }
892
893 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
894 {
895 int n = 0;
896 bool encode_raw = false;
897 size_t saved_offs = vs->output.offset;
898
899 switch(vs->vnc_encoding) {
900 case VNC_ENCODING_ZLIB:
901 n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
902 break;
903 case VNC_ENCODING_HEXTILE:
904 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
905 n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
906 break;
907 case VNC_ENCODING_TIGHT:
908 n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
909 break;
910 case VNC_ENCODING_TIGHT_PNG:
911 n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
912 break;
913 case VNC_ENCODING_ZRLE:
914 n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
915 break;
916 case VNC_ENCODING_ZYWRLE:
917 n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
918 break;
919 default:
920 encode_raw = true;
921 break;
922 }
923
924 /* If the client has the same pixel format as our internal buffer and
925 * a RAW encoding would need less space fall back to RAW encoding to
926 * save bandwidth and processing power in the client. */
927 if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
928 12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
929 vs->output.offset = saved_offs;
930 encode_raw = true;
931 }
932
933 if (encode_raw) {
934 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
935 n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
936 }
937
938 return n;
939 }
940
941 static void vnc_mouse_set(DisplayChangeListener *dcl,
942 int x, int y, int visible)
943 {
944 /* can we ask the client(s) to move the pointer ??? */
945 }
946
947 static int vnc_cursor_define(VncState *vs)
948 {
949 QEMUCursor *c = vs->vd->cursor;
950 int isize;
951
952 if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
953 vnc_lock_output(vs);
954 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
955 vnc_write_u8(vs, 0); /* padding */
956 vnc_write_u16(vs, 1); /* # of rects */
957 vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
958 VNC_ENCODING_RICH_CURSOR);
959 isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
960 vnc_write_pixels_generic(vs, c->data, isize);
961 vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
962 vnc_unlock_output(vs);
963 return 0;
964 }
965 return -1;
966 }
967
968 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
969 QEMUCursor *c)
970 {
971 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
972 VncState *vs;
973
974 cursor_put(vd->cursor);
975 g_free(vd->cursor_mask);
976
977 vd->cursor = c;
978 cursor_get(vd->cursor);
979 vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
980 vd->cursor_mask = g_malloc0(vd->cursor_msize);
981 cursor_get_mono_mask(c, 0, vd->cursor_mask);
982
983 QTAILQ_FOREACH(vs, &vd->clients, next) {
984 vnc_cursor_define(vs);
985 }
986 }
987
988 static int find_and_clear_dirty_height(VncState *vs,
989 int y, int last_x, int x, int height)
990 {
991 int h;
992
993 for (h = 1; h < (height - y); h++) {
994 if (!test_bit(last_x, vs->dirty[y + h])) {
995 break;
996 }
997 bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
998 }
999
1000 return h;
1001 }
1002
1003 /*
1004 * Figure out how much pending data we should allow in the output
1005 * buffer before we throttle incremental display updates, and/or
1006 * drop audio samples.
1007 *
1008 * We allow for equiv of 1 full display's worth of FB updates,
1009 * and 1 second of audio samples. If audio backlog was larger
1010 * than that the client would already suffering awful audio
1011 * glitches, so dropping samples is no worse really).
1012 */
1013 static void vnc_update_throttle_offset(VncState *vs)
1014 {
1015 size_t offset =
1016 vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1017
1018 if (vs->audio_cap) {
1019 int bps;
1020 switch (vs->as.fmt) {
1021 default:
1022 case AUDIO_FORMAT_U8:
1023 case AUDIO_FORMAT_S8:
1024 bps = 1;
1025 break;
1026 case AUDIO_FORMAT_U16:
1027 case AUDIO_FORMAT_S16:
1028 bps = 2;
1029 break;
1030 case AUDIO_FORMAT_U32:
1031 case AUDIO_FORMAT_S32:
1032 bps = 4;
1033 break;
1034 }
1035 offset += vs->as.freq * bps * vs->as.nchannels;
1036 }
1037
1038 /* Put a floor of 1MB on offset, so that if we have a large pending
1039 * buffer and the display is resized to a small size & back again
1040 * we don't suddenly apply a tiny send limit
1041 */
1042 offset = MAX(offset, 1024 * 1024);
1043
1044 if (vs->throttle_output_offset != offset) {
1045 trace_vnc_client_throttle_threshold(
1046 vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1047 vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1048 }
1049
1050 vs->throttle_output_offset = offset;
1051 }
1052
1053 static bool vnc_should_update(VncState *vs)
1054 {
1055 switch (vs->update) {
1056 case VNC_STATE_UPDATE_NONE:
1057 break;
1058 case VNC_STATE_UPDATE_INCREMENTAL:
1059 /* Only allow incremental updates if the pending send queue
1060 * is less than the permitted threshold, and the job worker
1061 * is completely idle.
1062 */
1063 if (vs->output.offset < vs->throttle_output_offset &&
1064 vs->job_update == VNC_STATE_UPDATE_NONE) {
1065 return true;
1066 }
1067 trace_vnc_client_throttle_incremental(
1068 vs, vs->ioc, vs->job_update, vs->output.offset);
1069 break;
1070 case VNC_STATE_UPDATE_FORCE:
1071 /* Only allow forced updates if the pending send queue
1072 * does not contain a previous forced update, and the
1073 * job worker is completely idle.
1074 *
1075 * Note this means we'll queue a forced update, even if
1076 * the output buffer size is otherwise over the throttle
1077 * output limit.
1078 */
1079 if (vs->force_update_offset == 0 &&
1080 vs->job_update == VNC_STATE_UPDATE_NONE) {
1081 return true;
1082 }
1083 trace_vnc_client_throttle_forced(
1084 vs, vs->ioc, vs->job_update, vs->force_update_offset);
1085 break;
1086 }
1087 return false;
1088 }
1089
1090 static int vnc_update_client(VncState *vs, int has_dirty)
1091 {
1092 VncDisplay *vd = vs->vd;
1093 VncJob *job;
1094 int y;
1095 int height, width;
1096 int n = 0;
1097
1098 if (vs->disconnecting) {
1099 vnc_disconnect_finish(vs);
1100 return 0;
1101 }
1102
1103 vs->has_dirty += has_dirty;
1104 if (!vnc_should_update(vs)) {
1105 return 0;
1106 }
1107
1108 if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1109 return 0;
1110 }
1111
1112 /*
1113 * Send screen updates to the vnc client using the server
1114 * surface and server dirty map. guest surface updates
1115 * happening in parallel don't disturb us, the next pass will
1116 * send them to the client.
1117 */
1118 job = vnc_job_new(vs);
1119
1120 height = pixman_image_get_height(vd->server);
1121 width = pixman_image_get_width(vd->server);
1122
1123 y = 0;
1124 for (;;) {
1125 int x, h;
1126 unsigned long x2;
1127 unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1128 height * VNC_DIRTY_BPL(vs),
1129 y * VNC_DIRTY_BPL(vs));
1130 if (offset == height * VNC_DIRTY_BPL(vs)) {
1131 /* no more dirty bits */
1132 break;
1133 }
1134 y = offset / VNC_DIRTY_BPL(vs);
1135 x = offset % VNC_DIRTY_BPL(vs);
1136 x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1137 VNC_DIRTY_BPL(vs), x);
1138 bitmap_clear(vs->dirty[y], x, x2 - x);
1139 h = find_and_clear_dirty_height(vs, y, x, x2, height);
1140 x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1141 if (x2 > x) {
1142 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1143 (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1144 }
1145 if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1146 y += h;
1147 if (y == height) {
1148 break;
1149 }
1150 }
1151 }
1152
1153 vs->job_update = vs->update;
1154 vs->update = VNC_STATE_UPDATE_NONE;
1155 vnc_job_push(job);
1156 vs->has_dirty = 0;
1157 return n;
1158 }
1159
1160 /* audio */
1161 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1162 {
1163 VncState *vs = opaque;
1164
1165 assert(vs->magic == VNC_MAGIC);
1166 switch (cmd) {
1167 case AUD_CNOTIFY_DISABLE:
1168 vnc_lock_output(vs);
1169 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1170 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1171 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1172 vnc_unlock_output(vs);
1173 vnc_flush(vs);
1174 break;
1175
1176 case AUD_CNOTIFY_ENABLE:
1177 vnc_lock_output(vs);
1178 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1179 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1180 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1181 vnc_unlock_output(vs);
1182 vnc_flush(vs);
1183 break;
1184 }
1185 }
1186
1187 static void audio_capture_destroy(void *opaque)
1188 {
1189 }
1190
1191 static void audio_capture(void *opaque, void *buf, int size)
1192 {
1193 VncState *vs = opaque;
1194
1195 assert(vs->magic == VNC_MAGIC);
1196 vnc_lock_output(vs);
1197 if (vs->output.offset < vs->throttle_output_offset) {
1198 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1199 vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1200 vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1201 vnc_write_u32(vs, size);
1202 vnc_write(vs, buf, size);
1203 } else {
1204 trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1205 }
1206 vnc_unlock_output(vs);
1207 vnc_flush(vs);
1208 }
1209
1210 static void audio_add(VncState *vs)
1211 {
1212 struct audio_capture_ops ops;
1213
1214 if (vs->audio_cap) {
1215 error_report("audio already running");
1216 return;
1217 }
1218
1219 ops.notify = audio_capture_notify;
1220 ops.destroy = audio_capture_destroy;
1221 ops.capture = audio_capture;
1222
1223 vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1224 if (!vs->audio_cap) {
1225 error_report("Failed to add audio capture");
1226 }
1227 }
1228
1229 static void audio_del(VncState *vs)
1230 {
1231 if (vs->audio_cap) {
1232 AUD_del_capture(vs->audio_cap, vs);
1233 vs->audio_cap = NULL;
1234 }
1235 }
1236
1237 static void vnc_disconnect_start(VncState *vs)
1238 {
1239 if (vs->disconnecting) {
1240 return;
1241 }
1242 trace_vnc_client_disconnect_start(vs, vs->ioc);
1243 vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1244 if (vs->ioc_tag) {
1245 g_source_remove(vs->ioc_tag);
1246 vs->ioc_tag = 0;
1247 }
1248 qio_channel_close(vs->ioc, NULL);
1249 vs->disconnecting = TRUE;
1250 }
1251
1252 void vnc_disconnect_finish(VncState *vs)
1253 {
1254 int i;
1255
1256 trace_vnc_client_disconnect_finish(vs, vs->ioc);
1257
1258 vnc_jobs_join(vs); /* Wait encoding jobs */
1259
1260 vnc_lock_output(vs);
1261 vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1262
1263 buffer_free(&vs->input);
1264 buffer_free(&vs->output);
1265
1266 qapi_free_VncClientInfo(vs->info);
1267
1268 vnc_zlib_clear(vs);
1269 vnc_tight_clear(vs);
1270 vnc_zrle_clear(vs);
1271
1272 #ifdef CONFIG_VNC_SASL
1273 vnc_sasl_client_cleanup(vs);
1274 #endif /* CONFIG_VNC_SASL */
1275 audio_del(vs);
1276 qkbd_state_lift_all_keys(vs->vd->kbd);
1277
1278 if (vs->mouse_mode_notifier.notify != NULL) {
1279 qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1280 }
1281 QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1282 if (QTAILQ_EMPTY(&vs->vd->clients)) {
1283 /* last client gone */
1284 vnc_update_server_surface(vs->vd);
1285 }
1286
1287 vnc_unlock_output(vs);
1288
1289 qemu_mutex_destroy(&vs->output_mutex);
1290 if (vs->bh != NULL) {
1291 qemu_bh_delete(vs->bh);
1292 }
1293 buffer_free(&vs->jobs_buffer);
1294
1295 for (i = 0; i < VNC_STAT_ROWS; ++i) {
1296 g_free(vs->lossy_rect[i]);
1297 }
1298 g_free(vs->lossy_rect);
1299
1300 object_unref(OBJECT(vs->ioc));
1301 vs->ioc = NULL;
1302 object_unref(OBJECT(vs->sioc));
1303 vs->sioc = NULL;
1304 vs->magic = 0;
1305 g_free(vs);
1306 }
1307
1308 size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
1309 {
1310 if (ret <= 0) {
1311 if (ret == 0) {
1312 trace_vnc_client_eof(vs, vs->ioc);
1313 vnc_disconnect_start(vs);
1314 } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1315 trace_vnc_client_io_error(vs, vs->ioc,
1316 errp ? error_get_pretty(*errp) :
1317 "Unknown");
1318 vnc_disconnect_start(vs);
1319 }
1320
1321 if (errp) {
1322 error_free(*errp);
1323 *errp = NULL;
1324 }
1325 return 0;
1326 }
1327 return ret;
1328 }
1329
1330
1331 void vnc_client_error(VncState *vs)
1332 {
1333 VNC_DEBUG("Closing down client sock: protocol error\n");
1334 vnc_disconnect_start(vs);
1335 }
1336
1337
1338 /*
1339 * Called to write a chunk of data to the client socket. The data may
1340 * be the raw data, or may have already been encoded by SASL.
1341 * The data will be written either straight onto the socket, or
1342 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1343 *
1344 * NB, it is theoretically possible to have 2 layers of encryption,
1345 * both SASL, and this TLS layer. It is highly unlikely in practice
1346 * though, since SASL encryption will typically be a no-op if TLS
1347 * is active
1348 *
1349 * Returns the number of bytes written, which may be less than
1350 * the requested 'datalen' if the socket would block. Returns
1351 * 0 on I/O error, and disconnects the client socket.
1352 */
1353 size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1354 {
1355 Error *err = NULL;
1356 ssize_t ret;
1357 ret = qio_channel_write(
1358 vs->ioc, (const char *)data, datalen, &err);
1359 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1360 return vnc_client_io_error(vs, ret, &err);
1361 }
1362
1363
1364 /*
1365 * Called to write buffered data to the client socket, when not
1366 * using any SASL SSF encryption layers. Will write as much data
1367 * as possible without blocking. If all buffered data is written,
1368 * will switch the FD poll() handler back to read monitoring.
1369 *
1370 * Returns the number of bytes written, which may be less than
1371 * the buffered output data if the socket would block. Returns
1372 * 0 on I/O error, and disconnects the client socket.
1373 */
1374 static size_t vnc_client_write_plain(VncState *vs)
1375 {
1376 size_t offset;
1377 size_t ret;
1378
1379 #ifdef CONFIG_VNC_SASL
1380 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1381 vs->output.buffer, vs->output.capacity, vs->output.offset,
1382 vs->sasl.waitWriteSSF);
1383
1384 if (vs->sasl.conn &&
1385 vs->sasl.runSSF &&
1386 vs->sasl.waitWriteSSF) {
1387 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1388 if (ret)
1389 vs->sasl.waitWriteSSF -= ret;
1390 } else
1391 #endif /* CONFIG_VNC_SASL */
1392 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1393 if (!ret)
1394 return 0;
1395
1396 if (ret >= vs->force_update_offset) {
1397 if (vs->force_update_offset != 0) {
1398 trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1399 }
1400 vs->force_update_offset = 0;
1401 } else {
1402 vs->force_update_offset -= ret;
1403 }
1404 offset = vs->output.offset;
1405 buffer_advance(&vs->output, ret);
1406 if (offset >= vs->throttle_output_offset &&
1407 vs->output.offset < vs->throttle_output_offset) {
1408 trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1409 }
1410
1411 if (vs->output.offset == 0) {
1412 if (vs->ioc_tag) {
1413 g_source_remove(vs->ioc_tag);
1414 }
1415 vs->ioc_tag = qio_channel_add_watch(
1416 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1417 }
1418
1419 return ret;
1420 }
1421
1422
1423 /*
1424 * First function called whenever there is data to be written to
1425 * the client socket. Will delegate actual work according to whether
1426 * SASL SSF layers are enabled (thus requiring encryption calls)
1427 */
1428 static void vnc_client_write_locked(VncState *vs)
1429 {
1430 #ifdef CONFIG_VNC_SASL
1431 if (vs->sasl.conn &&
1432 vs->sasl.runSSF &&
1433 !vs->sasl.waitWriteSSF) {
1434 vnc_client_write_sasl(vs);
1435 } else
1436 #endif /* CONFIG_VNC_SASL */
1437 {
1438 vnc_client_write_plain(vs);
1439 }
1440 }
1441
1442 static void vnc_client_write(VncState *vs)
1443 {
1444 assert(vs->magic == VNC_MAGIC);
1445 vnc_lock_output(vs);
1446 if (vs->output.offset) {
1447 vnc_client_write_locked(vs);
1448 } else if (vs->ioc != NULL) {
1449 if (vs->ioc_tag) {
1450 g_source_remove(vs->ioc_tag);
1451 }
1452 vs->ioc_tag = qio_channel_add_watch(
1453 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1454 }
1455 vnc_unlock_output(vs);
1456 }
1457
1458 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1459 {
1460 vs->read_handler = func;
1461 vs->read_handler_expect = expecting;
1462 }
1463
1464
1465 /*
1466 * Called to read a chunk of data from the client socket. The data may
1467 * be the raw data, or may need to be further decoded by SASL.
1468 * The data will be read either straight from to the socket, or
1469 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1470 *
1471 * NB, it is theoretically possible to have 2 layers of encryption,
1472 * both SASL, and this TLS layer. It is highly unlikely in practice
1473 * though, since SASL encryption will typically be a no-op if TLS
1474 * is active
1475 *
1476 * Returns the number of bytes read, which may be less than
1477 * the requested 'datalen' if the socket would block. Returns
1478 * 0 on I/O error or EOF, and disconnects the client socket.
1479 */
1480 size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1481 {
1482 ssize_t ret;
1483 Error *err = NULL;
1484 ret = qio_channel_read(
1485 vs->ioc, (char *)data, datalen, &err);
1486 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1487 return vnc_client_io_error(vs, ret, &err);
1488 }
1489
1490
1491 /*
1492 * Called to read data from the client socket to the input buffer,
1493 * when not using any SASL SSF encryption layers. Will read as much
1494 * data as possible without blocking.
1495 *
1496 * Returns the number of bytes read, which may be less than
1497 * the requested 'datalen' if the socket would block. Returns
1498 * 0 on I/O error or EOF, and disconnects the client socket.
1499 */
1500 static size_t vnc_client_read_plain(VncState *vs)
1501 {
1502 size_t ret;
1503 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1504 vs->input.buffer, vs->input.capacity, vs->input.offset);
1505 buffer_reserve(&vs->input, 4096);
1506 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1507 if (!ret)
1508 return 0;
1509 vs->input.offset += ret;
1510 return ret;
1511 }
1512
1513 static void vnc_jobs_bh(void *opaque)
1514 {
1515 VncState *vs = opaque;
1516
1517 assert(vs->magic == VNC_MAGIC);
1518 vnc_jobs_consume_buffer(vs);
1519 }
1520
1521 /*
1522 * First function called whenever there is more data to be read from
1523 * the client socket. Will delegate actual work according to whether
1524 * SASL SSF layers are enabled (thus requiring decryption calls)
1525 * Returns 0 on success, -1 if client disconnected
1526 */
1527 static int vnc_client_read(VncState *vs)
1528 {
1529 size_t ret;
1530
1531 #ifdef CONFIG_VNC_SASL
1532 if (vs->sasl.conn && vs->sasl.runSSF)
1533 ret = vnc_client_read_sasl(vs);
1534 else
1535 #endif /* CONFIG_VNC_SASL */
1536 ret = vnc_client_read_plain(vs);
1537 if (!ret) {
1538 if (vs->disconnecting) {
1539 vnc_disconnect_finish(vs);
1540 return -1;
1541 }
1542 return 0;
1543 }
1544
1545 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1546 size_t len = vs->read_handler_expect;
1547 int ret;
1548
1549 ret = vs->read_handler(vs, vs->input.buffer, len);
1550 if (vs->disconnecting) {
1551 vnc_disconnect_finish(vs);
1552 return -1;
1553 }
1554
1555 if (!ret) {
1556 buffer_advance(&vs->input, len);
1557 } else {
1558 vs->read_handler_expect = ret;
1559 }
1560 }
1561 return 0;
1562 }
1563
1564 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1565 GIOCondition condition, void *opaque)
1566 {
1567 VncState *vs = opaque;
1568
1569 assert(vs->magic == VNC_MAGIC);
1570 if (condition & G_IO_IN) {
1571 if (vnc_client_read(vs) < 0) {
1572 /* vs is free()ed here */
1573 return TRUE;
1574 }
1575 }
1576 if (condition & G_IO_OUT) {
1577 vnc_client_write(vs);
1578 }
1579
1580 if (vs->disconnecting) {
1581 if (vs->ioc_tag != 0) {
1582 g_source_remove(vs->ioc_tag);
1583 }
1584 vs->ioc_tag = 0;
1585 }
1586 return TRUE;
1587 }
1588
1589
1590 /*
1591 * Scale factor to apply to vs->throttle_output_offset when checking for
1592 * hard limit. Worst case normal usage could be x2, if we have a complete
1593 * incremental update and complete forced update in the output buffer.
1594 * So x3 should be good enough, but we pick x5 to be conservative and thus
1595 * (hopefully) never trigger incorrectly.
1596 */
1597 #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1598
1599 void vnc_write(VncState *vs, const void *data, size_t len)
1600 {
1601 assert(vs->magic == VNC_MAGIC);
1602 if (vs->disconnecting) {
1603 return;
1604 }
1605 /* Protection against malicious client/guest to prevent our output
1606 * buffer growing without bound if client stops reading data. This
1607 * should rarely trigger, because we have earlier throttling code
1608 * which stops issuing framebuffer updates and drops audio data
1609 * if the throttle_output_offset value is exceeded. So we only reach
1610 * this higher level if a huge number of pseudo-encodings get
1611 * triggered while data can't be sent on the socket.
1612 *
1613 * NB throttle_output_offset can be zero during early protocol
1614 * handshake, or from the job thread's VncState clone
1615 */
1616 if (vs->throttle_output_offset != 0 &&
1617 (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1618 vs->throttle_output_offset) {
1619 trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1620 vs->throttle_output_offset);
1621 vnc_disconnect_start(vs);
1622 return;
1623 }
1624 buffer_reserve(&vs->output, len);
1625
1626 if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1627 if (vs->ioc_tag) {
1628 g_source_remove(vs->ioc_tag);
1629 }
1630 vs->ioc_tag = qio_channel_add_watch(
1631 vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1632 }
1633
1634 buffer_append(&vs->output, data, len);
1635 }
1636
1637 void vnc_write_s32(VncState *vs, int32_t value)
1638 {
1639 vnc_write_u32(vs, *(uint32_t *)&value);
1640 }
1641
1642 void vnc_write_u32(VncState *vs, uint32_t value)
1643 {
1644 uint8_t buf[4];
1645
1646 buf[0] = (value >> 24) & 0xFF;
1647 buf[1] = (value >> 16) & 0xFF;
1648 buf[2] = (value >> 8) & 0xFF;
1649 buf[3] = value & 0xFF;
1650
1651 vnc_write(vs, buf, 4);
1652 }
1653
1654 void vnc_write_u16(VncState *vs, uint16_t value)
1655 {
1656 uint8_t buf[2];
1657
1658 buf[0] = (value >> 8) & 0xFF;
1659 buf[1] = value & 0xFF;
1660
1661 vnc_write(vs, buf, 2);
1662 }
1663
1664 void vnc_write_u8(VncState *vs, uint8_t value)
1665 {
1666 vnc_write(vs, (char *)&value, 1);
1667 }
1668
1669 void vnc_flush(VncState *vs)
1670 {
1671 vnc_lock_output(vs);
1672 if (vs->ioc != NULL && vs->output.offset) {
1673 vnc_client_write_locked(vs);
1674 }
1675 if (vs->disconnecting) {
1676 if (vs->ioc_tag != 0) {
1677 g_source_remove(vs->ioc_tag);
1678 }
1679 vs->ioc_tag = 0;
1680 }
1681 vnc_unlock_output(vs);
1682 }
1683
1684 static uint8_t read_u8(uint8_t *data, size_t offset)
1685 {
1686 return data[offset];
1687 }
1688
1689 static uint16_t read_u16(uint8_t *data, size_t offset)
1690 {
1691 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1692 }
1693
1694 static int32_t read_s32(uint8_t *data, size_t offset)
1695 {
1696 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1697 (data[offset + 2] << 8) | data[offset + 3]);
1698 }
1699
1700 uint32_t read_u32(uint8_t *data, size_t offset)
1701 {
1702 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1703 (data[offset + 2] << 8) | data[offset + 3]);
1704 }
1705
1706 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1707 {
1708 }
1709
1710 static void check_pointer_type_change(Notifier *notifier, void *data)
1711 {
1712 VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1713 int absolute = qemu_input_is_absolute();
1714
1715 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1716 vnc_lock_output(vs);
1717 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1718 vnc_write_u8(vs, 0);
1719 vnc_write_u16(vs, 1);
1720 vnc_framebuffer_update(vs, absolute, 0,
1721 pixman_image_get_width(vs->vd->server),
1722 pixman_image_get_height(vs->vd->server),
1723 VNC_ENCODING_POINTER_TYPE_CHANGE);
1724 vnc_unlock_output(vs);
1725 vnc_flush(vs);
1726 }
1727 vs->absolute = absolute;
1728 }
1729
1730 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1731 {
1732 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1733 [INPUT_BUTTON_LEFT] = 0x01,
1734 [INPUT_BUTTON_MIDDLE] = 0x02,
1735 [INPUT_BUTTON_RIGHT] = 0x04,
1736 [INPUT_BUTTON_WHEEL_UP] = 0x08,
1737 [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1738 };
1739 QemuConsole *con = vs->vd->dcl.con;
1740 int width = pixman_image_get_width(vs->vd->server);
1741 int height = pixman_image_get_height(vs->vd->server);
1742
1743 if (vs->last_bmask != button_mask) {
1744 qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1745 vs->last_bmask = button_mask;
1746 }
1747
1748 if (vs->absolute) {
1749 qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1750 qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1751 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1752 qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1753 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1754 } else {
1755 if (vs->last_x != -1) {
1756 qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1757 qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1758 }
1759 vs->last_x = x;
1760 vs->last_y = y;
1761 }
1762 qemu_input_event_sync();
1763 }
1764
1765 static void press_key(VncState *vs, QKeyCode qcode)
1766 {
1767 qkbd_state_key_event(vs->vd->kbd, qcode, true);
1768 qkbd_state_key_event(vs->vd->kbd, qcode, false);
1769 }
1770
1771 static void vnc_led_state_change(VncState *vs)
1772 {
1773 if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1774 return;
1775 }
1776
1777 vnc_lock_output(vs);
1778 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1779 vnc_write_u8(vs, 0);
1780 vnc_write_u16(vs, 1);
1781 vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1782 vnc_write_u8(vs, vs->vd->ledstate);
1783 vnc_unlock_output(vs);
1784 vnc_flush(vs);
1785 }
1786
1787 static void kbd_leds(void *opaque, int ledstate)
1788 {
1789 VncDisplay *vd = opaque;
1790 VncState *client;
1791
1792 trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1793 (ledstate & QEMU_NUM_LOCK_LED),
1794 (ledstate & QEMU_SCROLL_LOCK_LED));
1795
1796 if (ledstate == vd->ledstate) {
1797 return;
1798 }
1799
1800 vd->ledstate = ledstate;
1801
1802 QTAILQ_FOREACH(client, &vd->clients, next) {
1803 vnc_led_state_change(client);
1804 }
1805 }
1806
1807 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1808 {
1809 QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1810
1811 /* QEMU console switch */
1812 switch (qcode) {
1813 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1814 if (vs->vd->dcl.con == NULL && down &&
1815 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1816 qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1817 /* Reset the modifiers sent to the current console */
1818 qkbd_state_lift_all_keys(vs->vd->kbd);
1819 console_select(qcode - Q_KEY_CODE_1);
1820 return;
1821 }
1822 default:
1823 break;
1824 }
1825
1826 /* Turn off the lock state sync logic if the client support the led
1827 state extension.
1828 */
1829 if (down && vs->vd->lock_key_sync &&
1830 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1831 keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1832 /* If the numlock state needs to change then simulate an additional
1833 keypress before sending this one. This will happen if the user
1834 toggles numlock away from the VNC window.
1835 */
1836 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1837 if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1838 trace_vnc_key_sync_numlock(true);
1839 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1840 }
1841 } else {
1842 if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1843 trace_vnc_key_sync_numlock(false);
1844 press_key(vs, Q_KEY_CODE_NUM_LOCK);
1845 }
1846 }
1847 }
1848
1849 if (down && vs->vd->lock_key_sync &&
1850 !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1851 ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1852 /* If the capslock state needs to change then simulate an additional
1853 keypress before sending this one. This will happen if the user
1854 toggles capslock away from the VNC window.
1855 */
1856 int uppercase = !!(sym >= 'A' && sym <= 'Z');
1857 bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1858 bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1859 if (capslock) {
1860 if (uppercase == shift) {
1861 trace_vnc_key_sync_capslock(false);
1862 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1863 }
1864 } else {
1865 if (uppercase != shift) {
1866 trace_vnc_key_sync_capslock(true);
1867 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1868 }
1869 }
1870 }
1871
1872 qkbd_state_key_event(vs->vd->kbd, qcode, down);
1873 if (!qemu_console_is_graphic(NULL)) {
1874 bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1875 bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1876 /* QEMU console emulation */
1877 if (down) {
1878 switch (keycode) {
1879 case 0x2a: /* Left Shift */
1880 case 0x36: /* Right Shift */
1881 case 0x1d: /* Left CTRL */
1882 case 0x9d: /* Right CTRL */
1883 case 0x38: /* Left ALT */
1884 case 0xb8: /* Right ALT */
1885 break;
1886 case 0xc8:
1887 kbd_put_keysym(QEMU_KEY_UP);
1888 break;
1889 case 0xd0:
1890 kbd_put_keysym(QEMU_KEY_DOWN);
1891 break;
1892 case 0xcb:
1893 kbd_put_keysym(QEMU_KEY_LEFT);
1894 break;
1895 case 0xcd:
1896 kbd_put_keysym(QEMU_KEY_RIGHT);
1897 break;
1898 case 0xd3:
1899 kbd_put_keysym(QEMU_KEY_DELETE);
1900 break;
1901 case 0xc7:
1902 kbd_put_keysym(QEMU_KEY_HOME);
1903 break;
1904 case 0xcf:
1905 kbd_put_keysym(QEMU_KEY_END);
1906 break;
1907 case 0xc9:
1908 kbd_put_keysym(QEMU_KEY_PAGEUP);
1909 break;
1910 case 0xd1:
1911 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1912 break;
1913
1914 case 0x47:
1915 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1916 break;
1917 case 0x48:
1918 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1919 break;
1920 case 0x49:
1921 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1922 break;
1923 case 0x4b:
1924 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1925 break;
1926 case 0x4c:
1927 kbd_put_keysym('5');
1928 break;
1929 case 0x4d:
1930 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1931 break;
1932 case 0x4f:
1933 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1934 break;
1935 case 0x50:
1936 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1937 break;
1938 case 0x51:
1939 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1940 break;
1941 case 0x52:
1942 kbd_put_keysym('0');
1943 break;
1944 case 0x53:
1945 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1946 break;
1947
1948 case 0xb5:
1949 kbd_put_keysym('/');
1950 break;
1951 case 0x37:
1952 kbd_put_keysym('*');
1953 break;
1954 case 0x4a:
1955 kbd_put_keysym('-');
1956 break;
1957 case 0x4e:
1958 kbd_put_keysym('+');
1959 break;
1960 case 0x9c:
1961 kbd_put_keysym('\n');
1962 break;
1963
1964 default:
1965 if (control) {
1966 kbd_put_keysym(sym & 0x1f);
1967 } else {
1968 kbd_put_keysym(sym);
1969 }
1970 break;
1971 }
1972 }
1973 }
1974 }
1975
1976 static const char *code2name(int keycode)
1977 {
1978 return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
1979 }
1980
1981 static void key_event(VncState *vs, int down, uint32_t sym)
1982 {
1983 int keycode;
1984 int lsym = sym;
1985
1986 if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1987 lsym = lsym - 'A' + 'a';
1988 }
1989
1990 keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
1991 vs->vd->kbd, down) & SCANCODE_KEYMASK;
1992 trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1993 do_key_event(vs, down, keycode, sym);
1994 }
1995
1996 static void ext_key_event(VncState *vs, int down,
1997 uint32_t sym, uint16_t keycode)
1998 {
1999 /* if the user specifies a keyboard layout, always use it */
2000 if (keyboard_layout) {
2001 key_event(vs, down, sym);
2002 } else {
2003 trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
2004 do_key_event(vs, down, keycode, sym);
2005 }
2006 }
2007
2008 static void framebuffer_update_request(VncState *vs, int incremental,
2009 int x, int y, int w, int h)
2010 {
2011 if (incremental) {
2012 if (vs->update != VNC_STATE_UPDATE_FORCE) {
2013 vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2014 }
2015 } else {
2016 vs->update = VNC_STATE_UPDATE_FORCE;
2017 vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2018 }
2019 }
2020
2021 static void send_ext_key_event_ack(VncState *vs)
2022 {
2023 vnc_lock_output(vs);
2024 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2025 vnc_write_u8(vs, 0);
2026 vnc_write_u16(vs, 1);
2027 vnc_framebuffer_update(vs, 0, 0,
2028 pixman_image_get_width(vs->vd->server),
2029 pixman_image_get_height(vs->vd->server),
2030 VNC_ENCODING_EXT_KEY_EVENT);
2031 vnc_unlock_output(vs);
2032 vnc_flush(vs);
2033 }
2034
2035 static void send_ext_audio_ack(VncState *vs)
2036 {
2037 vnc_lock_output(vs);
2038 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2039 vnc_write_u8(vs, 0);
2040 vnc_write_u16(vs, 1);
2041 vnc_framebuffer_update(vs, 0, 0,
2042 pixman_image_get_width(vs->vd->server),
2043 pixman_image_get_height(vs->vd->server),
2044 VNC_ENCODING_AUDIO);
2045 vnc_unlock_output(vs);
2046 vnc_flush(vs);
2047 }
2048
2049 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2050 {
2051 int i;
2052 unsigned int enc = 0;
2053
2054 vs->features = 0;
2055 vs->vnc_encoding = 0;
2056 vs->tight.compression = 9;
2057 vs->tight.quality = -1; /* Lossless by default */
2058 vs->absolute = -1;
2059
2060 /*
2061 * Start from the end because the encodings are sent in order of preference.
2062 * This way the preferred encoding (first encoding defined in the array)
2063 * will be set at the end of the loop.
2064 */
2065 for (i = n_encodings - 1; i >= 0; i--) {
2066 enc = encodings[i];
2067 switch (enc) {
2068 case VNC_ENCODING_RAW:
2069 vs->vnc_encoding = enc;
2070 break;
2071 case VNC_ENCODING_COPYRECT:
2072 vs->features |= VNC_FEATURE_COPYRECT_MASK;
2073 break;
2074 case VNC_ENCODING_HEXTILE:
2075 vs->features |= VNC_FEATURE_HEXTILE_MASK;
2076 vs->vnc_encoding = enc;
2077 break;
2078 case VNC_ENCODING_TIGHT:
2079 vs->features |= VNC_FEATURE_TIGHT_MASK;
2080 vs->vnc_encoding = enc;
2081 break;
2082 #ifdef CONFIG_VNC_PNG
2083 case VNC_ENCODING_TIGHT_PNG:
2084 vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2085 vs->vnc_encoding = enc;
2086 break;
2087 #endif
2088 case VNC_ENCODING_ZLIB:
2089 vs->features |= VNC_FEATURE_ZLIB_MASK;
2090 vs->vnc_encoding = enc;
2091 break;
2092 case VNC_ENCODING_ZRLE:
2093 vs->features |= VNC_FEATURE_ZRLE_MASK;
2094 vs->vnc_encoding = enc;
2095 break;
2096 case VNC_ENCODING_ZYWRLE:
2097 vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2098 vs->vnc_encoding = enc;
2099 break;
2100 case VNC_ENCODING_DESKTOPRESIZE:
2101 vs->features |= VNC_FEATURE_RESIZE_MASK;
2102 break;
2103 case VNC_ENCODING_POINTER_TYPE_CHANGE:
2104 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2105 break;
2106 case VNC_ENCODING_RICH_CURSOR:
2107 vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2108 if (vs->vd->cursor) {
2109 vnc_cursor_define(vs);
2110 }
2111 break;
2112 case VNC_ENCODING_EXT_KEY_EVENT:
2113 send_ext_key_event_ack(vs);
2114 break;
2115 case VNC_ENCODING_AUDIO:
2116 send_ext_audio_ack(vs);
2117 break;
2118 case VNC_ENCODING_WMVi:
2119 vs->features |= VNC_FEATURE_WMVI_MASK;
2120 break;
2121 case VNC_ENCODING_LED_STATE:
2122 vs->features |= VNC_FEATURE_LED_STATE_MASK;
2123 break;
2124 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2125 vs->tight.compression = (enc & 0x0F);
2126 break;
2127 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2128 if (vs->vd->lossy) {
2129 vs->tight.quality = (enc & 0x0F);
2130 }
2131 break;
2132 default:
2133 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2134 break;
2135 }
2136 }
2137 vnc_desktop_resize(vs);
2138 check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2139 vnc_led_state_change(vs);
2140 }
2141
2142 static void set_pixel_conversion(VncState *vs)
2143 {
2144 pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2145
2146 if (fmt == VNC_SERVER_FB_FORMAT) {
2147 vs->write_pixels = vnc_write_pixels_copy;
2148 vnc_hextile_set_pixel_conversion(vs, 0);
2149 } else {
2150 vs->write_pixels = vnc_write_pixels_generic;
2151 vnc_hextile_set_pixel_conversion(vs, 1);
2152 }
2153 }
2154
2155 static void send_color_map(VncState *vs)
2156 {
2157 int i;
2158
2159 vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2160 vnc_write_u8(vs, 0); /* padding */
2161 vnc_write_u16(vs, 0); /* first color */
2162 vnc_write_u16(vs, 256); /* # of colors */
2163
2164 for (i = 0; i < 256; i++) {
2165 PixelFormat *pf = &vs->client_pf;
2166
2167 vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2168 vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2169 vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2170 }
2171 }
2172
2173 static void set_pixel_format(VncState *vs, int bits_per_pixel,
2174 int big_endian_flag, int true_color_flag,
2175 int red_max, int green_max, int blue_max,
2176 int red_shift, int green_shift, int blue_shift)
2177 {
2178 if (!true_color_flag) {
2179 /* Expose a reasonable default 256 color map */
2180 bits_per_pixel = 8;
2181 red_max = 7;
2182 green_max = 7;
2183 blue_max = 3;
2184 red_shift = 0;
2185 green_shift = 3;
2186 blue_shift = 6;
2187 }
2188
2189 switch (bits_per_pixel) {
2190 case 8:
2191 case 16:
2192 case 32:
2193 break;
2194 default:
2195 vnc_client_error(vs);
2196 return;
2197 }
2198
2199 vs->client_pf.rmax = red_max ? red_max : 0xFF;
2200 vs->client_pf.rbits = ctpopl(red_max);
2201 vs->client_pf.rshift = red_shift;
2202 vs->client_pf.rmask = red_max << red_shift;
2203 vs->client_pf.gmax = green_max ? green_max : 0xFF;
2204 vs->client_pf.gbits = ctpopl(green_max);
2205 vs->client_pf.gshift = green_shift;
2206 vs->client_pf.gmask = green_max << green_shift;
2207 vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2208 vs->client_pf.bbits = ctpopl(blue_max);
2209 vs->client_pf.bshift = blue_shift;
2210 vs->client_pf.bmask = blue_max << blue_shift;
2211 vs->client_pf.bits_per_pixel = bits_per_pixel;
2212 vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2213 vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2214 vs->client_be = big_endian_flag;
2215
2216 if (!true_color_flag) {
2217 send_color_map(vs);
2218 }
2219
2220 set_pixel_conversion(vs);
2221
2222 graphic_hw_invalidate(vs->vd->dcl.con);
2223 graphic_hw_update(vs->vd->dcl.con);
2224 }
2225
2226 static void pixel_format_message (VncState *vs) {
2227 char pad[3] = { 0, 0, 0 };
2228
2229 vs->client_pf = qemu_default_pixelformat(32);
2230
2231 vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2232 vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2233
2234 #ifdef HOST_WORDS_BIGENDIAN
2235 vnc_write_u8(vs, 1); /* big-endian-flag */
2236 #else
2237 vnc_write_u8(vs, 0); /* big-endian-flag */
2238 #endif
2239 vnc_write_u8(vs, 1); /* true-color-flag */
2240 vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
2241 vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
2242 vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
2243 vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
2244 vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
2245 vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
2246 vnc_write(vs, pad, 3); /* padding */
2247
2248 vnc_hextile_set_pixel_conversion(vs, 0);
2249 vs->write_pixels = vnc_write_pixels_copy;
2250 }
2251
2252 static void vnc_colordepth(VncState *vs)
2253 {
2254 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2255 /* Sending a WMVi message to notify the client*/
2256 vnc_lock_output(vs);
2257 vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2258 vnc_write_u8(vs, 0);
2259 vnc_write_u16(vs, 1); /* number of rects */
2260 vnc_framebuffer_update(vs, 0, 0,
2261 pixman_image_get_width(vs->vd->server),
2262 pixman_image_get_height(vs->vd->server),
2263 VNC_ENCODING_WMVi);
2264 pixel_format_message(vs);
2265 vnc_unlock_output(vs);
2266 vnc_flush(vs);
2267 } else {
2268 set_pixel_conversion(vs);
2269 }
2270 }
2271
2272 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2273 {
2274 int i;
2275 uint16_t limit;
2276 uint32_t freq;
2277 VncDisplay *vd = vs->vd;
2278
2279 if (data[0] > 3) {
2280 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2281 }
2282
2283 switch (data[0]) {
2284 case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2285 if (len == 1)
2286 return 20;
2287
2288 set_pixel_format(vs, read_u8(data, 4),
2289 read_u8(data, 6), read_u8(data, 7),
2290 read_u16(data, 8), read_u16(data, 10),
2291 read_u16(data, 12), read_u8(data, 14),
2292 read_u8(data, 15), read_u8(data, 16));
2293 break;
2294 case VNC_MSG_CLIENT_SET_ENCODINGS:
2295 if (len == 1)
2296 return 4;
2297
2298 if (len == 4) {
2299 limit = read_u16(data, 2);
2300 if (limit > 0)
2301 return 4 + (limit * 4);
2302 } else
2303 limit = read_u16(data, 2);
2304
2305 for (i = 0; i < limit; i++) {
2306 int32_t val = read_s32(data, 4 + (i * 4));
2307 memcpy(data + 4 + (i * 4), &val, sizeof(val));
2308 }
2309
2310 set_encodings(vs, (int32_t *)(data + 4), limit);
2311 break;
2312 case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2313 if (len == 1)
2314 return 10;
2315
2316 framebuffer_update_request(vs,
2317 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2318 read_u16(data, 6), read_u16(data, 8));
2319 break;
2320 case VNC_MSG_CLIENT_KEY_EVENT:
2321 if (len == 1)
2322 return 8;
2323
2324 key_event(vs, read_u8(data, 1), read_u32(data, 4));
2325 break;
2326 case VNC_MSG_CLIENT_POINTER_EVENT:
2327 if (len == 1)
2328 return 6;
2329
2330 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2331 break;
2332 case VNC_MSG_CLIENT_CUT_TEXT:
2333 if (len == 1) {
2334 return 8;
2335 }
2336 if (len == 8) {
2337 uint32_t dlen = read_u32(data, 4);
2338 if (dlen > (1 << 20)) {
2339 error_report("vnc: client_cut_text msg payload has %u bytes"
2340 " which exceeds our limit of 1MB.", dlen);
2341 vnc_client_error(vs);
2342 break;
2343 }
2344 if (dlen > 0) {
2345 return 8 + dlen;
2346 }
2347 }
2348
2349 client_cut_text(vs, read_u32(data, 4), data + 8);
2350 break;
2351 case VNC_MSG_CLIENT_QEMU:
2352 if (len == 1)
2353 return 2;
2354
2355 switch (read_u8(data, 1)) {
2356 case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2357 if (len == 2)
2358 return 12;
2359
2360 ext_key_event(vs, read_u16(data, 2),
2361 read_u32(data, 4), read_u32(data, 8));
2362 break;
2363 case VNC_MSG_CLIENT_QEMU_AUDIO:
2364 if (len == 2)
2365 return 4;
2366
2367 switch (read_u16 (data, 2)) {
2368 case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2369 audio_add(vs);
2370 break;
2371 case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2372 audio_del(vs);
2373 break;
2374 case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2375 if (len == 4)
2376 return 10;
2377 switch (read_u8(data, 4)) {
2378 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
2379 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
2380 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
2381 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
2382 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
2383 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
2384 default:
2385 VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2386 vnc_client_error(vs);
2387 break;
2388 }
2389 vs->as.nchannels = read_u8(data, 5);
2390 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2391 VNC_DEBUG("Invalid audio channel count %d\n",
2392 read_u8(data, 5));
2393 vnc_client_error(vs);
2394 break;
2395 }
2396 freq = read_u32(data, 6);
2397 /* No official limit for protocol, but 48khz is a sensible
2398 * upper bound for trustworthy clients, and this limit
2399 * protects calculations involving 'vs->as.freq' later.
2400 */
2401 if (freq > 48000) {
2402 VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2403 vnc_client_error(vs);
2404 break;
2405 }
2406 vs->as.freq = freq;
2407 break;
2408 default:
2409 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2410 vnc_client_error(vs);
2411 break;
2412 }
2413 break;
2414
2415 default:
2416 VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2417 vnc_client_error(vs);
2418 break;
2419 }
2420 break;
2421 default:
2422 VNC_DEBUG("Msg: %d\n", data[0]);
2423 vnc_client_error(vs);
2424 break;
2425 }
2426
2427 vnc_update_throttle_offset(vs);
2428 vnc_read_when(vs, protocol_client_msg, 1);
2429 return 0;
2430 }
2431
2432 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2433 {
2434 char buf[1024];
2435 VncShareMode mode;
2436 int size;
2437
2438 mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2439 switch (vs->vd->share_policy) {
2440 case VNC_SHARE_POLICY_IGNORE:
2441 /*
2442 * Ignore the shared flag. Nothing to do here.
2443 *
2444 * Doesn't conform to the rfb spec but is traditional qemu
2445 * behavior, thus left here as option for compatibility
2446 * reasons.
2447 */
2448 break;
2449 case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2450 /*
2451 * Policy: Allow clients ask for exclusive access.
2452 *
2453 * Implementation: When a client asks for exclusive access,
2454 * disconnect all others. Shared connects are allowed as long
2455 * as no exclusive connection exists.
2456 *
2457 * This is how the rfb spec suggests to handle the shared flag.
2458 */
2459 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2460 VncState *client;
2461 QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2462 if (vs == client) {
2463 continue;
2464 }
2465 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2466 client->share_mode != VNC_SHARE_MODE_SHARED) {
2467 continue;
2468 }
2469 vnc_disconnect_start(client);
2470 }
2471 }
2472 if (mode == VNC_SHARE_MODE_SHARED) {
2473 if (vs->vd->num_exclusive > 0) {
2474 vnc_disconnect_start(vs);
2475 return 0;
2476 }
2477 }
2478 break;
2479 case VNC_SHARE_POLICY_FORCE_SHARED:
2480 /*
2481 * Policy: Shared connects only.
2482 * Implementation: Disallow clients asking for exclusive access.
2483 *
2484 * Useful for shared desktop sessions where you don't want
2485 * someone forgetting to say -shared when running the vnc
2486 * client disconnect everybody else.
2487 */
2488 if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2489 vnc_disconnect_start(vs);
2490 return 0;
2491 }
2492 break;
2493 }
2494 vnc_set_share_mode(vs, mode);
2495
2496 if (vs->vd->num_shared > vs->vd->connections_limit) {
2497 vnc_disconnect_start(vs);
2498 return 0;
2499 }
2500
2501 assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2502 pixman_image_get_width(vs->vd->server) >= 0);
2503 assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2504 pixman_image_get_height(vs->vd->server) >= 0);
2505 vs->client_width = pixman_image_get_width(vs->vd->server);
2506 vs->client_height = pixman_image_get_height(vs->vd->server);
2507 vnc_write_u16(vs, vs->client_width);
2508 vnc_write_u16(vs, vs->client_height);
2509
2510 pixel_format_message(vs);
2511
2512 if (qemu_name) {
2513 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2514 if (size > sizeof(buf)) {
2515 size = sizeof(buf);
2516 }
2517 } else {
2518 size = snprintf(buf, sizeof(buf), "QEMU");
2519 }
2520
2521 vnc_write_u32(vs, size);
2522 vnc_write(vs, buf, size);
2523 vnc_flush(vs);
2524
2525 vnc_client_cache_auth(vs);
2526 vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2527
2528 vnc_read_when(vs, protocol_client_msg, 1);
2529
2530 return 0;
2531 }
2532
2533 void start_client_init(VncState *vs)
2534 {
2535 vnc_read_when(vs, protocol_client_init, 1);
2536 }
2537
2538 static void authentication_failed(VncState *vs)
2539 {
2540 vnc_write_u32(vs, 1); /* Reject auth */
2541 if (vs->minor >= 8) {
2542 static const char err[] = "Authentication failed";
2543 vnc_write_u32(vs, sizeof(err));
2544 vnc_write(vs, err, sizeof(err));
2545 }
2546 vnc_flush(vs);
2547 vnc_client_error(vs);
2548 }
2549
2550 static void make_challenge(VncState *vs)
2551 {
2552 int i;
2553
2554 srand(time(NULL)+getpid()+getpid()*987654+rand());
2555
2556 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2557 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2558 }
2559
2560 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2561 {
2562 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2563 size_t i, pwlen;
2564 unsigned char key[8];
2565 time_t now = time(NULL);
2566 QCryptoCipher *cipher = NULL;
2567 Error *err = NULL;
2568
2569 if (!vs->vd->password) {
2570 trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2571 goto reject;
2572 }
2573 if (vs->vd->expires < now) {
2574 trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2575 goto reject;
2576 }
2577
2578 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2579
2580 /* Calculate the expected challenge response */
2581 pwlen = strlen(vs->vd->password);
2582 for (i=0; i<sizeof(key); i++)
2583 key[i] = i<pwlen ? vs->vd->password[i] : 0;
2584
2585 cipher = qcrypto_cipher_new(
2586 QCRYPTO_CIPHER_ALG_DES_RFB,
2587 QCRYPTO_CIPHER_MODE_ECB,
2588 key, G_N_ELEMENTS(key),
2589 &err);
2590 if (!cipher) {
2591 trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2592 error_get_pretty(err));
2593 error_free(err);
2594 goto reject;
2595 }
2596
2597 if (qcrypto_cipher_encrypt(cipher,
2598 vs->challenge,
2599 response,
2600 VNC_AUTH_CHALLENGE_SIZE,
2601 &err) < 0) {
2602 trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2603 error_get_pretty(err));
2604 error_free(err);
2605 goto reject;
2606 }
2607
2608 /* Compare expected vs actual challenge response */
2609 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2610 trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2611 goto reject;
2612 } else {
2613 trace_vnc_auth_pass(vs, vs->auth);
2614 vnc_write_u32(vs, 0); /* Accept auth */
2615 vnc_flush(vs);
2616
2617 start_client_init(vs);
2618 }
2619
2620 qcrypto_cipher_free(cipher);
2621 return 0;
2622
2623 reject:
2624 authentication_failed(vs);
2625 qcrypto_cipher_free(cipher);
2626 return 0;
2627 }
2628
2629 void start_auth_vnc(VncState *vs)
2630 {
2631 make_challenge(vs);
2632 /* Send client a 'random' challenge */
2633 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2634 vnc_flush(vs);
2635
2636 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2637 }
2638
2639
2640 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2641 {
2642 /* We only advertise 1 auth scheme at a time, so client
2643 * must pick the one we sent. Verify this */
2644 if (data[0] != vs->auth) { /* Reject auth */
2645 trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2646 authentication_failed(vs);
2647 } else { /* Accept requested auth */
2648 trace_vnc_auth_start(vs, vs->auth);
2649 switch (vs->auth) {
2650 case VNC_AUTH_NONE:
2651 if (vs->minor >= 8) {
2652 vnc_write_u32(vs, 0); /* Accept auth completion */
2653 vnc_flush(vs);
2654 }
2655 trace_vnc_auth_pass(vs, vs->auth);
2656 start_client_init(vs);
2657 break;
2658
2659 case VNC_AUTH_VNC:
2660 start_auth_vnc(vs);
2661 break;
2662
2663 case VNC_AUTH_VENCRYPT:
2664 start_auth_vencrypt(vs);
2665 break;
2666
2667 #ifdef CONFIG_VNC_SASL
2668 case VNC_AUTH_SASL:
2669 start_auth_sasl(vs);
2670 break;
2671 #endif /* CONFIG_VNC_SASL */
2672
2673 default: /* Should not be possible, but just in case */
2674 trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2675 authentication_failed(vs);
2676 }
2677 }
2678 return 0;
2679 }
2680
2681 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2682 {
2683 char local[13];
2684
2685 memcpy(local, version, 12);
2686 local[12] = 0;
2687
2688 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2689 VNC_DEBUG("Malformed protocol version %s\n", local);
2690 vnc_client_error(vs);
2691 return 0;
2692 }
2693 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2694 if (vs->major != 3 ||
2695 (vs->minor != 3 &&
2696 vs->minor != 4 &&
2697 vs->minor != 5 &&
2698 vs->minor != 7 &&
2699 vs->minor != 8)) {
2700 VNC_DEBUG("Unsupported client version\n");
2701 vnc_write_u32(vs, VNC_AUTH_INVALID);
2702 vnc_flush(vs);
2703 vnc_client_error(vs);
2704 return 0;
2705 }
2706 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2707 * as equivalent to v3.3 by servers
2708 */
2709 if (vs->minor == 4 || vs->minor == 5)
2710 vs->minor = 3;
2711
2712 if (vs->minor == 3) {
2713 trace_vnc_auth_start(vs, vs->auth);
2714 if (vs->auth == VNC_AUTH_NONE) {
2715 vnc_write_u32(vs, vs->auth);
2716 vnc_flush(vs);
2717 trace_vnc_auth_pass(vs, vs->auth);
2718 start_client_init(vs);
2719 } else if (vs->auth == VNC_AUTH_VNC) {
2720 VNC_DEBUG("Tell client VNC auth\n");
2721 vnc_write_u32(vs, vs->auth);
2722 vnc_flush(vs);
2723 start_auth_vnc(vs);
2724 } else {
2725 trace_vnc_auth_fail(vs, vs->auth,
2726 "Unsupported auth method for v3.3", "");
2727 vnc_write_u32(vs, VNC_AUTH_INVALID);
2728 vnc_flush(vs);
2729 vnc_client_error(vs);
2730 }
2731 } else {
2732 vnc_write_u8(vs, 1); /* num auth */
2733 vnc_write_u8(vs, vs->auth);
2734 vnc_read_when(vs, protocol_client_auth, 1);
2735 vnc_flush(vs);
2736 }
2737
2738 return 0;
2739 }
2740
2741 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2742 {
2743 struct VncSurface *vs = &vd->guest;
2744
2745 return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2746 }
2747
2748 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2749 {
2750 int i, j;
2751
2752 w = (x + w) / VNC_STAT_RECT;
2753 h = (y + h) / VNC_STAT_RECT;
2754 x /= VNC_STAT_RECT;
2755 y /= VNC_STAT_RECT;
2756
2757 for (j = y; j <= h; j++) {
2758 for (i = x; i <= w; i++) {
2759 vs->lossy_rect[j][i] = 1;
2760 }
2761 }
2762 }
2763
2764 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2765 {
2766 VncState *vs;
2767 int sty = y / VNC_STAT_RECT;
2768 int stx = x / VNC_STAT_RECT;
2769 int has_dirty = 0;
2770
2771 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2772 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2773
2774 QTAILQ_FOREACH(vs, &vd->clients, next) {
2775 int j;
2776
2777 /* kernel send buffers are full -> refresh later */
2778 if (vs->output.offset) {
2779 continue;
2780 }
2781
2782 if (!vs->lossy_rect[sty][stx]) {
2783 continue;
2784 }
2785
2786 vs->lossy_rect[sty][stx] = 0;
2787 for (j = 0; j < VNC_STAT_RECT; ++j) {
2788 bitmap_set(vs->dirty[y + j],
2789 x / VNC_DIRTY_PIXELS_PER_BIT,
2790 VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2791 }
2792 has_dirty++;
2793 }
2794
2795 return has_dirty;
2796 }
2797
2798 static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
2799 {
2800 int width = MIN(pixman_image_get_width(vd->guest.fb),
2801 pixman_image_get_width(vd->server));
2802 int height = MIN(pixman_image_get_height(vd->guest.fb),
2803 pixman_image_get_height(vd->server));
2804 int x, y;
2805 struct timeval res;
2806 int has_dirty = 0;
2807
2808 for (y = 0; y < height; y += VNC_STAT_RECT) {
2809 for (x = 0; x < width; x += VNC_STAT_RECT) {
2810 VncRectStat *rect = vnc_stat_rect(vd, x, y);
2811
2812 rect->updated = false;
2813 }
2814 }
2815
2816 qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2817
2818 if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2819 return has_dirty;
2820 }
2821 vd->guest.last_freq_check = *tv;
2822
2823 for (y = 0; y < height; y += VNC_STAT_RECT) {
2824 for (x = 0; x < width; x += VNC_STAT_RECT) {
2825 VncRectStat *rect= vnc_stat_rect(vd, x, y);
2826 int count = ARRAY_SIZE(rect->times);
2827 struct timeval min, max;
2828
2829 if (!timerisset(&rect->times[count - 1])) {
2830 continue ;
2831 }
2832
2833 max = rect->times[(rect->idx + count - 1) % count];
2834 qemu_timersub(tv, &max, &res);
2835
2836 if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2837 rect->freq = 0;
2838 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2839 memset(rect->times, 0, sizeof (rect->times));
2840 continue ;
2841 }
2842
2843 min = rect->times[rect->idx];
2844 max = rect->times[(rect->idx + count - 1) % count];
2845 qemu_timersub(&max, &min, &res);
2846
2847 rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2848 rect->freq /= count;
2849 rect->freq = 1. / rect->freq;
2850 }
2851 }
2852 return has_dirty;
2853 }
2854
2855 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2856 {
2857 int i, j;
2858 double total = 0;
2859 int num = 0;
2860
2861 x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2862 y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2863
2864 for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2865 for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2866 total += vnc_stat_rect(vs->vd, i, j)->freq;
2867 num++;
2868 }
2869 }
2870
2871 if (num) {
2872 return total / num;
2873 } else {
2874 return 0;
2875 }
2876 }
2877
2878 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2879 {
2880 VncRectStat *rect;
2881
2882 rect = vnc_stat_rect(vd, x, y);
2883 if (rect->updated) {
2884 return ;
2885 }
2886 rect->times[rect->idx] = *tv;
2887 rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2888 rect->updated = true;
2889 }
2890
2891 static int vnc_refresh_server_surface(VncDisplay *vd)
2892 {
2893 int width = MIN(pixman_image_get_width(vd->guest.fb),
2894 pixman_image_get_width(vd->server));
2895 int height = MIN(pixman_image_get_height(vd->guest.fb),
2896 pixman_image_get_height(vd->server));
2897 int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2898 uint8_t *guest_row0 = NULL, *server_row0;
2899 VncState *vs;
2900 int has_dirty = 0;
2901 pixman_image_t *tmpbuf = NULL;
2902
2903 struct timeval tv = { 0, 0 };
2904
2905 if (!vd->non_adaptive) {
2906 gettimeofday(&tv, NULL);
2907 has_dirty = vnc_update_stats(vd, &tv);
2908 }
2909
2910 /*
2911 * Walk through the guest dirty map.
2912 * Check and copy modified bits from guest to server surface.
2913 * Update server dirty map.
2914 */
2915 server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2916 server_stride = guest_stride = guest_ll =
2917 pixman_image_get_stride(vd->server);
2918 cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2919 server_stride);
2920 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2921 int width = pixman_image_get_width(vd->server);
2922 tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2923 } else {
2924 int guest_bpp =
2925 PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2926 guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2927 guest_stride = pixman_image_get_stride(vd->guest.fb);
2928 guest_ll = pixman_image_get_width(vd->guest.fb)
2929 * DIV_ROUND_UP(guest_bpp, 8);
2930 }
2931 line_bytes = MIN(server_stride, guest_ll);
2932
2933 for (;;) {
2934 int x;
2935 uint8_t *guest_ptr, *server_ptr;
2936 unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2937 height * VNC_DIRTY_BPL(&vd->guest),
2938 y * VNC_DIRTY_BPL(&vd->guest));
2939 if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2940 /* no more dirty bits */
2941 break;
2942 }
2943 y = offset / VNC_DIRTY_BPL(&vd->guest);
2944 x = offset % VNC_DIRTY_BPL(&vd->guest);
2945
2946 server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2947
2948 if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2949 qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2950 guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2951 } else {
2952 guest_ptr = guest_row0 + y * guest_stride;
2953 }
2954 guest_ptr += x * cmp_bytes;
2955
2956 for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2957 x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2958 int _cmp_bytes = cmp_bytes;
2959 if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2960 continue;
2961 }
2962 if ((x + 1) * cmp_bytes > line_bytes) {
2963 _cmp_bytes = line_bytes - x * cmp_bytes;
2964 }
2965 assert(_cmp_bytes >= 0);
2966 if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2967 continue;
2968 }
2969 memcpy(server_ptr, guest_ptr, _cmp_bytes);
2970 if (!vd->non_adaptive) {
2971 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2972 y, &tv);
2973 }
2974 QTAILQ_FOREACH(vs, &vd->clients, next) {
2975 set_bit(x, vs->dirty[y]);
2976 }
2977 has_dirty++;
2978 }
2979
2980 y++;
2981 }
2982 qemu_pixman_image_unref(tmpbuf);
2983 return has_dirty;
2984 }
2985
2986 static void vnc_refresh(DisplayChangeListener *dcl)
2987 {
2988 VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2989 VncState *vs, *vn;
2990 int has_dirty, rects = 0;
2991
2992 if (QTAILQ_EMPTY(&vd->clients)) {
2993 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2994 return;
2995 }
2996
2997 graphic_hw_update(vd->dcl.con);
2998
2999 if (vnc_trylock_display(vd)) {
3000 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3001 return;
3002 }
3003
3004 has_dirty = vnc_refresh_server_surface(vd);
3005 vnc_unlock_display(vd);
3006
3007 QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
3008 rects += vnc_update_client(vs, has_dirty);
3009 /* vs might be free()ed here */
3010 }
3011
3012 if (has_dirty && rects) {
3013 vd->dcl.update_interval /= 2;
3014 if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3015 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3016 }
3017 } else {
3018 vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3019 if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3020 vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3021 }
3022 }
3023 }
3024
3025 static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3026 bool skipauth, bool websocket)
3027 {
3028 VncState *vs = g_new0(VncState, 1);
3029 bool first_client = QTAILQ_EMPTY(&vd->clients);
3030 int i;
3031
3032 trace_vnc_client_connect(vs, sioc);
3033 vs->magic = VNC_MAGIC;
3034 vs->sioc = sioc;
3035 object_ref(OBJECT(vs->sioc));
3036 vs->ioc = QIO_CHANNEL(sioc);
3037 object_ref(OBJECT(vs->ioc));
3038 vs->vd = vd;
3039
3040 buffer_init(&vs->input, "vnc-input/%p", sioc);
3041 buffer_init(&vs->output, "vnc-output/%p", sioc);
3042 buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc);
3043
3044 buffer_init(&vs->tight.tight, "vnc-tight/%p", sioc);
3045 buffer_init(&vs->tight.zlib, "vnc-tight-zlib/%p", sioc);
3046 buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
3047 #ifdef CONFIG_VNC_JPEG
3048 buffer_init(&vs->tight.jpeg, "vnc-tight-jpeg/%p", sioc);
3049 #endif
3050 #ifdef CONFIG_VNC_PNG
3051 buffer_init(&vs->tight.png, "vnc-tight-png/%p", sioc);
3052 #endif
3053 buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc);
3054 buffer_init(&vs->zrle.zrle, "vnc-zrle/%p", sioc);
3055 buffer_init(&vs->zrle.fb, "vnc-zrle-fb/%p", sioc);
3056 buffer_init(&vs->zrle.zlib, "vnc-zrle-zlib/%p", sioc);
3057
3058 if (skipauth) {
3059 vs->auth = VNC_AUTH_NONE;
3060 vs->subauth = VNC_AUTH_INVALID;
3061 } else {
3062 if (websocket) {
3063 vs->auth = vd->ws_auth;
3064 vs->subauth = VNC_AUTH_INVALID;
3065 } else {
3066 vs->auth = vd->auth;
3067 vs->subauth = vd->subauth;
3068 }
3069 }
3070 VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3071 sioc, websocket, vs->auth, vs->subauth);
3072
3073 vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3074 for (i = 0; i < VNC_STAT_ROWS; ++i) {
3075 vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3076 }
3077
3078 VNC_DEBUG("New client on socket %p\n", vs->sioc);
3079 update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3080 qio_channel_set_blocking(vs->ioc, false, NULL);
3081 if (vs->ioc_tag) {
3082 g_source_remove(vs->ioc_tag);
3083 }
3084 if (websocket) {
3085 vs->websocket = 1;
3086 if (vd->tlscreds) {
3087 vs->ioc_tag = qio_channel_add_watch(
3088 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
3089 } else {
3090 vs->ioc_tag = qio_channel_add_watch(
3091 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
3092 }
3093 } else {
3094 vs->ioc_tag = qio_channel_add_watch(
3095 vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
3096 }
3097
3098 vnc_client_cache_addr(vs);
3099 vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3100 vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3101
3102 vs->last_x = -1;
3103 vs->last_y = -1;
3104
3105 vs->as.freq = 44100;
3106 vs->as.nchannels = 2;
3107 vs->as.fmt = AUDIO_FORMAT_S16;
3108 vs->as.endianness = 0;
3109
3110 qemu_mutex_init(&vs->output_mutex);
3111 vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3112
3113 QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3114 if (first_client) {
3115 vnc_update_server_surface(vd);
3116 }
3117
3118 graphic_hw_update(vd->dcl.con);
3119
3120 if (!vs->websocket) {
3121 vnc_start_protocol(vs);
3122 }
3123
3124 if (vd->num_connecting > vd->connections_limit) {
3125 QTAILQ_FOREACH(vs, &vd->clients, next) {
3126 if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3127 vnc_disconnect_start(vs);
3128 return;
3129 }
3130 }
3131 }
3132 }
3133
3134 void vnc_start_protocol(VncState *vs)
3135 {
3136 vnc_write(vs, "RFB 003.008\n", 12);
3137 vnc_flush(vs);
3138 vnc_read_when(vs, protocol_version, 12);
3139
3140 vs->mouse_mode_notifier.notify = check_pointer_type_change;
3141 qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3142 }
3143
3144 static void vnc_listen_io(QIONetListener *listener,
3145 QIOChannelSocket *cioc,
3146 void *opaque)
3147 {
3148 VncDisplay *vd = opaque;
3149 bool isWebsock = listener == vd->wslistener;
3150
3151 qio_channel_set_name(QIO_CHANNEL(cioc),
3152 isWebsock ? "vnc-ws-server" : "vnc-server");
3153 qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3154 vnc_connect(vd, cioc, false, isWebsock);
3155 }
3156
3157 static const DisplayChangeListenerOps dcl_ops = {
3158 .dpy_name = "vnc",
3159 .dpy_refresh = vnc_refresh,
3160 .dpy_gfx_update = vnc_dpy_update,
3161 .dpy_gfx_switch = vnc_dpy_switch,
3162 .dpy_gfx_check_format = qemu_pixman_check_format,
3163 .dpy_mouse_set = vnc_mouse_set,
3164 .dpy_cursor_define = vnc_dpy_cursor_define,
3165 };
3166
3167 void vnc_display_init(const char *id, Error **errp)
3168 {
3169 VncDisplay *vd;
3170
3171 if (vnc_display_find(id) != NULL) {
3172 return;
3173 }
3174 vd = g_malloc0(sizeof(*vd));
3175
3176 vd->id = strdup(id);
3177 QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3178
3179 QTAILQ_INIT(&vd->clients);
3180 vd->expires = TIME_MAX;
3181
3182 if (keyboard_layout) {
3183 trace_vnc_key_map_init(keyboard_layout);
3184 vd->kbd_layout = init_keyboard_layout(name2keysym,
3185 keyboard_layout, errp);
3186 } else {
3187 vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3188 }
3189
3190 if (!vd->kbd_layout) {
3191 return;
3192 }
3193
3194 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3195 vd->connections_limit = 32;
3196
3197 qemu_mutex_init(&vd->mutex);
3198 vnc_start_worker_thread();
3199
3200 vd->dcl.ops = &dcl_ops;
3201 register_displaychangelistener(&vd->dcl);
3202 vd->kbd = qkbd_state_init(vd->dcl.con);
3203 }
3204
3205
3206 static void vnc_display_close(VncDisplay *vd)
3207 {
3208 if (!vd) {
3209 return;
3210 }
3211 vd->is_unix = false;
3212
3213 if (vd->listener) {
3214 qio_net_listener_disconnect(vd->listener);
3215 object_unref(OBJECT(vd->listener));
3216 }
3217 vd->listener = NULL;
3218
3219 if (vd->wslistener) {
3220 qio_net_listener_disconnect(vd->wslistener);
3221 object_unref(OBJECT(vd->wslistener));
3222 }
3223 vd->wslistener = NULL;
3224
3225 vd->auth = VNC_AUTH_INVALID;
3226 vd->subauth = VNC_AUTH_INVALID;
3227 if (vd->tlscreds) {
3228 object_unparent(OBJECT(vd->tlscreds));
3229 vd->tlscreds = NULL;
3230 }
3231 if (vd->tlsauthz) {
3232 object_unparent(OBJECT(vd->tlsauthz));
3233 vd->tlsauthz = NULL;
3234 }
3235 g_free(vd->tlsauthzid);
3236 vd->tlsauthzid = NULL;
3237 if (vd->lock_key_sync) {
3238 qemu_remove_led_event_handler(vd->led);
3239 vd->led = NULL;
3240 }
3241 #ifdef CONFIG_VNC_SASL
3242 if (vd->sasl.authz) {
3243 object_unparent(OBJECT(vd->sasl.authz));
3244 vd->sasl.authz = NULL;
3245 }
3246 g_free(vd->sasl.authzid);
3247 vd->sasl.authzid = NULL;
3248 #endif
3249 }
3250
3251 int vnc_display_password(const char *id, const char *password)
3252 {
3253 VncDisplay *vd = vnc_display_find(id);
3254
3255 if (!vd) {
3256 return -EINVAL;
3257 }
3258 if (vd->auth == VNC_AUTH_NONE) {
3259 error_printf_unless_qmp("If you want use passwords please enable "
3260 "password auth using '-vnc ${dpy},password'.\n");
3261 return -EINVAL;
3262 }
3263
3264 g_free(vd->password);
3265 vd->password = g_strdup(password);
3266
3267 return 0;
3268 }
3269
3270 int vnc_display_pw_expire(const char *id, time_t expires)
3271 {
3272 VncDisplay *vd = vnc_display_find(id);
3273
3274 if (!vd) {
3275 return -EINVAL;
3276 }
3277
3278 vd->expires = expires;
3279 return 0;
3280 }
3281
3282 static void vnc_display_print_local_addr(VncDisplay *vd)
3283 {
3284 SocketAddress *addr;
3285 Error *err = NULL;
3286
3287 if (!vd->listener || !vd->listener->nsioc) {
3288 return;
3289 }
3290
3291 addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], &err);
3292 if (!addr) {
3293 return;
3294 }
3295
3296 if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3297 qapi_free_SocketAddress(addr);
3298 return;
3299 }
3300 error_printf_unless_qmp("VNC server running on %s:%s\n",
3301 addr->u.inet.host,
3302 addr->u.inet.port);
3303 qapi_free_SocketAddress(addr);
3304 }
3305
3306 static QemuOptsList qemu_vnc_opts = {
3307 .name = "vnc",
3308 .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3309 .implied_opt_name = "vnc",
3310 .desc = {
3311 {
3312 .name = "vnc",
3313 .type = QEMU_OPT_STRING,
3314 },{
3315 .name = "websocket",
3316 .type = QEMU_OPT_STRING,
3317 },{
3318 .name = "tls-creds",
3319 .type = QEMU_OPT_STRING,
3320 },{
3321 .name = "share",
3322 .type = QEMU_OPT_STRING,
3323 },{
3324 .name = "display",
3325 .type = QEMU_OPT_STRING,
3326 },{
3327 .name = "head",
3328 .type = QEMU_OPT_NUMBER,
3329 },{
3330 .name = "connections",
3331 .type = QEMU_OPT_NUMBER,
3332 },{
3333 .name = "to",
3334 .type = QEMU_OPT_NUMBER,
3335 },{
3336 .name = "ipv4",
3337 .type = QEMU_OPT_BOOL,
3338 },{
3339 .name = "ipv6",
3340 .type = QEMU_OPT_BOOL,
3341 },{
3342 .name = "password",
3343 .type = QEMU_OPT_BOOL,
3344 },{
3345 .name = "reverse",
3346 .type = QEMU_OPT_BOOL,
3347 },{
3348 .name = "lock-key-sync",
3349 .type = QEMU_OPT_BOOL,
3350 },{
3351 .name = "key-delay-ms",
3352 .type = QEMU_OPT_NUMBER,
3353 },{
3354 .name = "sasl",
3355 .type = QEMU_OPT_BOOL,
3356 },{
3357 .name = "acl",
3358 .type = QEMU_OPT_BOOL,
3359 },{
3360 .name = "tls-authz",
3361 .type = QEMU_OPT_STRING,
3362 },{
3363 .name = "sasl-authz",
3364 .type = QEMU_OPT_STRING,
3365 },{
3366 .name = "lossy",
3367 .type = QEMU_OPT_BOOL,
3368 },{
3369 .name = "non-adaptive",
3370 .type = QEMU_OPT_BOOL,
3371 },
3372 { /* end of list */ }
3373 },
3374 };
3375
3376
3377 static int
3378 vnc_display_setup_auth(int *auth,
3379 int *subauth,
3380 QCryptoTLSCreds *tlscreds,
3381 bool password,
3382 bool sasl,
3383 bool websocket,
3384 Error **errp)
3385 {
3386 /*
3387 * We have a choice of 3 authentication options
3388 *
3389 * 1. none
3390 * 2. vnc
3391 * 3. sasl
3392 *
3393 * The channel can be run in 2 modes
3394 *
3395 * 1. clear
3396 * 2. tls
3397 *
3398 * And TLS can use 2 types of credentials
3399 *
3400 * 1. anon
3401 * 2. x509
3402 *
3403 * We thus have 9 possible logical combinations
3404 *
3405 * 1. clear + none
3406 * 2. clear + vnc
3407 * 3. clear + sasl
3408 * 4. tls + anon + none
3409 * 5. tls + anon + vnc
3410 * 6. tls + anon + sasl
3411 * 7. tls + x509 + none
3412 * 8. tls + x509 + vnc
3413 * 9. tls + x509 + sasl
3414 *
3415 * These need to be mapped into the VNC auth schemes
3416 * in an appropriate manner. In regular VNC, all the
3417 * TLS options get mapped into VNC_AUTH_VENCRYPT
3418 * sub-auth types.
3419 *
3420 * In websockets, the https:// protocol already provides
3421 * TLS support, so there is no need to make use of the
3422 * VeNCrypt extension. Furthermore, websockets browser
3423 * clients could not use VeNCrypt even if they wanted to,
3424 * as they cannot control when the TLS handshake takes
3425 * place. Thus there is no option but to rely on https://,
3426 * meaning combinations 4->6 and 7->9 will be mapped to
3427 * VNC auth schemes in the same way as combos 1->3.
3428 *
3429 * Regardless of fact that we have a different mapping to
3430 * VNC auth mechs for plain VNC vs websockets VNC, the end
3431 * result has the same security characteristics.
3432 */
3433 if (websocket || !tlscreds) {
3434 if (password) {
3435 VNC_DEBUG("Initializing VNC server with password auth\n");
3436 *auth = VNC_AUTH_VNC;
3437 } else if (sasl) {
3438 VNC_DEBUG("Initializing VNC server with SASL auth\n");
3439 *auth = VNC_AUTH_SASL;
3440 } else {
3441 VNC_DEBUG("Initializing VNC server with no auth\n");
3442 *auth = VNC_AUTH_NONE;
3443 }
3444 *subauth = VNC_AUTH_INVALID;
3445 } else {
3446 bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3447 TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3448 bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3449 TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3450
3451 if (!is_x509 && !is_anon) {
3452 error_setg(errp,
3453 "Unsupported TLS cred type %s",
3454 object_get_typename(OBJECT(tlscreds)));
3455 return -1;
3456 }
3457 *auth = VNC_AUTH_VENCRYPT;
3458 if (password) {
3459 if (is_x509) {
3460 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3461 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3462 } else {
3463 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3464 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3465 }
3466
3467 } else if (sasl) {
3468 if (is_x509) {
3469 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3470 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3471 } else {
3472 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3473 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3474 }
3475 } else {
3476 if (is_x509) {
3477 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3478 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3479 } else {
3480 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3481 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3482 }
3483 }
3484 }
3485 return 0;
3486 }
3487
3488
3489 static int vnc_display_get_address(const char *addrstr,
3490 bool websocket,
3491 bool reverse,
3492 int displaynum,
3493 int to,
3494 bool has_ipv4,
3495 bool has_ipv6,
3496 bool ipv4,
3497 bool ipv6,
3498 SocketAddress **retaddr,
3499 Error **errp)
3500 {
3501 int ret = -1;
3502 SocketAddress *addr = NULL;
3503
3504 addr = g_new0(SocketAddress, 1);
3505
3506 if (strncmp(addrstr, "unix:", 5) == 0) {
3507 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3508 addr->u.q_unix.path = g_strdup(addrstr + 5);
3509
3510 if (websocket) {
3511 error_setg(errp, "UNIX sockets not supported with websock");
3512 goto cleanup;
3513 }
3514
3515 if (to) {
3516 error_setg(errp, "Port range not support with UNIX socket");
3517 goto cleanup;
3518 }
3519 ret = 0;
3520 } else {
3521 const char *port;
3522 size_t hostlen;
3523 unsigned long long baseport = 0;
3524 InetSocketAddress *inet;
3525
3526 port = strrchr(addrstr, ':');
3527 if (!port) {
3528 if (websocket) {
3529 hostlen = 0;
3530 port = addrstr;
3531 } else {
3532 error_setg(errp, "no vnc port specified");
3533 goto cleanup;
3534 }
3535 } else {
3536 hostlen = port - addrstr;
3537 port++;
3538 if (*port == '\0') {
3539 error_setg(errp, "vnc port cannot be empty");
3540 goto cleanup;
3541 }
3542 }
3543
3544 addr->type = SOCKET_ADDRESS_TYPE_INET;
3545 inet = &addr->u.inet;
3546 if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3547 inet->host = g_strndup(addrstr + 1, hostlen - 2);
3548 } else {
3549 inet->host = g_strndup(addrstr, hostlen);
3550 }
3551 /* plain VNC port is just an offset, for websocket
3552 * port is absolute */
3553 if (websocket) {
3554 if (g_str_equal(addrstr, "") ||
3555 g_str_equal(addrstr, "on")) {
3556 if (displaynum == -1) {
3557 error_setg(errp, "explicit websocket port is required");
3558 goto cleanup;
3559 }
3560 inet->port = g_strdup_printf(
3561 "%d", displaynum + 5700);
3562 if (to) {
3563 inet->has_to = true;
3564 inet->to = to + 5700;
3565 }
3566 } else {
3567 inet->port = g_strdup(port);
3568 }
3569 } else {
3570 int offset = reverse ? 0 : 5900;
3571 if (parse_uint_full(port, &baseport, 10) < 0) {
3572 error_setg(errp, "can't convert to a number: %s", port);
3573 goto cleanup;
3574 }
3575 if (baseport > 65535 ||
3576 baseport + offset > 65535) {
3577 error_setg(errp, "port %s out of range", port);
3578 goto cleanup;
3579 }
3580 inet->port = g_strdup_printf(
3581 "%d", (int)baseport + offset);
3582
3583 if (to) {
3584 inet->has_to = true;
3585 inet->to = to + offset;
3586 }
3587 }
3588
3589 inet->ipv4 = ipv4;
3590 inet->has_ipv4 = has_ipv4;
3591 inet->ipv6 = ipv6;
3592 inet->has_ipv6 = has_ipv6;
3593
3594 ret = baseport;
3595 }
3596
3597 *retaddr = addr;
3598
3599 cleanup:
3600 if (ret < 0) {
3601 qapi_free_SocketAddress(addr);
3602 }
3603 return ret;
3604 }
3605
3606 static void vnc_free_addresses(SocketAddress ***retsaddr,
3607 size_t *retnsaddr)
3608 {
3609 size_t i;
3610
3611 for (i = 0; i < *retnsaddr; i++) {
3612 qapi_free_SocketAddress((*retsaddr)[i]);
3613 }
3614 g_free(*retsaddr);
3615
3616 *retsaddr = NULL;
3617 *retnsaddr = 0;
3618 }
3619
3620 static int vnc_display_get_addresses(QemuOpts *opts,
3621 bool reverse,
3622 SocketAddress ***retsaddr,
3623 size_t *retnsaddr,
3624 SocketAddress ***retwsaddr,
3625 size_t *retnwsaddr,
3626 Error **errp)
3627 {
3628 SocketAddress *saddr = NULL;
3629 SocketAddress *wsaddr = NULL;
3630 QemuOptsIter addriter;
3631 const char *addr;
3632 int to = qemu_opt_get_number(opts, "to", 0);
3633 bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3634 bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3635 bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3636 bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3637 int displaynum = -1;
3638 int ret = -1;
3639
3640 *retsaddr = NULL;
3641 *retnsaddr = 0;
3642 *retwsaddr = NULL;
3643 *retnwsaddr = 0;
3644
3645 addr = qemu_opt_get(opts, "vnc");
3646 if (addr == NULL || g_str_equal(addr, "none")) {
3647 ret = 0;
3648 goto cleanup;
3649 }
3650 if (qemu_opt_get(opts, "websocket") &&
3651 !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3652 error_setg(errp,
3653 "SHA1 hash support is required for websockets");
3654 goto cleanup;
3655 }
3656
3657 qemu_opt_iter_init(&addriter, opts, "vnc");
3658 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3659 int rv;
3660 rv = vnc_display_get_address(addr, false, reverse, 0, to,
3661 has_ipv4, has_ipv6,
3662 ipv4, ipv6,
3663 &saddr, errp);
3664 if (rv < 0) {
3665 goto cleanup;
3666 }
3667 /* Historical compat - first listen address can be used
3668 * to set the default websocket port
3669 */
3670 if (displaynum == -1) {
3671 displaynum = rv;
3672 }
3673 *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3674 (*retsaddr)[(*retnsaddr)++] = saddr;
3675 }
3676
3677 /* If we had multiple primary displays, we don't do defaults
3678 * for websocket, and require explicit config instead. */
3679 if (*retnsaddr > 1) {
3680 displaynum = -1;
3681 }
3682
3683 qemu_opt_iter_init(&addriter, opts, "websocket");
3684 while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3685 if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3686 has_ipv4, has_ipv6,
3687 ipv4, ipv6,
3688 &wsaddr, errp) < 0) {
3689 goto cleanup;
3690 }
3691
3692 /* Historical compat - if only a single listen address was
3693 * provided, then this is used to set the default listen
3694 * address for websocket too
3695 */
3696 if (*retnsaddr == 1 &&
3697 (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3698 wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3699 g_str_equal(wsaddr->u.inet.host, "") &&
3700 !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3701 g_free(wsaddr->u.inet.host);
3702 wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3703 }
3704
3705 *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3706 (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3707 }
3708
3709 ret = 0;
3710 cleanup:
3711 if (ret < 0) {
3712 vnc_free_addresses(retsaddr, retnsaddr);
3713 vnc_free_addresses(retwsaddr, retnwsaddr);
3714 }
3715 return ret;
3716 }
3717
3718 static int vnc_display_connect(VncDisplay *vd,
3719 SocketAddress **saddr,
3720 size_t nsaddr,
3721 SocketAddress **wsaddr,
3722 size_t nwsaddr,
3723 Error **errp)
3724 {
3725 /* connect to viewer */
3726 QIOChannelSocket *sioc = NULL;
3727 if (nwsaddr != 0) {
3728 error_setg(errp, "Cannot use websockets in reverse mode");
3729 return -1;
3730 }
3731 if (nsaddr != 1) {
3732 error_setg(errp, "Expected a single address in reverse mode");
3733 return -1;
3734 }
3735 /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3736 vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3737 sioc = qio_channel_socket_new();
3738 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3739 if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3740 return -1;
3741 }
3742 vnc_connect(vd, sioc, false, false);
3743 object_unref(OBJECT(sioc));
3744 return 0;
3745 }
3746
3747
3748 static int vnc_display_listen(VncDisplay *vd,
3749 SocketAddress **saddr,
3750 size_t nsaddr,
3751 SocketAddress **wsaddr,
3752 size_t nwsaddr,
3753 Error **errp)
3754 {
3755 size_t i;
3756
3757 if (nsaddr) {
3758 vd->listener = qio_net_listener_new();
3759 qio_net_listener_set_name(vd->listener, "vnc-listen");
3760 for (i = 0; i < nsaddr; i++) {
3761 if (qio_net_listener_open_sync(vd->listener,
3762 saddr[i],
3763 errp) < 0) {
3764 return -1;
3765 }
3766 }
3767
3768 qio_net_listener_set_client_func(vd->listener,
3769 vnc_listen_io, vd, NULL);
3770 }
3771
3772 if (nwsaddr) {
3773 vd->wslistener = qio_net_listener_new();
3774 qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3775 for (i = 0; i < nwsaddr; i++) {
3776 if (qio_net_listener_open_sync(vd->wslistener,
3777 wsaddr[i],
3778 errp) < 0) {
3779 return -1;
3780 }
3781 }
3782
3783 qio_net_listener_set_client_func(vd->wslistener,
3784 vnc_listen_io, vd, NULL);
3785 }
3786
3787 return 0;
3788 }
3789
3790
3791 void vnc_display_open(const char *id, Error **errp)
3792 {
3793 VncDisplay *vd = vnc_display_find(id);
3794 QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3795 SocketAddress **saddr = NULL, **wsaddr = NULL;
3796 size_t nsaddr, nwsaddr;
3797 const char *share, *device_id;
3798 QemuConsole *con;
3799 bool password = false;
3800 bool reverse = false;
3801 const char *credid;
3802 bool sasl = false;
3803 int acl = 0;
3804 const char *tlsauthz;
3805 const char *saslauthz;
3806 int lock_key_sync = 1;
3807 int key_delay_ms;
3808
3809 if (!vd) {
3810 error_setg(errp, "VNC display not active");
3811 return;
3812 }
3813 vnc_display_close(vd);
3814
3815 if (!opts) {
3816 return;
3817 }
3818
3819 reverse = qemu_opt_get_bool(opts, "reverse", false);
3820 if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3821 &wsaddr, &nwsaddr, errp) < 0) {
3822 goto fail;
3823 }
3824
3825 password = qemu_opt_get_bool(opts, "password", false);
3826 if (password) {
3827 if (fips_get_state()) {
3828 error_setg(errp,
3829 "VNC password auth disabled due to FIPS mode, "
3830 "consider using the VeNCrypt or SASL authentication "
3831 "methods as an alternative");
3832 goto fail;
3833 }
3834 if (!qcrypto_cipher_supports(
3835 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3836 error_setg(errp,
3837 "Cipher backend does not support DES RFB algorithm");
3838 goto fail;
3839 }
3840 }
3841
3842 lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3843 key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3844 sasl = qemu_opt_get_bool(opts, "sasl", false);
3845 #ifndef CONFIG_VNC_SASL
3846 if (sasl) {
3847 error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3848 goto fail;
3849 }
3850 #endif /* CONFIG_VNC_SASL */
3851 credid = qemu_opt_get(opts, "tls-creds");
3852 if (credid) {
3853 Object *creds;
3854 creds = object_resolve_path_component(
3855 object_get_objects_root(), credid);
3856 if (!creds) {
3857 error_setg(errp, "No TLS credentials with id '%s'",
3858 credid);
3859 goto fail;
3860 }
3861 vd->tlscreds = (QCryptoTLSCreds *)
3862 object_dynamic_cast(creds,
3863 TYPE_QCRYPTO_TLS_CREDS);
3864 if (!vd->tlscreds) {
3865 error_setg(errp, "Object with id '%s' is not TLS credentials",
3866 credid);
3867 goto fail;
3868 }
3869 object_ref(OBJECT(vd->tlscreds));
3870
3871 if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3872 error_setg(errp,
3873 "Expecting TLS credentials with a server endpoint");
3874 goto fail;
3875 }
3876 }
3877 if (qemu_opt_get(opts, "acl")) {
3878 error_report("The 'acl' option to -vnc is deprecated. "
3879 "Please use the 'tls-authz' and 'sasl-authz' "
3880 "options instead");
3881 }
3882 acl = qemu_opt_get_bool(opts, "acl", false);
3883 tlsauthz = qemu_opt_get(opts, "tls-authz");
3884 if (acl && tlsauthz) {
3885 error_setg(errp, "'acl' option is mutually exclusive with the "
3886 "'tls-authz' option");
3887 goto fail;
3888 }
3889 if (tlsauthz && !vd->tlscreds) {
3890 error_setg(errp, "'tls-authz' provided but TLS is not enabled");
3891 goto fail;
3892 }
3893
3894 saslauthz = qemu_opt_get(opts, "sasl-authz");
3895 if (acl && saslauthz) {
3896 error_setg(errp, "'acl' option is mutually exclusive with the "
3897 "'sasl-authz' option");
3898 goto fail;
3899 }
3900 if (saslauthz && !sasl) {
3901 error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
3902 goto fail;
3903 }
3904
3905 share = qemu_opt_get(opts, "share");
3906 if (share) {
3907 if (strcmp(share, "ignore") == 0) {
3908 vd->share_policy = VNC_SHARE_POLICY_IGNORE;
3909 } else if (strcmp(share, "allow-exclusive") == 0) {
3910 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3911 } else if (strcmp(share, "force-shared") == 0) {
3912 vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3913 } else {
3914 error_setg(errp, "unknown vnc share= option");
3915 goto fail;
3916 }
3917 } else {
3918 vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3919 }
3920 vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3921
3922 #ifdef CONFIG_VNC_JPEG
3923 vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
3924 #endif
3925 vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3926 /* adaptive updates are only used with tight encoding and
3927 * if lossy updates are enabled so we can disable all the
3928 * calculations otherwise */
3929 if (!vd->lossy) {
3930 vd->non_adaptive = true;
3931 }
3932
3933 if (tlsauthz) {
3934 vd->tlsauthzid = g_strdup(tlsauthz);
3935 } else if (acl) {
3936 if (strcmp(vd->id, "default") == 0) {
3937 vd->tlsauthzid = g_strdup("vnc.x509dname");
3938 } else {
3939 vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
3940 }
3941 vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
3942 QAUTHZ_LIST_POLICY_DENY,
3943 &error_abort));
3944 }
3945 #ifdef CONFIG_VNC_SASL
3946 if (sasl) {
3947 if (saslauthz) {
3948 vd->sasl.authzid = g_strdup(saslauthz);
3949 } else if (acl) {
3950 if (strcmp(vd->id, "default") == 0) {
3951 vd->sasl.authzid = g_strdup("vnc.username");
3952 } else {
3953 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
3954 }
3955 vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
3956 QAUTHZ_LIST_POLICY_DENY,
3957 &error_abort));
3958 }
3959 }
3960 #endif
3961
3962 if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
3963 vd->tlscreds, password,
3964 sasl, false, errp) < 0) {
3965 goto fail;
3966 }
3967 trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
3968
3969 if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
3970 vd->tlscreds, password,
3971 sasl, true, errp) < 0) {
3972 goto fail;
3973 }
3974 trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
3975
3976 #ifdef CONFIG_VNC_SASL
3977 if (sasl) {
3978 int saslErr = sasl_server_init(NULL, "qemu");
3979
3980 if (saslErr != SASL_OK) {
3981 error_setg(errp, "Failed to initialize SASL auth: %s",
3982 sasl_errstring(saslErr, NULL, NULL));
3983 goto fail;
3984 }
3985 }
3986 #endif
3987 vd->lock_key_sync = lock_key_sync;
3988 if (lock_key_sync) {
3989 vd->led = qemu_add_led_event_handler(kbd_leds, vd);
3990 }
3991 vd->ledstate = 0;
3992
3993 device_id = qemu_opt_get(opts, "display");
3994 if (device_id) {
3995 int head = qemu_opt_get_number(opts, "head", 0);
3996 Error *err = NULL;
3997
3998 con = qemu_console_lookup_by_device_name(device_id, head, &err);
3999 if (err) {
4000 error_propagate(errp, err);
4001 goto fail;
4002 }
4003 } else {
4004 con = NULL;
4005 }
4006
4007 if (con != vd->dcl.con) {
4008 qkbd_state_free(vd->kbd);
4009 unregister_displaychangelistener(&vd->dcl);
4010 vd->dcl.con = con;
4011 register_displaychangelistener(&vd->dcl);
4012 vd->kbd = qkbd_state_init(vd->dcl.con);
4013 }
4014 qkbd_state_set_delay(vd->kbd, key_delay_ms);
4015
4016 if (saddr == NULL) {
4017 goto cleanup;
4018 }
4019
4020 if (reverse) {
4021 if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4022 goto fail;
4023 }
4024 } else {
4025 if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4026 goto fail;
4027 }
4028 }
4029
4030 if (qemu_opt_get(opts, "to")) {
4031 vnc_display_print_local_addr(vd);
4032 }
4033
4034 cleanup:
4035 vnc_free_addresses(&saddr, &nsaddr);
4036 vnc_free_addresses(&wsaddr, &nwsaddr);
4037 return;
4038
4039 fail:
4040 vnc_display_close(vd);
4041 goto cleanup;
4042 }
4043
4044 void vnc_display_add_client(const char *id, int csock, bool skipauth)
4045 {
4046 VncDisplay *vd = vnc_display_find(id);
4047 QIOChannelSocket *sioc;
4048
4049 if (!vd) {
4050 return;
4051 }
4052
4053 sioc = qio_channel_socket_new_fd(csock, NULL);
4054 if (sioc) {
4055 qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4056 vnc_connect(vd, sioc, skipauth, false);
4057 object_unref(OBJECT(sioc));
4058 }
4059 }
4060
4061 static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4062 {
4063 int i = 2;
4064 char *id;
4065
4066 id = g_strdup("default");
4067 while (qemu_opts_find(olist, id)) {
4068 g_free(id);
4069 id = g_strdup_printf("vnc%d", i++);
4070 }
4071 qemu_opts_set_id(opts, id);
4072 }
4073
4074 QemuOpts *vnc_parse(const char *str, Error **errp)
4075 {
4076 QemuOptsList *olist = qemu_find_opts("vnc");
4077 QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
4078 const char *id;
4079
4080 if (!opts) {
4081 return NULL;
4082 }
4083
4084 id = qemu_opts_id(opts);
4085 if (!id) {
4086 /* auto-assign id if not present */
4087 vnc_auto_assign_id(olist, opts);
4088 }
4089 return opts;
4090 }
4091
4092 int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4093 {
4094 Error *local_err = NULL;
4095 char *id = (char *)qemu_opts_id(opts);
4096
4097 assert(id);
4098 vnc_display_init(id, &local_err);
4099 if (local_err) {
4100 error_propagate(errp, local_err);
4101 return -1;
4102 }
4103 vnc_display_open(id, &local_err);
4104 if (local_err != NULL) {
4105 error_propagate(errp, local_err);
4106 return -1;
4107 }
4108 return 0;
4109 }
4110
4111 static void vnc_register_config(void)
4112 {
4113 qemu_add_opts(&qemu_vnc_opts);
4114 }
4115 opts_init(vnc_register_config);