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