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