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