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