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