]> git.proxmox.com Git - mirror_qemu.git/blame - vnc.c
vnc: fix server surface pixel format.
[mirror_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"
24236869
FB
32
33#define VNC_REFRESH_INTERVAL (1000 / 30)
34
35#include "vnc_keysym.h"
70848515
TS
36#include "d3des.h"
37
90a1e3c0
AL
38#define count_bits(c, v) { \
39 for (c = 0; v; v >>= 1) \
40 { \
41 c += v & 1; \
42 } \
43}
8d5d2d4c 44
24236869 45
753b4053 46static VncDisplay *vnc_display; /* needed for info vnc */
7d957bd8 47static DisplayChangeListener *dcl;
a9ce8590 48
1ff7df1a
AL
49static char *addr_to_string(const char *format,
50 struct sockaddr_storage *sa,
51 socklen_t salen) {
52 char *addr;
53 char host[NI_MAXHOST];
54 char serv[NI_MAXSERV];
55 int err;
457772e6 56 size_t addrlen;
1ff7df1a
AL
57
58 if ((err = getnameinfo((struct sockaddr *)sa, salen,
59 host, sizeof(host),
60 serv, sizeof(serv),
61 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
62 VNC_DEBUG("Cannot resolve address %d: %s\n",
63 err, gai_strerror(err));
64 return NULL;
65 }
66
457772e6
AL
67 /* Enough for the existing format + the 2 vars we're
68 * subsituting in. */
69 addrlen = strlen(format) + strlen(host) + strlen(serv);
70 addr = qemu_malloc(addrlen + 1);
71 snprintf(addr, addrlen, format, host, serv);
72 addr[addrlen] = '\0';
1ff7df1a
AL
73
74 return addr;
75}
76
2f9606b3
AL
77
78char *vnc_socket_local_addr(const char *format, int fd) {
1ff7df1a
AL
79 struct sockaddr_storage sa;
80 socklen_t salen;
81
82 salen = sizeof(sa);
83 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
84 return NULL;
85
86 return addr_to_string(format, &sa, salen);
87}
88
2f9606b3
AL
89
90char *vnc_socket_remote_addr(const char *format, int fd) {
1ff7df1a
AL
91 struct sockaddr_storage sa;
92 socklen_t salen;
93
94 salen = sizeof(sa);
95 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
96 return NULL;
97
98 return addr_to_string(format, &sa, salen);
99}
100
101static const char *vnc_auth_name(VncDisplay *vd) {
102 switch (vd->auth) {
103 case VNC_AUTH_INVALID:
104 return "invalid";
105 case VNC_AUTH_NONE:
106 return "none";
107 case VNC_AUTH_VNC:
108 return "vnc";
109 case VNC_AUTH_RA2:
110 return "ra2";
111 case VNC_AUTH_RA2NE:
112 return "ra2ne";
113 case VNC_AUTH_TIGHT:
114 return "tight";
115 case VNC_AUTH_ULTRA:
116 return "ultra";
117 case VNC_AUTH_TLS:
118 return "tls";
119 case VNC_AUTH_VENCRYPT:
120#ifdef CONFIG_VNC_TLS
121 switch (vd->subauth) {
122 case VNC_AUTH_VENCRYPT_PLAIN:
123 return "vencrypt+plain";
124 case VNC_AUTH_VENCRYPT_TLSNONE:
125 return "vencrypt+tls+none";
126 case VNC_AUTH_VENCRYPT_TLSVNC:
127 return "vencrypt+tls+vnc";
128 case VNC_AUTH_VENCRYPT_TLSPLAIN:
129 return "vencrypt+tls+plain";
130 case VNC_AUTH_VENCRYPT_X509NONE:
131 return "vencrypt+x509+none";
132 case VNC_AUTH_VENCRYPT_X509VNC:
133 return "vencrypt+x509+vnc";
134 case VNC_AUTH_VENCRYPT_X509PLAIN:
135 return "vencrypt+x509+plain";
28a76be8
AL
136 case VNC_AUTH_VENCRYPT_TLSSASL:
137 return "vencrypt+tls+sasl";
138 case VNC_AUTH_VENCRYPT_X509SASL:
139 return "vencrypt+x509+sasl";
1ff7df1a
AL
140 default:
141 return "vencrypt";
142 }
143#else
144 return "vencrypt";
145#endif
2f9606b3 146 case VNC_AUTH_SASL:
28a76be8 147 return "sasl";
1ff7df1a
AL
148 }
149 return "unknown";
150}
151
1ff7df1a
AL
152static void do_info_vnc_client(Monitor *mon, VncState *client)
153{
154 char *clientAddr =
155 vnc_socket_remote_addr(" address: %s:%s\n",
156 client->csock);
157 if (!clientAddr)
158 return;
159
160 monitor_printf(mon, "Client:\n");
161 monitor_printf(mon, "%s", clientAddr);
162 free(clientAddr);
1263b7d6
AL
163
164#ifdef CONFIG_VNC_TLS
165 if (client->tls.session &&
28a76be8
AL
166 client->tls.dname)
167 monitor_printf(mon, " x509 dname: %s\n", client->tls.dname);
1263b7d6 168 else
28a76be8 169 monitor_printf(mon, " x509 dname: none\n");
1263b7d6
AL
170#endif
171#ifdef CONFIG_VNC_SASL
172 if (client->sasl.conn &&
28a76be8
AL
173 client->sasl.username)
174 monitor_printf(mon, " username: %s\n", client->sasl.username);
1263b7d6 175 else
28a76be8 176 monitor_printf(mon, " username: none\n");
1263b7d6 177#endif
1ff7df1a
AL
178}
179
376253ec 180void do_info_vnc(Monitor *mon)
a9ce8590 181{
1ff7df1a
AL
182 if (vnc_display == NULL || vnc_display->display == NULL) {
183 monitor_printf(mon, "Server: disabled\n");
184 } else {
185 char *serverAddr = vnc_socket_local_addr(" address: %s:%s\n",
186 vnc_display->lsock);
187
188 if (!serverAddr)
189 return;
190
191 monitor_printf(mon, "Server:\n");
192 monitor_printf(mon, "%s", serverAddr);
193 free(serverAddr);
194 monitor_printf(mon, " auth: %s\n", vnc_auth_name(vnc_display));
195
196 if (vnc_display->clients) {
197 VncState *client = vnc_display->clients;
198 while (client) {
199 do_info_vnc_client(mon, client);
200 client = client->next;
201 }
202 } else {
203 monitor_printf(mon, "Client: none\n");
204 }
a9ce8590
FB
205 }
206}
207
29fa4ed9
AL
208static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
209 return (vs->features & (1 << feature));
210}
211
24236869
FB
212/* TODO
213 1) Get the queue working for IO.
214 2) there is some weirdness when using the -S option (the screen is grey
215 and not totally invalidated
216 3) resolutions > 1024
217*/
218
24236869 219static void vnc_update_client(void *opaque);
24236869 220
753b4053 221static void vnc_colordepth(VncState *vs);
7eac3a87 222
99589bdc
FB
223static inline void vnc_set_bit(uint32_t *d, int k)
224{
225 d[k >> 5] |= 1 << (k & 0x1f);
226}
227
228static inline void vnc_clear_bit(uint32_t *d, int k)
229{
230 d[k >> 5] &= ~(1 << (k & 0x1f));
231}
232
233static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
234{
235 int j;
236
237 j = 0;
238 while (n >= 32) {
239 d[j++] = -1;
240 n -= 32;
241 }
5fafdf24 242 if (n > 0)
99589bdc
FB
243 d[j++] = (1 << n) - 1;
244 while (j < nb_words)
245 d[j++] = 0;
246}
247
248static inline int vnc_get_bit(const uint32_t *d, int k)
249{
250 return (d[k >> 5] >> (k & 0x1f)) & 1;
251}
252
5fafdf24 253static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
99589bdc
FB
254 int nb_words)
255{
256 int i;
257 for(i = 0; i < nb_words; i++) {
258 if ((d1[i] & d2[i]) != 0)
259 return 1;
260 }
261 return 0;
262}
263
753b4053 264static void vnc_update(VncState *vs, int x, int y, int w, int h)
24236869 265{
6baebed7 266 struct VncSurface *s = &vs->guest;
24236869
FB
267 int i;
268
269 h += y;
270
0486e8a7
AZ
271 /* round x down to ensure the loop only spans one 16-pixel block per,
272 iteration. otherwise, if (x % 16) != 0, the last iteration may span
273 two 16-pixel blocks but we only mark the first as dirty
274 */
275 w += (x % 16);
276 x -= (x % 16);
277
6baebed7
AL
278 x = MIN(x, s->ds->width);
279 y = MIN(y, s->ds->height);
280 w = MIN(x + w, s->ds->width) - x;
281 h = MIN(h, s->ds->height);
788abf8e 282
24236869 283 for (; y < h; y++)
28a76be8 284 for (i = 0; i < w; i += 16)
6baebed7 285 vnc_set_bit(s->dirty[y], (x + i) / 16);
24236869
FB
286}
287
753b4053
AL
288static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
289{
290 VncDisplay *vd = ds->opaque;
291 VncState *vs = vd->clients;
292 while (vs != NULL) {
293 vnc_update(vs, x, y, w, h);
294 vs = vs->next;
295 }
296}
297
24236869 298static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
28a76be8 299 int32_t encoding)
24236869
FB
300{
301 vnc_write_u16(vs, x);
302 vnc_write_u16(vs, y);
303 vnc_write_u16(vs, w);
304 vnc_write_u16(vs, h);
305
306 vnc_write_s32(vs, encoding);
307}
308
2f9606b3 309void buffer_reserve(Buffer *buffer, size_t len)
89064286
AL
310{
311 if ((buffer->capacity - buffer->offset) < len) {
28a76be8
AL
312 buffer->capacity += (len + 1024);
313 buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
314 if (buffer->buffer == NULL) {
315 fprintf(stderr, "vnc: out of memory\n");
316 exit(1);
317 }
89064286
AL
318 }
319}
320
2f9606b3 321int buffer_empty(Buffer *buffer)
89064286
AL
322{
323 return buffer->offset == 0;
324}
325
2f9606b3 326uint8_t *buffer_end(Buffer *buffer)
89064286
AL
327{
328 return buffer->buffer + buffer->offset;
329}
330
2f9606b3 331void buffer_reset(Buffer *buffer)
89064286 332{
28a76be8 333 buffer->offset = 0;
89064286
AL
334}
335
2f9606b3 336void buffer_append(Buffer *buffer, const void *data, size_t len)
89064286
AL
337{
338 memcpy(buffer->buffer + buffer->offset, data, len);
339 buffer->offset += len;
340}
341
753b4053 342static void vnc_resize(VncState *vs)
24236869 343{
753b4053 344 DisplayState *ds = vs->ds;
73e14b62 345 int size_changed;
24236869 346
6baebed7
AL
347 /* guest surface */
348 if (!vs->guest.ds)
349 vs->guest.ds = qemu_mallocz(sizeof(*vs->guest.ds));
350 if (ds_get_bytes_per_pixel(ds) != vs->guest.ds->pf.bytes_per_pixel)
a528b80c 351 console_color_init(ds);
753b4053 352 vnc_colordepth(vs);
6baebed7
AL
353 size_changed = ds_get_width(ds) != vs->guest.ds->width ||
354 ds_get_height(ds) != vs->guest.ds->height;
355 *(vs->guest.ds) = *(ds->surface);
b94eb43f 356 if (size_changed) {
29fa4ed9 357 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
b94eb43f
AZ
358 vnc_write_u8(vs, 0); /* msg id */
359 vnc_write_u8(vs, 0);
360 vnc_write_u16(vs, 1); /* number of rects */
29fa4ed9
AL
361 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
362 VNC_ENCODING_DESKTOPRESIZE);
b94eb43f
AZ
363 vnc_flush(vs);
364 }
24236869 365 }
6baebed7 366 memset(vs->guest.dirty, 0xFF, sizeof(vs->guest.dirty));
8bba5c81 367
6baebed7 368 /* server surface */
89ee676e
GH
369 if (!vs->server.ds)
370 vs->server.ds = qemu_mallocz(sizeof(*vs->server.ds));
371 if (vs->server.ds->data)
372 qemu_free(vs->server.ds->data);
373 *(vs->server.ds) = *(ds->surface);
374 vs->server.ds->data = qemu_mallocz(vs->server.ds->linesize *
375 vs->server.ds->height);
6baebed7 376 memset(vs->server.dirty, 0xFF, sizeof(vs->guest.dirty));
24236869
FB
377}
378
753b4053
AL
379static void vnc_dpy_resize(DisplayState *ds)
380{
381 VncDisplay *vd = ds->opaque;
382 VncState *vs = vd->clients;
383 while (vs != NULL) {
384 vnc_resize(vs);
385 vs = vs->next;
386 }
387}
388
3512779a
FB
389/* fastest code */
390static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
391{
392 vnc_write(vs, pixels, size);
393}
394
395/* slowest but generic code. */
396static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
397{
7eac3a87
AL
398 uint8_t r, g, b;
399
6baebed7
AL
400 r = ((((v & vs->server.ds->pf.rmask) >> vs->server.ds->pf.rshift) << vs->clientds.pf.rbits) >>
401 vs->server.ds->pf.rbits);
402 g = ((((v & vs->server.ds->pf.gmask) >> vs->server.ds->pf.gshift) << vs->clientds.pf.gbits) >>
403 vs->server.ds->pf.gbits);
404 b = ((((v & vs->server.ds->pf.bmask) >> vs->server.ds->pf.bshift) << vs->clientds.pf.bbits) >>
405 vs->server.ds->pf.bbits);
6cec5487
AL
406 v = (r << vs->clientds.pf.rshift) |
407 (g << vs->clientds.pf.gshift) |
408 (b << vs->clientds.pf.bshift);
409 switch(vs->clientds.pf.bytes_per_pixel) {
3512779a
FB
410 case 1:
411 buf[0] = v;
412 break;
413 case 2:
6cec5487 414 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
3512779a
FB
415 buf[0] = v >> 8;
416 buf[1] = v;
417 } else {
418 buf[1] = v >> 8;
419 buf[0] = v;
420 }
421 break;
422 default:
423 case 4:
6cec5487 424 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
3512779a
FB
425 buf[0] = v >> 24;
426 buf[1] = v >> 16;
427 buf[2] = v >> 8;
428 buf[3] = v;
429 } else {
430 buf[3] = v >> 24;
431 buf[2] = v >> 16;
432 buf[1] = v >> 8;
433 buf[0] = v;
434 }
435 break;
436 }
437}
438
439static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
440{
3512779a 441 uint8_t buf[4];
3512779a 442
6baebed7 443 if (vs->server.ds->pf.bytes_per_pixel == 4) {
7eac3a87
AL
444 uint32_t *pixels = pixels1;
445 int n, i;
446 n = size >> 2;
447 for(i = 0; i < n; i++) {
448 vnc_convert_pixel(vs, buf, pixels[i]);
6cec5487 449 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
7eac3a87 450 }
6baebed7 451 } else if (vs->server.ds->pf.bytes_per_pixel == 2) {
7eac3a87
AL
452 uint16_t *pixels = pixels1;
453 int n, i;
454 n = size >> 1;
455 for(i = 0; i < n; i++) {
456 vnc_convert_pixel(vs, buf, pixels[i]);
6cec5487 457 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
7eac3a87 458 }
6baebed7 459 } else if (vs->server.ds->pf.bytes_per_pixel == 1) {
7eac3a87
AL
460 uint8_t *pixels = pixels1;
461 int n, i;
462 n = size;
463 for(i = 0; i < n; i++) {
464 vnc_convert_pixel(vs, buf, pixels[i]);
6cec5487 465 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
7eac3a87
AL
466 }
467 } else {
468 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
3512779a
FB
469 }
470}
471
24236869
FB
472static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
473{
474 int i;
60fe76f3 475 uint8_t *row;
24236869 476
6baebed7 477 row = vs->server.ds->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
24236869 478 for (i = 0; i < h; i++) {
28a76be8
AL
479 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
480 row += ds_get_linesize(vs->ds);
24236869
FB
481 }
482}
483
484static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
485{
486 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
487 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
488}
489
490#define BPP 8
491#include "vnchextile.h"
492#undef BPP
493
494#define BPP 16
495#include "vnchextile.h"
496#undef BPP
497
498#define BPP 32
499#include "vnchextile.h"
500#undef BPP
501
7eac3a87
AL
502#define GENERIC
503#define BPP 8
504#include "vnchextile.h"
505#undef BPP
506#undef GENERIC
507
508#define GENERIC
509#define BPP 16
510#include "vnchextile.h"
511#undef BPP
512#undef GENERIC
513
3512779a
FB
514#define GENERIC
515#define BPP 32
516#include "vnchextile.h"
517#undef BPP
518#undef GENERIC
519
24236869
FB
520static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
521{
522 int i, j;
523 int has_fg, has_bg;
7eac3a87 524 uint8_t *last_fg, *last_bg;
24236869 525
6baebed7
AL
526 last_fg = (uint8_t *) qemu_malloc(vs->server.ds->pf.bytes_per_pixel);
527 last_bg = (uint8_t *) qemu_malloc(vs->server.ds->pf.bytes_per_pixel);
24236869
FB
528 has_fg = has_bg = 0;
529 for (j = y; j < (y + h); j += 16) {
28a76be8 530 for (i = x; i < (x + w); i += 16) {
5fafdf24 531 vs->send_hextile_tile(vs, i, j,
3512779a 532 MIN(16, x + w - i), MIN(16, y + h - j),
7eac3a87 533 last_bg, last_fg, &has_bg, &has_fg);
28a76be8 534 }
24236869 535 }
7eac3a87
AL
536 free(last_fg);
537 free(last_bg);
538
24236869
FB
539}
540
059cef40
AL
541static void vnc_zlib_init(VncState *vs)
542{
543 int i;
544 for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
545 vs->zlib_stream[i].opaque = NULL;
546}
547
548static void vnc_zlib_start(VncState *vs)
549{
550 buffer_reset(&vs->zlib);
551
552 // make the output buffer be the zlib buffer, so we can compress it later
553 vs->zlib_tmp = vs->output;
554 vs->output = vs->zlib;
555}
556
557static int vnc_zlib_stop(VncState *vs, int stream_id)
558{
559 z_streamp zstream = &vs->zlib_stream[stream_id];
560 int previous_out;
561
562 // switch back to normal output/zlib buffers
563 vs->zlib = vs->output;
564 vs->output = vs->zlib_tmp;
565
566 // compress the zlib buffer
567
568 // initialize the stream
569 // XXX need one stream per session
570 if (zstream->opaque != vs) {
571 int err;
572
573 VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
574 VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
575 zstream->zalloc = Z_NULL;
576 zstream->zfree = Z_NULL;
577
578 err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
579 MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
580
581 if (err != Z_OK) {
582 fprintf(stderr, "VNC: error initializing zlib\n");
583 return -1;
584 }
585
586 zstream->opaque = vs;
587 }
588
589 // XXX what to do if tight_compression changed in between?
590
591 // reserve memory in output buffer
592 buffer_reserve(&vs->output, vs->zlib.offset + 64);
593
594 // set pointers
595 zstream->next_in = vs->zlib.buffer;
596 zstream->avail_in = vs->zlib.offset;
597 zstream->next_out = vs->output.buffer + vs->output.offset;
598 zstream->avail_out = vs->output.capacity - vs->output.offset;
599 zstream->data_type = Z_BINARY;
600 previous_out = zstream->total_out;
601
602 // start encoding
603 if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
604 fprintf(stderr, "VNC: error during zlib compression\n");
605 return -1;
606 }
607
608 vs->output.offset = vs->output.capacity - zstream->avail_out;
609 return zstream->total_out - previous_out;
610}
611
612static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
613{
614 int old_offset, new_offset, bytes_written;
615
616 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
617
618 // remember where we put in the follow-up size
619 old_offset = vs->output.offset;
620 vnc_write_s32(vs, 0);
621
622 // compress the stream
623 vnc_zlib_start(vs);
624 send_framebuffer_update_raw(vs, x, y, w, h);
625 bytes_written = vnc_zlib_stop(vs, 0);
626
627 if (bytes_written == -1)
628 return;
629
630 // hack in the size
631 new_offset = vs->output.offset;
632 vs->output.offset = old_offset;
633 vnc_write_u32(vs, bytes_written);
634 vs->output.offset = new_offset;
635}
636
24236869
FB
637static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
638{
fb437313 639 switch(vs->vnc_encoding) {
28a76be8
AL
640 case VNC_ENCODING_ZLIB:
641 send_framebuffer_update_zlib(vs, x, y, w, h);
642 break;
643 case VNC_ENCODING_HEXTILE:
644 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
645 send_framebuffer_update_hextile(vs, x, y, w, h);
646 break;
647 default:
648 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
649 send_framebuffer_update_raw(vs, x, y, w, h);
650 break;
fb437313 651 }
24236869
FB
652}
653
753b4053 654static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
24236869 655{
c522d0e2 656 vs->force_update = 1;
24236869
FB
657 vnc_update_client(vs);
658
24236869
FB
659 vnc_write_u8(vs, 0); /* msg id */
660 vnc_write_u8(vs, 0);
661 vnc_write_u16(vs, 1); /* number of rects */
29fa4ed9 662 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
24236869
FB
663 vnc_write_u16(vs, src_x);
664 vnc_write_u16(vs, src_y);
665 vnc_flush(vs);
666}
667
753b4053
AL
668static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
669{
670 VncDisplay *vd = ds->opaque;
671 VncState *vs = vd->clients;
672 while (vs != NULL) {
673 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
674 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
675 else /* TODO */
676 vnc_update(vs, dst_x, dst_y, w, h);
677 vs = vs->next;
678 }
679}
680
6baebed7
AL
681static int find_and_clear_dirty_height(struct VncSurface *s,
682 int y, int last_x, int x)
24236869
FB
683{
684 int h;
685
6baebed7 686 for (h = 1; h < (s->ds->height - y) && h < 1; h++) {
28a76be8 687 int tmp_x;
6baebed7 688 if (!vnc_get_bit(s->dirty[y + h], last_x))
28a76be8
AL
689 break;
690 for (tmp_x = last_x; tmp_x < x; tmp_x++)
6baebed7 691 vnc_clear_bit(s->dirty[y + h], tmp_x);
24236869
FB
692 }
693
694 return h;
695}
696
697static void vnc_update_client(void *opaque)
698{
699 VncState *vs = opaque;
24236869 700 if (vs->need_update && vs->csock != -1) {
28a76be8 701 int y;
6baebed7
AL
702 uint8_t *guest_row;
703 uint8_t *server_row;
bee1b010 704 int cmp_bytes;
28a76be8
AL
705 uint32_t width_mask[VNC_DIRTY_WORDS];
706 int n_rectangles;
707 int saved_offset;
708 int has_dirty = 0;
24236869 709
c522d0e2
AL
710 if (vs->output.offset && !vs->audio_cap && !vs->force_update) {
711 /* kernel send buffers are full -> drop frames to throttle */
712 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
713 return;
714 }
715
a0ecfb73
AZ
716 vga_hw_update();
717
6baebed7
AL
718 /*
719 * Walk through the guest dirty map.
720 * Check and copy modified bits from guest to server surface.
721 * Update server dirty map.
722 */
6cec5487 723 vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
bee1b010 724 cmp_bytes = 16 * ds_get_bytes_per_pixel(vs->ds);
6baebed7
AL
725 guest_row = vs->guest.ds->data;
726 server_row = vs->server.ds->data;
727 for (y = 0; y < vs->guest.ds->height; y++) {
728 if (vnc_and_bits(vs->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
28a76be8 729 int x;
6baebed7
AL
730 uint8_t *guest_ptr;
731 uint8_t *server_ptr;
732
733 guest_ptr = guest_row;
734 server_ptr = server_row;
735
736 for (x = 0; x < vs->guest.ds->width;
737 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
738 if (!vnc_get_bit(vs->guest.dirty[y], (x / 16)))
739 continue;
740 vnc_clear_bit(vs->guest.dirty[y], (x / 16));
741 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
742 continue;
743 memcpy(server_ptr, guest_ptr, cmp_bytes);
744 vnc_set_bit(vs->server.dirty[y], (x / 16));
745 has_dirty++;
28a76be8
AL
746 }
747 }
6baebed7
AL
748 guest_row += ds_get_linesize(vs->ds);
749 server_row += ds_get_linesize(vs->ds);
28a76be8
AL
750 }
751
c522d0e2 752 if (!has_dirty && !vs->audio_cap && !vs->force_update) {
28a76be8
AL
753 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
754 return;
755 }
756
6baebed7
AL
757 /*
758 * Send screen updates to the vnc client using the server
759 * surface and server dirty map. guest surface updates
760 * happening in parallel don't disturb us, the next pass will
761 * send them to the client.
762 */
28a76be8
AL
763 n_rectangles = 0;
764 vnc_write_u8(vs, 0); /* msg id */
765 vnc_write_u8(vs, 0);
766 saved_offset = vs->output.offset;
767 vnc_write_u16(vs, 0);
768
6baebed7 769 for (y = 0; y < vs->server.ds->height; y++) {
28a76be8
AL
770 int x;
771 int last_x = -1;
6baebed7
AL
772 for (x = 0; x < vs->server.ds->width / 16; x++) {
773 if (vnc_get_bit(vs->server.dirty[y], x)) {
28a76be8
AL
774 if (last_x == -1) {
775 last_x = x;
776 }
6baebed7 777 vnc_clear_bit(vs->server.dirty[y], x);
28a76be8
AL
778 } else {
779 if (last_x != -1) {
6baebed7 780 int h = find_and_clear_dirty_height(&vs->server, y, last_x, x);
28a76be8
AL
781 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
782 n_rectangles++;
783 }
784 last_x = -1;
785 }
786 }
787 if (last_x != -1) {
6baebed7 788 int h = find_and_clear_dirty_height(&vs->server, y, last_x, x);
28a76be8
AL
789 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
790 n_rectangles++;
791 }
792 }
793 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
794 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
795 vnc_flush(vs);
c522d0e2 796 vs->force_update = 0;
24236869
FB
797
798 }
24236869 799
a0ecfb73
AZ
800 if (vs->csock != -1) {
801 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
24236869 802 }
24236869 803
24236869
FB
804}
805
429a8ed3 806/* audio */
807static void audio_capture_notify(void *opaque, audcnotification_e cmd)
808{
809 VncState *vs = opaque;
810
811 switch (cmd) {
812 case AUD_CNOTIFY_DISABLE:
813 vnc_write_u8(vs, 255);
814 vnc_write_u8(vs, 1);
815 vnc_write_u16(vs, 0);
816 vnc_flush(vs);
817 break;
818
819 case AUD_CNOTIFY_ENABLE:
820 vnc_write_u8(vs, 255);
821 vnc_write_u8(vs, 1);
822 vnc_write_u16(vs, 1);
823 vnc_flush(vs);
824 break;
825 }
826}
827
828static void audio_capture_destroy(void *opaque)
829{
830}
831
832static void audio_capture(void *opaque, void *buf, int size)
833{
834 VncState *vs = opaque;
835
836 vnc_write_u8(vs, 255);
837 vnc_write_u8(vs, 1);
838 vnc_write_u16(vs, 2);
839 vnc_write_u32(vs, size);
840 vnc_write(vs, buf, size);
841 vnc_flush(vs);
842}
843
844static void audio_add(VncState *vs)
845{
376253ec 846 Monitor *mon = cur_mon;
429a8ed3 847 struct audio_capture_ops ops;
848
849 if (vs->audio_cap) {
376253ec 850 monitor_printf(mon, "audio already running\n");
429a8ed3 851 return;
852 }
853
854 ops.notify = audio_capture_notify;
855 ops.destroy = audio_capture_destroy;
856 ops.capture = audio_capture;
857
858 vs->audio_cap = AUD_add_capture(NULL, &vs->as, &ops, vs);
859 if (!vs->audio_cap) {
376253ec 860 monitor_printf(mon, "Failed to add audio capture\n");
429a8ed3 861 }
862}
863
864static void audio_del(VncState *vs)
865{
866 if (vs->audio_cap) {
867 AUD_del_capture(vs->audio_cap, vs);
868 vs->audio_cap = NULL;
869 }
870}
871
2f9606b3
AL
872
873int vnc_client_io_error(VncState *vs, int ret, int last_errno)
24236869
FB
874{
875 if (ret == 0 || ret == -1) {
ea01e5fd
AZ
876 if (ret == -1) {
877 switch (last_errno) {
878 case EINTR:
879 case EAGAIN:
880#ifdef _WIN32
881 case WSAEWOULDBLOCK:
882#endif
883 return 0;
884 default:
885 break;
886 }
887 }
24236869 888
28a76be8
AL
889 VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
890 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
891 closesocket(vs->csock);
753b4053
AL
892 qemu_del_timer(vs->timer);
893 qemu_free_timer(vs->timer);
894 if (vs->input.buffer) qemu_free(vs->input.buffer);
895 if (vs->output.buffer) qemu_free(vs->output.buffer);
eb38c52c 896#ifdef CONFIG_VNC_TLS
28a76be8 897 vnc_tls_client_cleanup(vs);
8d5d2d4c 898#endif /* CONFIG_VNC_TLS */
2f9606b3
AL
899#ifdef CONFIG_VNC_SASL
900 vnc_sasl_client_cleanup(vs);
901#endif /* CONFIG_VNC_SASL */
429a8ed3 902 audio_del(vs);
753b4053
AL
903
904 VncState *p, *parent = NULL;
905 for (p = vs->vd->clients; p != NULL; p = p->next) {
906 if (p == vs) {
907 if (parent)
908 parent->next = p->next;
909 else
910 vs->vd->clients = p->next;
911 break;
912 }
913 parent = p;
914 }
915 if (!vs->vd->clients)
916 dcl->idle = 1;
917
89ee676e
GH
918 qemu_free(vs->server.ds->data);
919 qemu_free(vs->server.ds);
6baebed7 920 qemu_free(vs->guest.ds);
753b4053 921 qemu_free(vs);
6baebed7 922
28a76be8 923 return 0;
24236869
FB
924 }
925 return ret;
926}
927
5fb6c7a8
AL
928
929void vnc_client_error(VncState *vs)
24236869 930{
6ca957f0 931 vnc_client_io_error(vs, -1, EINVAL);
24236869
FB
932}
933
2f9606b3
AL
934
935/*
936 * Called to write a chunk of data to the client socket. The data may
937 * be the raw data, or may have already been encoded by SASL.
938 * The data will be written either straight onto the socket, or
939 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
940 *
941 * NB, it is theoretically possible to have 2 layers of encryption,
942 * both SASL, and this TLS layer. It is highly unlikely in practice
943 * though, since SASL encryption will typically be a no-op if TLS
944 * is active
945 *
946 * Returns the number of bytes written, which may be less than
947 * the requested 'datalen' if the socket would block. Returns
948 * -1 on error, and disconnects the client socket.
949 */
950long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
24236869 951{
ceb5caaf 952 long ret;
eb38c52c 953#ifdef CONFIG_VNC_TLS
5fb6c7a8 954 if (vs->tls.session) {
28a76be8
AL
955 ret = gnutls_write(vs->tls.session, data, datalen);
956 if (ret < 0) {
957 if (ret == GNUTLS_E_AGAIN)
958 errno = EAGAIN;
959 else
960 errno = EIO;
961 ret = -1;
962 }
8d5d2d4c
TS
963 } else
964#endif /* CONFIG_VNC_TLS */
28a76be8 965 ret = send(vs->csock, data, datalen, 0);
23decc87 966 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
2f9606b3
AL
967 return vnc_client_io_error(vs, ret, socket_error());
968}
969
970
971/*
972 * Called to write buffered data to the client socket, when not
973 * using any SASL SSF encryption layers. Will write as much data
974 * as possible without blocking. If all buffered data is written,
975 * will switch the FD poll() handler back to read monitoring.
976 *
977 * Returns the number of bytes written, which may be less than
978 * the buffered output data if the socket would block. Returns
979 * -1 on error, and disconnects the client socket.
980 */
981static long vnc_client_write_plain(VncState *vs)
982{
983 long ret;
984
985#ifdef CONFIG_VNC_SASL
23decc87 986 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
2f9606b3
AL
987 vs->output.buffer, vs->output.capacity, vs->output.offset,
988 vs->sasl.waitWriteSSF);
989
990 if (vs->sasl.conn &&
991 vs->sasl.runSSF &&
992 vs->sasl.waitWriteSSF) {
993 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
994 if (ret)
995 vs->sasl.waitWriteSSF -= ret;
996 } else
997#endif /* CONFIG_VNC_SASL */
998 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
24236869 999 if (!ret)
2f9606b3 1000 return 0;
24236869
FB
1001
1002 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1003 vs->output.offset -= ret;
1004
1005 if (vs->output.offset == 0) {
28a76be8 1006 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
24236869 1007 }
2f9606b3
AL
1008
1009 return ret;
1010}
1011
1012
1013/*
1014 * First function called whenever there is data to be written to
1015 * the client socket. Will delegate actual work according to whether
1016 * SASL SSF layers are enabled (thus requiring encryption calls)
1017 */
1018void vnc_client_write(void *opaque)
1019{
1020 long ret;
1021 VncState *vs = opaque;
1022
1023#ifdef CONFIG_VNC_SASL
1024 if (vs->sasl.conn &&
1025 vs->sasl.runSSF &&
1026 !vs->sasl.waitWriteSSF)
1027 ret = vnc_client_write_sasl(vs);
1028 else
1029#endif /* CONFIG_VNC_SASL */
1030 ret = vnc_client_write_plain(vs);
24236869
FB
1031}
1032
5fb6c7a8 1033void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
24236869
FB
1034{
1035 vs->read_handler = func;
1036 vs->read_handler_expect = expecting;
1037}
1038
2f9606b3
AL
1039
1040/*
1041 * Called to read a chunk of data from the client socket. The data may
1042 * be the raw data, or may need to be further decoded by SASL.
1043 * The data will be read either straight from to the socket, or
1044 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1045 *
1046 * NB, it is theoretically possible to have 2 layers of encryption,
1047 * both SASL, and this TLS layer. It is highly unlikely in practice
1048 * though, since SASL encryption will typically be a no-op if TLS
1049 * is active
1050 *
1051 * Returns the number of bytes read, which may be less than
1052 * the requested 'datalen' if the socket would block. Returns
1053 * -1 on error, and disconnects the client socket.
1054 */
1055long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
24236869 1056{
ceb5caaf 1057 long ret;
eb38c52c 1058#ifdef CONFIG_VNC_TLS
5fb6c7a8 1059 if (vs->tls.session) {
28a76be8
AL
1060 ret = gnutls_read(vs->tls.session, data, datalen);
1061 if (ret < 0) {
1062 if (ret == GNUTLS_E_AGAIN)
1063 errno = EAGAIN;
1064 else
1065 errno = EIO;
1066 ret = -1;
1067 }
8d5d2d4c
TS
1068 } else
1069#endif /* CONFIG_VNC_TLS */
28a76be8 1070 ret = recv(vs->csock, data, datalen, 0);
23decc87 1071 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
2f9606b3
AL
1072 return vnc_client_io_error(vs, ret, socket_error());
1073}
24236869 1074
2f9606b3
AL
1075
1076/*
1077 * Called to read data from the client socket to the input buffer,
1078 * when not using any SASL SSF encryption layers. Will read as much
1079 * data as possible without blocking.
1080 *
1081 * Returns the number of bytes read. Returns -1 on error, and
1082 * disconnects the client socket.
1083 */
1084static long vnc_client_read_plain(VncState *vs)
1085{
1086 int ret;
23decc87 1087 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
2f9606b3
AL
1088 vs->input.buffer, vs->input.capacity, vs->input.offset);
1089 buffer_reserve(&vs->input, 4096);
1090 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1091 if (!ret)
1092 return 0;
24236869 1093 vs->input.offset += ret;
2f9606b3
AL
1094 return ret;
1095}
1096
1097
1098/*
1099 * First function called whenever there is more data to be read from
1100 * the client socket. Will delegate actual work according to whether
1101 * SASL SSF layers are enabled (thus requiring decryption calls)
1102 */
1103void vnc_client_read(void *opaque)
1104{
1105 VncState *vs = opaque;
1106 long ret;
1107
1108#ifdef CONFIG_VNC_SASL
1109 if (vs->sasl.conn && vs->sasl.runSSF)
1110 ret = vnc_client_read_sasl(vs);
1111 else
1112#endif /* CONFIG_VNC_SASL */
1113 ret = vnc_client_read_plain(vs);
1114 if (!ret)
28a76be8 1115 return;
24236869
FB
1116
1117 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
28a76be8
AL
1118 size_t len = vs->read_handler_expect;
1119 int ret;
1120
1121 ret = vs->read_handler(vs, vs->input.buffer, len);
1122 if (vs->csock == -1)
1123 return;
1124
1125 if (!ret) {
1126 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1127 vs->input.offset -= len;
1128 } else {
1129 vs->read_handler_expect = ret;
1130 }
24236869
FB
1131 }
1132}
1133
5fb6c7a8 1134void vnc_write(VncState *vs, const void *data, size_t len)
24236869
FB
1135{
1136 buffer_reserve(&vs->output, len);
1137
1138 if (buffer_empty(&vs->output)) {
28a76be8 1139 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
24236869
FB
1140 }
1141
1142 buffer_append(&vs->output, data, len);
1143}
1144
5fb6c7a8 1145void vnc_write_s32(VncState *vs, int32_t value)
24236869
FB
1146{
1147 vnc_write_u32(vs, *(uint32_t *)&value);
1148}
1149
5fb6c7a8 1150void vnc_write_u32(VncState *vs, uint32_t value)
24236869
FB
1151{
1152 uint8_t buf[4];
1153
1154 buf[0] = (value >> 24) & 0xFF;
1155 buf[1] = (value >> 16) & 0xFF;
1156 buf[2] = (value >> 8) & 0xFF;
1157 buf[3] = value & 0xFF;
1158
1159 vnc_write(vs, buf, 4);
1160}
1161
5fb6c7a8 1162void vnc_write_u16(VncState *vs, uint16_t value)
24236869 1163{
64f5a135 1164 uint8_t buf[2];
24236869
FB
1165
1166 buf[0] = (value >> 8) & 0xFF;
1167 buf[1] = value & 0xFF;
1168
1169 vnc_write(vs, buf, 2);
1170}
1171
5fb6c7a8 1172void vnc_write_u8(VncState *vs, uint8_t value)
24236869
FB
1173{
1174 vnc_write(vs, (char *)&value, 1);
1175}
1176
5fb6c7a8 1177void vnc_flush(VncState *vs)
24236869
FB
1178{
1179 if (vs->output.offset)
28a76be8 1180 vnc_client_write(vs);
24236869
FB
1181}
1182
5fb6c7a8 1183uint8_t read_u8(uint8_t *data, size_t offset)
24236869
FB
1184{
1185 return data[offset];
1186}
1187
5fb6c7a8 1188uint16_t read_u16(uint8_t *data, size_t offset)
24236869
FB
1189{
1190 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1191}
1192
5fb6c7a8 1193int32_t read_s32(uint8_t *data, size_t offset)
24236869
FB
1194{
1195 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
28a76be8 1196 (data[offset + 2] << 8) | data[offset + 3]);
24236869
FB
1197}
1198
5fb6c7a8 1199uint32_t read_u32(uint8_t *data, size_t offset)
24236869
FB
1200{
1201 return ((data[offset] << 24) | (data[offset + 1] << 16) |
28a76be8 1202 (data[offset + 2] << 8) | data[offset + 3]);
24236869
FB
1203}
1204
60fe76f3 1205static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
24236869
FB
1206{
1207}
1208
564c337e
FB
1209static void check_pointer_type_change(VncState *vs, int absolute)
1210{
29fa4ed9 1211 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
28a76be8
AL
1212 vnc_write_u8(vs, 0);
1213 vnc_write_u8(vs, 0);
1214 vnc_write_u16(vs, 1);
1215 vnc_framebuffer_update(vs, absolute, 0,
1216 ds_get_width(vs->ds), ds_get_height(vs->ds),
29fa4ed9 1217 VNC_ENCODING_POINTER_TYPE_CHANGE);
28a76be8 1218 vnc_flush(vs);
564c337e
FB
1219 }
1220 vs->absolute = absolute;
1221}
1222
24236869
FB
1223static void pointer_event(VncState *vs, int button_mask, int x, int y)
1224{
1225 int buttons = 0;
1226 int dz = 0;
1227
1228 if (button_mask & 0x01)
28a76be8 1229 buttons |= MOUSE_EVENT_LBUTTON;
24236869 1230 if (button_mask & 0x02)
28a76be8 1231 buttons |= MOUSE_EVENT_MBUTTON;
24236869 1232 if (button_mask & 0x04)
28a76be8 1233 buttons |= MOUSE_EVENT_RBUTTON;
24236869 1234 if (button_mask & 0x08)
28a76be8 1235 dz = -1;
24236869 1236 if (button_mask & 0x10)
28a76be8 1237 dz = 1;
564c337e
FB
1238
1239 if (vs->absolute) {
28a76be8
AL
1240 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1241 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1242 dz, buttons);
29fa4ed9 1243 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
28a76be8
AL
1244 x -= 0x7FFF;
1245 y -= 0x7FFF;
24236869 1246
28a76be8 1247 kbd_mouse_event(x, y, dz, buttons);
564c337e 1248 } else {
28a76be8
AL
1249 if (vs->last_x != -1)
1250 kbd_mouse_event(x - vs->last_x,
1251 y - vs->last_y,
1252 dz, buttons);
1253 vs->last_x = x;
1254 vs->last_y = y;
24236869 1255 }
564c337e
FB
1256
1257 check_pointer_type_change(vs, kbd_mouse_is_absolute());
24236869
FB
1258}
1259
64f5a135
FB
1260static void reset_keys(VncState *vs)
1261{
1262 int i;
1263 for(i = 0; i < 256; i++) {
1264 if (vs->modifiers_state[i]) {
1265 if (i & 0x80)
1266 kbd_put_keycode(0xe0);
1267 kbd_put_keycode(i | 0x80);
1268 vs->modifiers_state[i] = 0;
1269 }
1270 }
1271}
1272
a528b80c
AZ
1273static void press_key(VncState *vs, int keysym)
1274{
753b4053
AL
1275 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1276 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
a528b80c
AZ
1277}
1278
9ca313aa 1279static void do_key_event(VncState *vs, int down, int keycode, int sym)
24236869 1280{
64f5a135
FB
1281 /* QEMU console switch */
1282 switch(keycode) {
1283 case 0x2a: /* Left Shift */
1284 case 0x36: /* Right Shift */
1285 case 0x1d: /* Left CTRL */
1286 case 0x9d: /* Right CTRL */
1287 case 0x38: /* Left ALT */
1288 case 0xb8: /* Right ALT */
1289 if (down)
1290 vs->modifiers_state[keycode] = 1;
1291 else
1292 vs->modifiers_state[keycode] = 0;
1293 break;
5fafdf24 1294 case 0x02 ... 0x0a: /* '1' to '9' keys */
64f5a135
FB
1295 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1296 /* Reset the modifiers sent to the current console */
1297 reset_keys(vs);
1298 console_select(keycode - 0x02);
1299 return;
1300 }
1301 break;
28a76be8
AL
1302 case 0x3a: /* CapsLock */
1303 case 0x45: /* NumLock */
a528b80c
AZ
1304 if (!down)
1305 vs->modifiers_state[keycode] ^= 1;
1306 break;
1307 }
1308
753b4053 1309 if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
a528b80c
AZ
1310 /* If the numlock state needs to change then simulate an additional
1311 keypress before sending this one. This will happen if the user
1312 toggles numlock away from the VNC window.
1313 */
753b4053 1314 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
a528b80c
AZ
1315 if (!vs->modifiers_state[0x45]) {
1316 vs->modifiers_state[0x45] = 1;
1317 press_key(vs, 0xff7f);
1318 }
1319 } else {
1320 if (vs->modifiers_state[0x45]) {
1321 vs->modifiers_state[0x45] = 0;
1322 press_key(vs, 0xff7f);
1323 }
1324 }
64f5a135 1325 }
24236869 1326
64f5a135
FB
1327 if (is_graphic_console()) {
1328 if (keycode & 0x80)
1329 kbd_put_keycode(0xe0);
1330 if (down)
1331 kbd_put_keycode(keycode & 0x7f);
1332 else
1333 kbd_put_keycode(keycode | 0x80);
1334 } else {
1335 /* QEMU console emulation */
1336 if (down) {
1337 switch (keycode) {
1338 case 0x2a: /* Left Shift */
1339 case 0x36: /* Right Shift */
1340 case 0x1d: /* Left CTRL */
1341 case 0x9d: /* Right CTRL */
1342 case 0x38: /* Left ALT */
1343 case 0xb8: /* Right ALT */
1344 break;
1345 case 0xc8:
0fc8e0ec 1346 case 0x48:
64f5a135
FB
1347 kbd_put_keysym(QEMU_KEY_UP);
1348 break;
1349 case 0xd0:
0fc8e0ec 1350 case 0x50:
64f5a135
FB
1351 kbd_put_keysym(QEMU_KEY_DOWN);
1352 break;
1353 case 0xcb:
0fc8e0ec 1354 case 0x4b:
64f5a135
FB
1355 kbd_put_keysym(QEMU_KEY_LEFT);
1356 break;
1357 case 0xcd:
0fc8e0ec 1358 case 0x4d:
64f5a135
FB
1359 kbd_put_keysym(QEMU_KEY_RIGHT);
1360 break;
1361 case 0xd3:
0fc8e0ec 1362 case 0x53:
64f5a135
FB
1363 kbd_put_keysym(QEMU_KEY_DELETE);
1364 break;
1365 case 0xc7:
0fc8e0ec 1366 case 0x47:
64f5a135
FB
1367 kbd_put_keysym(QEMU_KEY_HOME);
1368 break;
1369 case 0xcf:
0fc8e0ec 1370 case 0x4f:
64f5a135
FB
1371 kbd_put_keysym(QEMU_KEY_END);
1372 break;
1373 case 0xc9:
0fc8e0ec 1374 case 0x49:
64f5a135
FB
1375 kbd_put_keysym(QEMU_KEY_PAGEUP);
1376 break;
1377 case 0xd1:
0fc8e0ec 1378 case 0x51:
64f5a135
FB
1379 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1380 break;
1381 default:
1382 kbd_put_keysym(sym);
1383 break;
1384 }
1385 }
1386 }
24236869
FB
1387}
1388
bdbd7676
FB
1389static void key_event(VncState *vs, int down, uint32_t sym)
1390{
9ca313aa
AL
1391 int keycode;
1392
a528b80c 1393 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
28a76be8 1394 sym = sym - 'A' + 'a';
9ca313aa 1395
753b4053 1396 keycode = keysym2scancode(vs->vd->kbd_layout, sym & 0xFFFF);
9ca313aa
AL
1397 do_key_event(vs, down, keycode, sym);
1398}
1399
1400static void ext_key_event(VncState *vs, int down,
1401 uint32_t sym, uint16_t keycode)
1402{
1403 /* if the user specifies a keyboard layout, always use it */
1404 if (keyboard_layout)
1405 key_event(vs, down, sym);
1406 else
1407 do_key_event(vs, down, keycode, sym);
bdbd7676
FB
1408}
1409
24236869 1410static void framebuffer_update_request(VncState *vs, int incremental,
28a76be8
AL
1411 int x_position, int y_position,
1412 int w, int h)
24236869 1413{
0e1f5a0c
AL
1414 if (x_position > ds_get_width(vs->ds))
1415 x_position = ds_get_width(vs->ds);
1416 if (y_position > ds_get_height(vs->ds))
1417 y_position = ds_get_height(vs->ds);
1418 if (x_position + w >= ds_get_width(vs->ds))
1419 w = ds_get_width(vs->ds) - x_position;
1420 if (y_position + h >= ds_get_height(vs->ds))
1421 h = ds_get_height(vs->ds) - y_position;
cf2d385c 1422
24236869
FB
1423 int i;
1424 vs->need_update = 1;
c522d0e2 1425 vs->force_update = 1;
24236869 1426 if (!incremental) {
28a76be8 1427 for (i = 0; i < h; i++) {
6baebed7
AL
1428 vnc_set_bits(vs->guest.dirty[y_position + i],
1429 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1430 vnc_set_bits(vs->server.dirty[y_position + i],
0e1f5a0c 1431 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
28a76be8 1432 }
24236869
FB
1433 }
1434}
1435
9ca313aa
AL
1436static void send_ext_key_event_ack(VncState *vs)
1437{
1438 vnc_write_u8(vs, 0);
1439 vnc_write_u8(vs, 0);
1440 vnc_write_u16(vs, 1);
29fa4ed9
AL
1441 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1442 VNC_ENCODING_EXT_KEY_EVENT);
9ca313aa
AL
1443 vnc_flush(vs);
1444}
1445
429a8ed3 1446static void send_ext_audio_ack(VncState *vs)
1447{
1448 vnc_write_u8(vs, 0);
1449 vnc_write_u8(vs, 0);
1450 vnc_write_u16(vs, 1);
29fa4ed9
AL
1451 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1452 VNC_ENCODING_AUDIO);
429a8ed3 1453 vnc_flush(vs);
1454}
1455
24236869
FB
1456static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1457{
1458 int i;
29fa4ed9 1459 unsigned int enc = 0;
24236869 1460
059cef40 1461 vnc_zlib_init(vs);
29fa4ed9 1462 vs->features = 0;
fb437313
AL
1463 vs->vnc_encoding = 0;
1464 vs->tight_compression = 9;
1465 vs->tight_quality = 9;
564c337e 1466 vs->absolute = -1;
24236869
FB
1467
1468 for (i = n_encodings - 1; i >= 0; i--) {
29fa4ed9
AL
1469 enc = encodings[i];
1470 switch (enc) {
1471 case VNC_ENCODING_RAW:
fb437313 1472 vs->vnc_encoding = enc;
29fa4ed9
AL
1473 break;
1474 case VNC_ENCODING_COPYRECT:
753b4053 1475 vs->features |= VNC_FEATURE_COPYRECT_MASK;
29fa4ed9
AL
1476 break;
1477 case VNC_ENCODING_HEXTILE:
1478 vs->features |= VNC_FEATURE_HEXTILE_MASK;
fb437313 1479 vs->vnc_encoding = enc;
29fa4ed9 1480 break;
059cef40
AL
1481 case VNC_ENCODING_ZLIB:
1482 vs->features |= VNC_FEATURE_ZLIB_MASK;
1483 vs->vnc_encoding = enc;
1484 break;
29fa4ed9
AL
1485 case VNC_ENCODING_DESKTOPRESIZE:
1486 vs->features |= VNC_FEATURE_RESIZE_MASK;
1487 break;
1488 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1489 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1490 break;
1491 case VNC_ENCODING_EXT_KEY_EVENT:
9ca313aa
AL
1492 send_ext_key_event_ack(vs);
1493 break;
29fa4ed9 1494 case VNC_ENCODING_AUDIO:
429a8ed3 1495 send_ext_audio_ack(vs);
1496 break;
29fa4ed9
AL
1497 case VNC_ENCODING_WMVi:
1498 vs->features |= VNC_FEATURE_WMVI_MASK;
ca4cca4d 1499 break;
fb437313
AL
1500 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1501 vs->tight_compression = (enc & 0x0F);
1502 break;
1503 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1504 vs->tight_quality = (enc & 0x0F);
1505 break;
29fa4ed9
AL
1506 default:
1507 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1508 break;
1509 }
24236869 1510 }
564c337e
FB
1511
1512 check_pointer_type_change(vs, kbd_mouse_is_absolute());
24236869
FB
1513}
1514
6cec5487
AL
1515static void set_pixel_conversion(VncState *vs)
1516{
1517 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1518 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1519 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1520 vs->write_pixels = vnc_write_pixels_copy;
1521 switch (vs->ds->surface->pf.bits_per_pixel) {
1522 case 8:
1523 vs->send_hextile_tile = send_hextile_tile_8;
1524 break;
1525 case 16:
1526 vs->send_hextile_tile = send_hextile_tile_16;
1527 break;
1528 case 32:
1529 vs->send_hextile_tile = send_hextile_tile_32;
1530 break;
1531 }
1532 } else {
1533 vs->write_pixels = vnc_write_pixels_generic;
1534 switch (vs->ds->surface->pf.bits_per_pixel) {
1535 case 8:
1536 vs->send_hextile_tile = send_hextile_tile_generic_8;
1537 break;
1538 case 16:
1539 vs->send_hextile_tile = send_hextile_tile_generic_16;
1540 break;
1541 case 32:
1542 vs->send_hextile_tile = send_hextile_tile_generic_32;
1543 break;
1544 }
1545 }
1546}
1547
24236869 1548static void set_pixel_format(VncState *vs,
28a76be8
AL
1549 int bits_per_pixel, int depth,
1550 int big_endian_flag, int true_color_flag,
1551 int red_max, int green_max, int blue_max,
1552 int red_shift, int green_shift, int blue_shift)
24236869 1553{
3512779a 1554 if (!true_color_flag) {
28a76be8 1555 vnc_client_error(vs);
3512779a
FB
1556 return;
1557 }
24236869 1558
6baebed7 1559 vs->clientds = *(vs->guest.ds);
6cec5487 1560 vs->clientds.pf.rmax = red_max;
90a1e3c0 1561 count_bits(vs->clientds.pf.rbits, red_max);
6cec5487
AL
1562 vs->clientds.pf.rshift = red_shift;
1563 vs->clientds.pf.rmask = red_max << red_shift;
1564 vs->clientds.pf.gmax = green_max;
90a1e3c0 1565 count_bits(vs->clientds.pf.gbits, green_max);
6cec5487
AL
1566 vs->clientds.pf.gshift = green_shift;
1567 vs->clientds.pf.gmask = green_max << green_shift;
1568 vs->clientds.pf.bmax = blue_max;
90a1e3c0 1569 count_bits(vs->clientds.pf.bbits, blue_max);
6cec5487
AL
1570 vs->clientds.pf.bshift = blue_shift;
1571 vs->clientds.pf.bmask = blue_max << blue_shift;
1572 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1573 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1574 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1575 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1576
1577 set_pixel_conversion(vs);
24236869
FB
1578
1579 vga_hw_invalidate();
1580 vga_hw_update();
1581}
1582
ca4cca4d
AL
1583static void pixel_format_message (VncState *vs) {
1584 char pad[3] = { 0, 0, 0 };
1585
6cec5487
AL
1586 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1587 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
ca4cca4d
AL
1588
1589#ifdef WORDS_BIGENDIAN
1590 vnc_write_u8(vs, 1); /* big-endian-flag */
1591#else
1592 vnc_write_u8(vs, 0); /* big-endian-flag */
1593#endif
1594 vnc_write_u8(vs, 1); /* true-color-flag */
6cec5487
AL
1595 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1596 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1597 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1598 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1599 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1600 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1601 if (vs->ds->surface->pf.bits_per_pixel == 32)
ca4cca4d 1602 vs->send_hextile_tile = send_hextile_tile_32;
6cec5487 1603 else if (vs->ds->surface->pf.bits_per_pixel == 16)
ca4cca4d 1604 vs->send_hextile_tile = send_hextile_tile_16;
6cec5487 1605 else if (vs->ds->surface->pf.bits_per_pixel == 8)
ca4cca4d 1606 vs->send_hextile_tile = send_hextile_tile_8;
6cec5487 1607 vs->clientds = *(vs->ds->surface);
3cded540 1608 vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
ca4cca4d
AL
1609 vs->write_pixels = vnc_write_pixels_copy;
1610
1611 vnc_write(vs, pad, 3); /* padding */
1612}
1613
7d957bd8
AL
1614static void vnc_dpy_setdata(DisplayState *ds)
1615{
1616 /* We don't have to do anything */
1617}
1618
753b4053 1619static void vnc_colordepth(VncState *vs)
7eac3a87 1620{
753b4053 1621 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
ca4cca4d
AL
1622 /* Sending a WMVi message to notify the client*/
1623 vnc_write_u8(vs, 0); /* msg id */
1624 vnc_write_u8(vs, 0);
1625 vnc_write_u16(vs, 1); /* number of rects */
753b4053
AL
1626 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1627 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
ca4cca4d
AL
1628 pixel_format_message(vs);
1629 vnc_flush(vs);
7eac3a87 1630 } else {
6cec5487 1631 set_pixel_conversion(vs);
7eac3a87
AL
1632 }
1633}
1634
60fe76f3 1635static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
24236869
FB
1636{
1637 int i;
1638 uint16_t limit;
1639
1640 switch (data[0]) {
1641 case 0:
28a76be8
AL
1642 if (len == 1)
1643 return 20;
1644
1645 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1646 read_u8(data, 6), read_u8(data, 7),
1647 read_u16(data, 8), read_u16(data, 10),
1648 read_u16(data, 12), read_u8(data, 14),
1649 read_u8(data, 15), read_u8(data, 16));
1650 break;
24236869 1651 case 2:
28a76be8
AL
1652 if (len == 1)
1653 return 4;
24236869 1654
28a76be8 1655 if (len == 4) {
69dd5c9f
AL
1656 limit = read_u16(data, 2);
1657 if (limit > 0)
1658 return 4 + (limit * 4);
1659 } else
1660 limit = read_u16(data, 2);
24236869 1661
28a76be8
AL
1662 for (i = 0; i < limit; i++) {
1663 int32_t val = read_s32(data, 4 + (i * 4));
1664 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1665 }
24236869 1666
28a76be8
AL
1667 set_encodings(vs, (int32_t *)(data + 4), limit);
1668 break;
24236869 1669 case 3:
28a76be8
AL
1670 if (len == 1)
1671 return 10;
24236869 1672
28a76be8
AL
1673 framebuffer_update_request(vs,
1674 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1675 read_u16(data, 6), read_u16(data, 8));
1676 break;
24236869 1677 case 4:
28a76be8
AL
1678 if (len == 1)
1679 return 8;
24236869 1680
28a76be8
AL
1681 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1682 break;
24236869 1683 case 5:
28a76be8
AL
1684 if (len == 1)
1685 return 6;
24236869 1686
28a76be8
AL
1687 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1688 break;
24236869 1689 case 6:
28a76be8
AL
1690 if (len == 1)
1691 return 8;
24236869 1692
28a76be8 1693 if (len == 8) {
baa7666c
TS
1694 uint32_t dlen = read_u32(data, 4);
1695 if (dlen > 0)
1696 return 8 + dlen;
1697 }
24236869 1698
28a76be8
AL
1699 client_cut_text(vs, read_u32(data, 4), data + 8);
1700 break;
9ca313aa
AL
1701 case 255:
1702 if (len == 1)
1703 return 2;
1704
1705 switch (read_u8(data, 1)) {
1706 case 0:
1707 if (len == 2)
1708 return 12;
1709
1710 ext_key_event(vs, read_u16(data, 2),
1711 read_u32(data, 4), read_u32(data, 8));
1712 break;
429a8ed3 1713 case 1:
1714 if (len == 2)
1715 return 4;
1716
1717 switch (read_u16 (data, 2)) {
1718 case 0:
1719 audio_add(vs);
1720 break;
1721 case 1:
1722 audio_del(vs);
1723 break;
1724 case 2:
1725 if (len == 4)
1726 return 10;
1727 switch (read_u8(data, 4)) {
1728 case 0: vs->as.fmt = AUD_FMT_U8; break;
1729 case 1: vs->as.fmt = AUD_FMT_S8; break;
1730 case 2: vs->as.fmt = AUD_FMT_U16; break;
1731 case 3: vs->as.fmt = AUD_FMT_S16; break;
1732 case 4: vs->as.fmt = AUD_FMT_U32; break;
1733 case 5: vs->as.fmt = AUD_FMT_S32; break;
1734 default:
1735 printf("Invalid audio format %d\n", read_u8(data, 4));
1736 vnc_client_error(vs);
1737 break;
1738 }
1739 vs->as.nchannels = read_u8(data, 5);
1740 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1741 printf("Invalid audio channel coount %d\n",
1742 read_u8(data, 5));
1743 vnc_client_error(vs);
1744 break;
1745 }
1746 vs->as.freq = read_u32(data, 6);
1747 break;
1748 default:
1749 printf ("Invalid audio message %d\n", read_u8(data, 4));
1750 vnc_client_error(vs);
1751 break;
1752 }
1753 break;
1754
9ca313aa
AL
1755 default:
1756 printf("Msg: %d\n", read_u16(data, 0));
1757 vnc_client_error(vs);
1758 break;
1759 }
1760 break;
24236869 1761 default:
28a76be8
AL
1762 printf("Msg: %d\n", data[0]);
1763 vnc_client_error(vs);
1764 break;
24236869 1765 }
5fafdf24 1766
24236869
FB
1767 vnc_read_when(vs, protocol_client_msg, 1);
1768 return 0;
1769}
1770
60fe76f3 1771static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
24236869 1772{
c35734b2
TS
1773 char buf[1024];
1774 int size;
24236869 1775
0e1f5a0c
AL
1776 vnc_write_u16(vs, ds_get_width(vs->ds));
1777 vnc_write_u16(vs, ds_get_height(vs->ds));
24236869 1778
ca4cca4d 1779 pixel_format_message(vs);
24236869 1780
c35734b2
TS
1781 if (qemu_name)
1782 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1783 else
1784 size = snprintf(buf, sizeof(buf), "QEMU");
1785
1786 vnc_write_u32(vs, size);
1787 vnc_write(vs, buf, size);
24236869
FB
1788 vnc_flush(vs);
1789
1790 vnc_read_when(vs, protocol_client_msg, 1);
1791
1792 return 0;
1793}
1794
5fb6c7a8
AL
1795void start_client_init(VncState *vs)
1796{
1797 vnc_read_when(vs, protocol_client_init, 1);
1798}
1799
70848515
TS
1800static void make_challenge(VncState *vs)
1801{
1802 int i;
1803
1804 srand(time(NULL)+getpid()+getpid()*987654+rand());
1805
1806 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1807 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1808}
1809
60fe76f3 1810static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
70848515 1811{
60fe76f3 1812 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
70848515 1813 int i, j, pwlen;
60fe76f3 1814 unsigned char key[8];
70848515 1815
753b4053 1816 if (!vs->vd->password || !vs->vd->password[0]) {
28a76be8
AL
1817 VNC_DEBUG("No password configured on server");
1818 vnc_write_u32(vs, 1); /* Reject auth */
1819 if (vs->minor >= 8) {
1820 static const char err[] = "Authentication failed";
1821 vnc_write_u32(vs, sizeof(err));
1822 vnc_write(vs, err, sizeof(err));
1823 }
1824 vnc_flush(vs);
1825 vnc_client_error(vs);
1826 return 0;
70848515
TS
1827 }
1828
1829 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1830
1831 /* Calculate the expected challenge response */
753b4053 1832 pwlen = strlen(vs->vd->password);
70848515 1833 for (i=0; i<sizeof(key); i++)
753b4053 1834 key[i] = i<pwlen ? vs->vd->password[i] : 0;
70848515
TS
1835 deskey(key, EN0);
1836 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1837 des(response+j, response+j);
1838
1839 /* Compare expected vs actual challenge response */
1840 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
28a76be8
AL
1841 VNC_DEBUG("Client challenge reponse did not match\n");
1842 vnc_write_u32(vs, 1); /* Reject auth */
1843 if (vs->minor >= 8) {
1844 static const char err[] = "Authentication failed";
1845 vnc_write_u32(vs, sizeof(err));
1846 vnc_write(vs, err, sizeof(err));
1847 }
1848 vnc_flush(vs);
1849 vnc_client_error(vs);
70848515 1850 } else {
28a76be8
AL
1851 VNC_DEBUG("Accepting VNC challenge response\n");
1852 vnc_write_u32(vs, 0); /* Accept auth */
1853 vnc_flush(vs);
70848515 1854
5fb6c7a8 1855 start_client_init(vs);
70848515
TS
1856 }
1857 return 0;
1858}
1859
5fb6c7a8 1860void start_auth_vnc(VncState *vs)
70848515
TS
1861{
1862 make_challenge(vs);
1863 /* Send client a 'random' challenge */
1864 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1865 vnc_flush(vs);
1866
1867 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
469b15c6
TS
1868}
1869
1870
60fe76f3 1871static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
70848515
TS
1872{
1873 /* We only advertise 1 auth scheme at a time, so client
1874 * must pick the one we sent. Verify this */
753b4053 1875 if (data[0] != vs->vd->auth) { /* Reject auth */
1263b7d6 1876 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
70848515
TS
1877 vnc_write_u32(vs, 1);
1878 if (vs->minor >= 8) {
1879 static const char err[] = "Authentication failed";
1880 vnc_write_u32(vs, sizeof(err));
1881 vnc_write(vs, err, sizeof(err));
1882 }
1883 vnc_client_error(vs);
1884 } else { /* Accept requested auth */
1885 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
753b4053 1886 switch (vs->vd->auth) {
70848515
TS
1887 case VNC_AUTH_NONE:
1888 VNC_DEBUG("Accept auth none\n");
a26c97ad
AZ
1889 if (vs->minor >= 8) {
1890 vnc_write_u32(vs, 0); /* Accept auth completion */
1891 vnc_flush(vs);
1892 }
5fb6c7a8 1893 start_client_init(vs);
70848515
TS
1894 break;
1895
1896 case VNC_AUTH_VNC:
1897 VNC_DEBUG("Start VNC auth\n");
5fb6c7a8
AL
1898 start_auth_vnc(vs);
1899 break;
70848515 1900
eb38c52c 1901#ifdef CONFIG_VNC_TLS
8d5d2d4c
TS
1902 case VNC_AUTH_VENCRYPT:
1903 VNC_DEBUG("Accept VeNCrypt auth\n");;
5fb6c7a8
AL
1904 start_auth_vencrypt(vs);
1905 break;
8d5d2d4c
TS
1906#endif /* CONFIG_VNC_TLS */
1907
2f9606b3
AL
1908#ifdef CONFIG_VNC_SASL
1909 case VNC_AUTH_SASL:
1910 VNC_DEBUG("Accept SASL auth\n");
1911 start_auth_sasl(vs);
1912 break;
1913#endif /* CONFIG_VNC_SASL */
1914
70848515 1915 default: /* Should not be possible, but just in case */
1263b7d6 1916 VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
70848515
TS
1917 vnc_write_u8(vs, 1);
1918 if (vs->minor >= 8) {
1919 static const char err[] = "Authentication failed";
1920 vnc_write_u32(vs, sizeof(err));
1921 vnc_write(vs, err, sizeof(err));
1922 }
1923 vnc_client_error(vs);
1924 }
1925 }
1926 return 0;
1927}
1928
60fe76f3 1929static int protocol_version(VncState *vs, uint8_t *version, size_t len)
24236869
FB
1930{
1931 char local[13];
24236869
FB
1932
1933 memcpy(local, version, 12);
1934 local[12] = 0;
1935
70848515 1936 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
28a76be8
AL
1937 VNC_DEBUG("Malformed protocol version %s\n", local);
1938 vnc_client_error(vs);
1939 return 0;
24236869 1940 }
70848515
TS
1941 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
1942 if (vs->major != 3 ||
28a76be8
AL
1943 (vs->minor != 3 &&
1944 vs->minor != 4 &&
1945 vs->minor != 5 &&
1946 vs->minor != 7 &&
1947 vs->minor != 8)) {
1948 VNC_DEBUG("Unsupported client version\n");
1949 vnc_write_u32(vs, VNC_AUTH_INVALID);
1950 vnc_flush(vs);
1951 vnc_client_error(vs);
1952 return 0;
70848515 1953 }
b0566f4f 1954 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
70848515
TS
1955 * as equivalent to v3.3 by servers
1956 */
b0566f4f 1957 if (vs->minor == 4 || vs->minor == 5)
28a76be8 1958 vs->minor = 3;
70848515
TS
1959
1960 if (vs->minor == 3) {
28a76be8 1961 if (vs->vd->auth == VNC_AUTH_NONE) {
70848515 1962 VNC_DEBUG("Tell client auth none\n");
753b4053 1963 vnc_write_u32(vs, vs->vd->auth);
70848515 1964 vnc_flush(vs);
28a76be8 1965 start_client_init(vs);
753b4053 1966 } else if (vs->vd->auth == VNC_AUTH_VNC) {
70848515 1967 VNC_DEBUG("Tell client VNC auth\n");
753b4053 1968 vnc_write_u32(vs, vs->vd->auth);
70848515
TS
1969 vnc_flush(vs);
1970 start_auth_vnc(vs);
1971 } else {
753b4053 1972 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
70848515
TS
1973 vnc_write_u32(vs, VNC_AUTH_INVALID);
1974 vnc_flush(vs);
1975 vnc_client_error(vs);
1976 }
1977 } else {
28a76be8
AL
1978 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
1979 vnc_write_u8(vs, 1); /* num auth */
1980 vnc_write_u8(vs, vs->vd->auth);
1981 vnc_read_when(vs, protocol_client_auth, 1);
1982 vnc_flush(vs);
70848515 1983 }
24236869
FB
1984
1985 return 0;
1986}
1987
753b4053 1988static void vnc_connect(VncDisplay *vd, int csock)
3aa3eea3 1989{
753b4053
AL
1990 VncState *vs = qemu_mallocz(sizeof(VncState));
1991 vs->csock = csock;
1992
1993 VNC_DEBUG("New client on socket %d\n", csock);
7d957bd8 1994 dcl->idle = 0;
3aa3eea3
AZ
1995 socket_set_nonblock(vs->csock);
1996 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
753b4053
AL
1997
1998 vs->vd = vd;
1999 vs->ds = vd->ds;
2000 vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
2001 vs->last_x = -1;
2002 vs->last_y = -1;
2003
2004 vs->as.freq = 44100;
2005 vs->as.nchannels = 2;
2006 vs->as.fmt = AUD_FMT_S16;
2007 vs->as.endianness = 0;
2008
2009 vnc_resize(vs);
3aa3eea3
AZ
2010 vnc_write(vs, "RFB 003.008\n", 12);
2011 vnc_flush(vs);
2012 vnc_read_when(vs, protocol_version, 12);
3aa3eea3 2013 vnc_update_client(vs);
53762ddb 2014 reset_keys(vs);
753b4053
AL
2015
2016 vs->next = vd->clients;
2017 vd->clients = vs;
3aa3eea3
AZ
2018}
2019
24236869
FB
2020static void vnc_listen_read(void *opaque)
2021{
753b4053 2022 VncDisplay *vs = opaque;
24236869
FB
2023 struct sockaddr_in addr;
2024 socklen_t addrlen = sizeof(addr);
2025
9f60ad50
AZ
2026 /* Catch-up */
2027 vga_hw_update();
2028
753b4053
AL
2029 int csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2030 if (csock != -1) {
2031 vnc_connect(vs, csock);
24236869
FB
2032 }
2033}
2034
71cab5ca 2035void vnc_display_init(DisplayState *ds)
24236869 2036{
753b4053 2037 VncDisplay *vs;
24236869
FB
2038
2039 vs = qemu_mallocz(sizeof(VncState));
7d957bd8 2040 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
24236869
FB
2041
2042 ds->opaque = vs;
7d957bd8 2043 dcl->idle = 1;
753b4053 2044 vnc_display = vs;
24236869
FB
2045
2046 vs->lsock = -1;
24236869
FB
2047
2048 vs->ds = ds;
2049
9ca313aa 2050 if (keyboard_layout)
0483755a 2051 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
9ca313aa 2052 else
0483755a 2053 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
24236869 2054
24236869 2055 if (!vs->kbd_layout)
28a76be8 2056 exit(1);
24236869 2057
753b4053 2058 dcl->dpy_copy = vnc_dpy_copy;
7d957bd8
AL
2059 dcl->dpy_update = vnc_dpy_update;
2060 dcl->dpy_resize = vnc_dpy_resize;
2061 dcl->dpy_setdata = vnc_dpy_setdata;
7d957bd8 2062 register_displaychangelistener(ds, dcl);
71cab5ca
TS
2063}
2064
6f43024c 2065
71cab5ca
TS
2066void vnc_display_close(DisplayState *ds)
2067{
753b4053 2068 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
71cab5ca 2069
452b4d88
AL
2070 if (!vs)
2071 return;
71cab5ca 2072 if (vs->display) {
28a76be8
AL
2073 qemu_free(vs->display);
2074 vs->display = NULL;
71cab5ca
TS
2075 }
2076 if (vs->lsock != -1) {
28a76be8
AL
2077 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2078 close(vs->lsock);
2079 vs->lsock = -1;
71cab5ca 2080 }
70848515 2081 vs->auth = VNC_AUTH_INVALID;
eb38c52c 2082#ifdef CONFIG_VNC_TLS
8d5d2d4c 2083 vs->subauth = VNC_AUTH_INVALID;
5fb6c7a8 2084 vs->tls.x509verify = 0;
8d5d2d4c 2085#endif
70848515
TS
2086}
2087
2088int vnc_display_password(DisplayState *ds, const char *password)
2089{
753b4053 2090 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
70848515
TS
2091
2092 if (vs->password) {
28a76be8
AL
2093 qemu_free(vs->password);
2094 vs->password = NULL;
70848515
TS
2095 }
2096 if (password && password[0]) {
28a76be8
AL
2097 if (!(vs->password = qemu_strdup(password)))
2098 return -1;
70848515
TS
2099 }
2100
2101 return 0;
71cab5ca
TS
2102}
2103
70848515 2104int vnc_display_open(DisplayState *ds, const char *display)
71cab5ca 2105{
753b4053 2106 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
70848515
TS
2107 const char *options;
2108 int password = 0;
3aa3eea3 2109 int reverse = 0;
9712ecaf 2110 int to_port = 0;
eb38c52c 2111#ifdef CONFIG_VNC_TLS
3a702699 2112 int tls = 0, x509 = 0;
8d5d2d4c 2113#endif
2f9606b3
AL
2114#ifdef CONFIG_VNC_SASL
2115 int sasl = 0;
2116 int saslErr;
2117#endif
76655d6d 2118 int acl = 0;
71cab5ca 2119
753b4053 2120 if (!vnc_display)
452b4d88 2121 return -1;
71cab5ca 2122 vnc_display_close(ds);
70848515 2123 if (strcmp(display, "none") == 0)
28a76be8 2124 return 0;
24236869 2125
70848515 2126 if (!(vs->display = strdup(display)))
28a76be8 2127 return -1;
70848515
TS
2128
2129 options = display;
2130 while ((options = strchr(options, ','))) {
28a76be8
AL
2131 options++;
2132 if (strncmp(options, "password", 8) == 0) {
2133 password = 1; /* Require password auth */
2134 } else if (strncmp(options, "reverse", 7) == 0) {
2135 reverse = 1;
2136 } else if (strncmp(options, "to=", 3) == 0) {
9712ecaf 2137 to_port = atoi(options+3) + 5900;
2f9606b3 2138#ifdef CONFIG_VNC_SASL
28a76be8
AL
2139 } else if (strncmp(options, "sasl", 4) == 0) {
2140 sasl = 1; /* Require SASL auth */
2f9606b3 2141#endif
eb38c52c 2142#ifdef CONFIG_VNC_TLS
28a76be8
AL
2143 } else if (strncmp(options, "tls", 3) == 0) {
2144 tls = 1; /* Require TLS */
2145 } else if (strncmp(options, "x509", 4) == 0) {
2146 char *start, *end;
2147 x509 = 1; /* Require x509 certificates */
2148 if (strncmp(options, "x509verify", 10) == 0)
2149 vs->tls.x509verify = 1; /* ...and verify client certs */
2150
2151 /* Now check for 'x509=/some/path' postfix
2152 * and use that to setup x509 certificate/key paths */
2153 start = strchr(options, '=');
2154 end = strchr(options, ',');
2155 if (start && (!end || (start < end))) {
2156 int len = end ? end-(start+1) : strlen(start+1);
2157 char *path = qemu_strndup(start + 1, len);
2158
2159 VNC_DEBUG("Trying certificate path '%s'\n", path);
2160 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2161 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2162 qemu_free(path);
2163 qemu_free(vs->display);
2164 vs->display = NULL;
2165 return -1;
2166 }
2167 qemu_free(path);
2168 } else {
2169 fprintf(stderr, "No certificate path provided\n");
2170 qemu_free(vs->display);
2171 vs->display = NULL;
2172 return -1;
2173 }
8d5d2d4c 2174#endif
28a76be8
AL
2175 } else if (strncmp(options, "acl", 3) == 0) {
2176 acl = 1;
2177 }
70848515
TS
2178 }
2179
76655d6d
AL
2180#ifdef CONFIG_VNC_TLS
2181 if (acl && x509 && vs->tls.x509verify) {
28a76be8
AL
2182 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2183 fprintf(stderr, "Failed to create x509 dname ACL\n");
2184 exit(1);
2185 }
76655d6d
AL
2186 }
2187#endif
2188#ifdef CONFIG_VNC_SASL
2189 if (acl && sasl) {
28a76be8
AL
2190 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2191 fprintf(stderr, "Failed to create username ACL\n");
2192 exit(1);
2193 }
76655d6d
AL
2194 }
2195#endif
2196
2f9606b3
AL
2197 /*
2198 * Combinations we support here:
2199 *
2200 * - no-auth (clear text, no auth)
2201 * - password (clear text, weak auth)
2202 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
2203 * - tls (encrypt, weak anonymous creds, no auth)
2204 * - tls + password (encrypt, weak anonymous creds, weak auth)
2205 * - tls + sasl (encrypt, weak anonymous creds, good auth)
2206 * - tls + x509 (encrypt, good x509 creds, no auth)
2207 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
2208 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
2209 *
2210 * NB1. TLS is a stackable auth scheme.
2211 * NB2. the x509 schemes have option to validate a client cert dname
2212 */
70848515 2213 if (password) {
eb38c52c 2214#ifdef CONFIG_VNC_TLS
28a76be8
AL
2215 if (tls) {
2216 vs->auth = VNC_AUTH_VENCRYPT;
2217 if (x509) {
2218 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2219 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2220 } else {
2221 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2222 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2223 }
2224 } else {
2f9606b3 2225#endif /* CONFIG_VNC_TLS */
28a76be8
AL
2226 VNC_DEBUG("Initializing VNC server with password auth\n");
2227 vs->auth = VNC_AUTH_VNC;
eb38c52c 2228#ifdef CONFIG_VNC_TLS
28a76be8
AL
2229 vs->subauth = VNC_AUTH_INVALID;
2230 }
2f9606b3
AL
2231#endif /* CONFIG_VNC_TLS */
2232#ifdef CONFIG_VNC_SASL
2233 } else if (sasl) {
2234#ifdef CONFIG_VNC_TLS
2235 if (tls) {
2236 vs->auth = VNC_AUTH_VENCRYPT;
2237 if (x509) {
28a76be8 2238 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2f9606b3
AL
2239 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2240 } else {
28a76be8 2241 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2f9606b3
AL
2242 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2243 }
2244 } else {
2245#endif /* CONFIG_VNC_TLS */
28a76be8 2246 VNC_DEBUG("Initializing VNC server with SASL auth\n");
2f9606b3
AL
2247 vs->auth = VNC_AUTH_SASL;
2248#ifdef CONFIG_VNC_TLS
2249 vs->subauth = VNC_AUTH_INVALID;
2250 }
2251#endif /* CONFIG_VNC_TLS */
2252#endif /* CONFIG_VNC_SASL */
70848515 2253 } else {
eb38c52c 2254#ifdef CONFIG_VNC_TLS
28a76be8
AL
2255 if (tls) {
2256 vs->auth = VNC_AUTH_VENCRYPT;
2257 if (x509) {
2258 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2259 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2260 } else {
2261 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2262 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2263 }
2264 } else {
8d5d2d4c 2265#endif
28a76be8
AL
2266 VNC_DEBUG("Initializing VNC server with no auth\n");
2267 vs->auth = VNC_AUTH_NONE;
eb38c52c 2268#ifdef CONFIG_VNC_TLS
28a76be8
AL
2269 vs->subauth = VNC_AUTH_INVALID;
2270 }
8d5d2d4c 2271#endif
70848515 2272 }
24236869 2273
2f9606b3
AL
2274#ifdef CONFIG_VNC_SASL
2275 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2276 fprintf(stderr, "Failed to initialize SASL auth %s",
2277 sasl_errstring(saslErr, NULL, NULL));
2278 free(vs->display);
2279 vs->display = NULL;
2280 return -1;
2281 }
2282#endif
2283
3aa3eea3 2284 if (reverse) {
9712ecaf
AL
2285 /* connect to viewer */
2286 if (strncmp(display, "unix:", 5) == 0)
2287 vs->lsock = unix_connect(display+5);
2288 else
2289 vs->lsock = inet_connect(display, SOCK_STREAM);
2290 if (-1 == vs->lsock) {
3aa3eea3
AZ
2291 free(vs->display);
2292 vs->display = NULL;
2293 return -1;
2294 } else {
753b4053 2295 int csock = vs->lsock;
3aa3eea3 2296 vs->lsock = -1;
753b4053 2297 vnc_connect(vs, csock);
3aa3eea3 2298 }
9712ecaf 2299 return 0;
24236869 2300
9712ecaf
AL
2301 } else {
2302 /* listen for connects */
2303 char *dpy;
2304 dpy = qemu_malloc(256);
2305 if (strncmp(display, "unix:", 5) == 0) {
bc575e95 2306 pstrcpy(dpy, 256, "unix:");
4a55bfdf 2307 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
9712ecaf
AL
2308 } else {
2309 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2310 }
2311 if (-1 == vs->lsock) {
2312 free(dpy);
d0513623 2313 return -1;
9712ecaf
AL
2314 } else {
2315 free(vs->display);
2316 vs->display = dpy;
2317 }
24236869 2318 }
753b4053 2319 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
24236869 2320}