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