2 * QEMU VNC display driver
4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5 * Copyright (C) 2006 Fabrice Bellard
6 * Copyright (C) 2009 Red Hat, Inc
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:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
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
29 #include "qemu_socket.h"
30 #include "qemu-timer.h"
33 #define VNC_REFRESH_INTERVAL (1000 / 30)
35 #include "vnc_keysym.h"
38 #define count_bits(c, v) { \
39 for (c = 0; v; v >>= 1) \
46 static VncDisplay *vnc_display; /* needed for info vnc */
47 static DisplayChangeListener *dcl;
49 static char *addr_to_string(const char *format,
50 struct sockaddr_storage *sa,
53 char host[NI_MAXHOST];
54 char serv[NI_MAXSERV];
58 if ((err = getnameinfo((struct sockaddr *)sa, salen,
61 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
62 VNC_DEBUG("Cannot resolve address %d: %s\n",
63 err, gai_strerror(err));
67 /* Enough for the existing format + the 2 vars we're
69 addrlen = strlen(format) + strlen(host) + strlen(serv);
70 addr = qemu_malloc(addrlen + 1);
71 snprintf(addr, addrlen, format, host, serv);
78 char *vnc_socket_local_addr(const char *format, int fd) {
79 struct sockaddr_storage sa;
83 if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
86 return addr_to_string(format, &sa, salen);
90 char *vnc_socket_remote_addr(const char *format, int fd) {
91 struct sockaddr_storage sa;
95 if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
98 return addr_to_string(format, &sa, salen);
101 static const char *vnc_auth_name(VncDisplay *vd) {
103 case VNC_AUTH_INVALID:
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";
136 case VNC_AUTH_VENCRYPT_TLSSASL:
137 return "vencrypt+tls+sasl";
138 case VNC_AUTH_VENCRYPT_X509SASL:
139 return "vencrypt+x509+sasl";
152 static void do_info_vnc_client(Monitor *mon, VncState *client)
155 vnc_socket_remote_addr(" address: %s:%s\n",
160 monitor_printf(mon, "Client:\n");
161 monitor_printf(mon, "%s", clientAddr);
164 #ifdef CONFIG_VNC_TLS
165 if (client->tls.session &&
167 monitor_printf(mon, " x509 dname: %s\n", client->tls.dname);
169 monitor_printf(mon, " x509 dname: none\n");
171 #ifdef CONFIG_VNC_SASL
172 if (client->sasl.conn &&
173 client->sasl.username)
174 monitor_printf(mon, " username: %s\n", client->sasl.username);
176 monitor_printf(mon, " username: none\n");
180 void do_info_vnc(Monitor *mon)
182 if (vnc_display == NULL || vnc_display->display == NULL) {
183 monitor_printf(mon, "Server: disabled\n");
185 char *serverAddr = vnc_socket_local_addr(" address: %s:%s\n",
191 monitor_printf(mon, "Server:\n");
192 monitor_printf(mon, "%s", serverAddr);
194 monitor_printf(mon, " auth: %s\n", vnc_auth_name(vnc_display));
196 if (vnc_display->clients) {
197 VncState *client = vnc_display->clients;
199 do_info_vnc_client(mon, client);
200 client = client->next;
203 monitor_printf(mon, "Client: none\n");
208 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
209 return (vs->features & (1 << feature));
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
219 static void vnc_update_client(void *opaque);
221 static void vnc_colordepth(VncState *vs);
223 static inline void vnc_set_bit(uint32_t *d, int k)
225 d[k >> 5] |= 1 << (k & 0x1f);
228 static inline void vnc_clear_bit(uint32_t *d, int k)
230 d[k >> 5] &= ~(1 << (k & 0x1f));
233 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
243 d[j++] = (1 << n) - 1;
248 static inline int vnc_get_bit(const uint32_t *d, int k)
250 return (d[k >> 5] >> (k & 0x1f)) & 1;
253 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
257 for(i = 0; i < nb_words; i++) {
258 if ((d1[i] & d2[i]) != 0)
264 static void vnc_update(VncState *vs, int x, int y, int w, int h)
266 struct VncSurface *s = &vs->guest;
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
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);
284 for (i = 0; i < w; i += 16)
285 vnc_set_bit(s->dirty[y], (x + i) / 16);
288 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
290 VncDisplay *vd = ds->opaque;
291 VncState *vs = vd->clients;
293 vnc_update(vs, x, y, w, h);
298 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
301 vnc_write_u16(vs, x);
302 vnc_write_u16(vs, y);
303 vnc_write_u16(vs, w);
304 vnc_write_u16(vs, h);
306 vnc_write_s32(vs, encoding);
309 void buffer_reserve(Buffer *buffer, size_t len)
311 if ((buffer->capacity - buffer->offset) < len) {
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");
321 int buffer_empty(Buffer *buffer)
323 return buffer->offset == 0;
326 uint8_t *buffer_end(Buffer *buffer)
328 return buffer->buffer + buffer->offset;
331 void buffer_reset(Buffer *buffer)
336 void buffer_append(Buffer *buffer, const void *data, size_t len)
338 memcpy(buffer->buffer + buffer->offset, data, len);
339 buffer->offset += len;
342 static void vnc_resize(VncState *vs)
344 DisplayState *ds = vs->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)
351 console_color_init(ds);
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);
357 if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
358 vnc_write_u8(vs, 0); /* msg id */
360 vnc_write_u16(vs, 1); /* number of rects */
361 vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
362 VNC_ENCODING_DESKTOPRESIZE);
366 memset(vs->guest.dirty, 0xFF, sizeof(vs->guest.dirty));
369 if (!vs->server.ds) {
370 vs->server.ds = default_allocator.create_displaysurface(ds_get_width(ds),
373 default_allocator.resize_displaysurface(vs->server.ds,
374 ds_get_width(ds), ds_get_height(ds));
376 if (vs->server.ds->data == NULL) {
377 fprintf(stderr, "vnc: memory allocation failed\n");
380 memset(vs->server.dirty, 0xFF, sizeof(vs->guest.dirty));
383 static void vnc_dpy_resize(DisplayState *ds)
385 VncDisplay *vd = ds->opaque;
386 VncState *vs = vd->clients;
394 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
396 vnc_write(vs, pixels, size);
399 /* slowest but generic code. */
400 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
404 r = ((((v & vs->server.ds->pf.rmask) >> vs->server.ds->pf.rshift) << vs->clientds.pf.rbits) >>
405 vs->server.ds->pf.rbits);
406 g = ((((v & vs->server.ds->pf.gmask) >> vs->server.ds->pf.gshift) << vs->clientds.pf.gbits) >>
407 vs->server.ds->pf.gbits);
408 b = ((((v & vs->server.ds->pf.bmask) >> vs->server.ds->pf.bshift) << vs->clientds.pf.bbits) >>
409 vs->server.ds->pf.bbits);
410 v = (r << vs->clientds.pf.rshift) |
411 (g << vs->clientds.pf.gshift) |
412 (b << vs->clientds.pf.bshift);
413 switch(vs->clientds.pf.bytes_per_pixel) {
418 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
428 if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
443 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
447 if (vs->server.ds->pf.bytes_per_pixel == 4) {
448 uint32_t *pixels = pixels1;
451 for(i = 0; i < n; i++) {
452 vnc_convert_pixel(vs, buf, pixels[i]);
453 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
455 } else if (vs->server.ds->pf.bytes_per_pixel == 2) {
456 uint16_t *pixels = pixels1;
459 for(i = 0; i < n; i++) {
460 vnc_convert_pixel(vs, buf, pixels[i]);
461 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
463 } else if (vs->server.ds->pf.bytes_per_pixel == 1) {
464 uint8_t *pixels = pixels1;
467 for(i = 0; i < n; i++) {
468 vnc_convert_pixel(vs, buf, pixels[i]);
469 vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
472 fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
476 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
481 row = vs->server.ds->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
482 for (i = 0; i < h; i++) {
483 vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
484 row += ds_get_linesize(vs->ds);
488 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
490 ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
491 ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
495 #include "vnchextile.h"
499 #include "vnchextile.h"
503 #include "vnchextile.h"
508 #include "vnchextile.h"
514 #include "vnchextile.h"
520 #include "vnchextile.h"
524 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
528 uint8_t *last_fg, *last_bg;
530 last_fg = (uint8_t *) qemu_malloc(vs->server.ds->pf.bytes_per_pixel);
531 last_bg = (uint8_t *) qemu_malloc(vs->server.ds->pf.bytes_per_pixel);
533 for (j = y; j < (y + h); j += 16) {
534 for (i = x; i < (x + w); i += 16) {
535 vs->send_hextile_tile(vs, i, j,
536 MIN(16, x + w - i), MIN(16, y + h - j),
537 last_bg, last_fg, &has_bg, &has_fg);
545 static void vnc_zlib_init(VncState *vs)
548 for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
549 vs->zlib_stream[i].opaque = NULL;
552 static void vnc_zlib_start(VncState *vs)
554 buffer_reset(&vs->zlib);
556 // make the output buffer be the zlib buffer, so we can compress it later
557 vs->zlib_tmp = vs->output;
558 vs->output = vs->zlib;
561 static int vnc_zlib_stop(VncState *vs, int stream_id)
563 z_streamp zstream = &vs->zlib_stream[stream_id];
566 // switch back to normal output/zlib buffers
567 vs->zlib = vs->output;
568 vs->output = vs->zlib_tmp;
570 // compress the zlib buffer
572 // initialize the stream
573 // XXX need one stream per session
574 if (zstream->opaque != vs) {
577 VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
578 VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
579 zstream->zalloc = Z_NULL;
580 zstream->zfree = Z_NULL;
582 err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
583 MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
586 fprintf(stderr, "VNC: error initializing zlib\n");
590 zstream->opaque = vs;
593 // XXX what to do if tight_compression changed in between?
595 // reserve memory in output buffer
596 buffer_reserve(&vs->output, vs->zlib.offset + 64);
599 zstream->next_in = vs->zlib.buffer;
600 zstream->avail_in = vs->zlib.offset;
601 zstream->next_out = vs->output.buffer + vs->output.offset;
602 zstream->avail_out = vs->output.capacity - vs->output.offset;
603 zstream->data_type = Z_BINARY;
604 previous_out = zstream->total_out;
607 if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
608 fprintf(stderr, "VNC: error during zlib compression\n");
612 vs->output.offset = vs->output.capacity - zstream->avail_out;
613 return zstream->total_out - previous_out;
616 static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
618 int old_offset, new_offset, bytes_written;
620 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
622 // remember where we put in the follow-up size
623 old_offset = vs->output.offset;
624 vnc_write_s32(vs, 0);
626 // compress the stream
628 send_framebuffer_update_raw(vs, x, y, w, h);
629 bytes_written = vnc_zlib_stop(vs, 0);
631 if (bytes_written == -1)
635 new_offset = vs->output.offset;
636 vs->output.offset = old_offset;
637 vnc_write_u32(vs, bytes_written);
638 vs->output.offset = new_offset;
641 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
643 switch(vs->vnc_encoding) {
644 case VNC_ENCODING_ZLIB:
645 send_framebuffer_update_zlib(vs, x, y, w, h);
647 case VNC_ENCODING_HEXTILE:
648 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
649 send_framebuffer_update_hextile(vs, x, y, w, h);
652 vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
653 send_framebuffer_update_raw(vs, x, y, w, h);
658 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
660 vs->force_update = 1;
661 vnc_update_client(vs);
663 vnc_write_u8(vs, 0); /* msg id */
665 vnc_write_u16(vs, 1); /* number of rects */
666 vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
667 vnc_write_u16(vs, src_x);
668 vnc_write_u16(vs, src_y);
672 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
674 VncDisplay *vd = ds->opaque;
675 VncState *vs = vd->clients;
677 if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
678 vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
680 vnc_update(vs, dst_x, dst_y, w, h);
685 static int find_and_clear_dirty_height(struct VncSurface *s,
686 int y, int last_x, int x)
690 for (h = 1; h < (s->ds->height - y) && h < 1; h++) {
692 if (!vnc_get_bit(s->dirty[y + h], last_x))
694 for (tmp_x = last_x; tmp_x < x; tmp_x++)
695 vnc_clear_bit(s->dirty[y + h], tmp_x);
701 static void vnc_update_client(void *opaque)
703 VncState *vs = opaque;
704 if (vs->need_update && vs->csock != -1) {
708 int cmp_bytes = 16 * ds_get_bytes_per_pixel(vs->ds);
709 uint32_t width_mask[VNC_DIRTY_WORDS];
714 if (vs->output.offset && !vs->audio_cap && !vs->force_update) {
715 /* kernel send buffers are full -> drop frames to throttle */
716 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
723 * Walk through the guest dirty map.
724 * Check and copy modified bits from guest to server surface.
725 * Update server dirty map.
727 vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
728 guest_row = vs->guest.ds->data;
729 server_row = vs->server.ds->data;
730 for (y = 0; y < vs->guest.ds->height; y++) {
731 if (vnc_and_bits(vs->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
736 guest_ptr = guest_row;
737 server_ptr = server_row;
739 for (x = 0; x < vs->guest.ds->width;
740 x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
741 if (!vnc_get_bit(vs->guest.dirty[y], (x / 16)))
743 vnc_clear_bit(vs->guest.dirty[y], (x / 16));
744 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
746 memcpy(server_ptr, guest_ptr, cmp_bytes);
747 vnc_set_bit(vs->server.dirty[y], (x / 16));
751 guest_row += ds_get_linesize(vs->ds);
752 server_row += ds_get_linesize(vs->ds);
755 if (!has_dirty && !vs->audio_cap && !vs->force_update) {
756 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
761 * Send screen updates to the vnc client using the server
762 * surface and server dirty map. guest surface updates
763 * happening in parallel don't disturb us, the next pass will
764 * send them to the client.
767 vnc_write_u8(vs, 0); /* msg id */
769 saved_offset = vs->output.offset;
770 vnc_write_u16(vs, 0);
772 for (y = 0; y < vs->server.ds->height; y++) {
775 for (x = 0; x < vs->server.ds->width / 16; x++) {
776 if (vnc_get_bit(vs->server.dirty[y], x)) {
780 vnc_clear_bit(vs->server.dirty[y], x);
783 int h = find_and_clear_dirty_height(&vs->server, y, last_x, x);
784 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
791 int h = find_and_clear_dirty_height(&vs->server, y, last_x, x);
792 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
796 vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
797 vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
799 vs->force_update = 0;
803 if (vs->csock != -1) {
804 qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
810 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
812 VncState *vs = opaque;
815 case AUD_CNOTIFY_DISABLE:
816 vnc_write_u8(vs, 255);
818 vnc_write_u16(vs, 0);
822 case AUD_CNOTIFY_ENABLE:
823 vnc_write_u8(vs, 255);
825 vnc_write_u16(vs, 1);
831 static void audio_capture_destroy(void *opaque)
835 static void audio_capture(void *opaque, void *buf, int size)
837 VncState *vs = opaque;
839 vnc_write_u8(vs, 255);
841 vnc_write_u16(vs, 2);
842 vnc_write_u32(vs, size);
843 vnc_write(vs, buf, size);
847 static void audio_add(VncState *vs)
849 Monitor *mon = cur_mon;
850 struct audio_capture_ops ops;
853 monitor_printf(mon, "audio already running\n");
857 ops.notify = audio_capture_notify;
858 ops.destroy = audio_capture_destroy;
859 ops.capture = audio_capture;
861 vs->audio_cap = AUD_add_capture(NULL, &vs->as, &ops, vs);
862 if (!vs->audio_cap) {
863 monitor_printf(mon, "Failed to add audio capture\n");
867 static void audio_del(VncState *vs)
870 AUD_del_capture(vs->audio_cap, vs);
871 vs->audio_cap = NULL;
876 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
878 if (ret == 0 || ret == -1) {
880 switch (last_errno) {
892 VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
893 qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
894 closesocket(vs->csock);
895 qemu_del_timer(vs->timer);
896 qemu_free_timer(vs->timer);
897 if (vs->input.buffer) qemu_free(vs->input.buffer);
898 if (vs->output.buffer) qemu_free(vs->output.buffer);
899 #ifdef CONFIG_VNC_TLS
900 vnc_tls_client_cleanup(vs);
901 #endif /* CONFIG_VNC_TLS */
902 #ifdef CONFIG_VNC_SASL
903 vnc_sasl_client_cleanup(vs);
904 #endif /* CONFIG_VNC_SASL */
907 VncState *p, *parent = NULL;
908 for (p = vs->vd->clients; p != NULL; p = p->next) {
911 parent->next = p->next;
913 vs->vd->clients = p->next;
918 if (!vs->vd->clients)
921 default_allocator.free_displaysurface(vs->server.ds);
922 qemu_free(vs->guest.ds);
931 void vnc_client_error(VncState *vs)
933 vnc_client_io_error(vs, -1, EINVAL);
938 * Called to write a chunk of data to the client socket. The data may
939 * be the raw data, or may have already been encoded by SASL.
940 * The data will be written either straight onto the socket, or
941 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
943 * NB, it is theoretically possible to have 2 layers of encryption,
944 * both SASL, and this TLS layer. It is highly unlikely in practice
945 * though, since SASL encryption will typically be a no-op if TLS
948 * Returns the number of bytes written, which may be less than
949 * the requested 'datalen' if the socket would block. Returns
950 * -1 on error, and disconnects the client socket.
952 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
955 #ifdef CONFIG_VNC_TLS
956 if (vs->tls.session) {
957 ret = gnutls_write(vs->tls.session, data, datalen);
959 if (ret == GNUTLS_E_AGAIN)
966 #endif /* CONFIG_VNC_TLS */
967 ret = send(vs->csock, data, datalen, 0);
968 VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
969 return vnc_client_io_error(vs, ret, socket_error());
974 * Called to write buffered data to the client socket, when not
975 * using any SASL SSF encryption layers. Will write as much data
976 * as possible without blocking. If all buffered data is written,
977 * will switch the FD poll() handler back to read monitoring.
979 * Returns the number of bytes written, which may be less than
980 * the buffered output data if the socket would block. Returns
981 * -1 on error, and disconnects the client socket.
983 static long vnc_client_write_plain(VncState *vs)
987 #ifdef CONFIG_VNC_SASL
988 VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
989 vs->output.buffer, vs->output.capacity, vs->output.offset,
990 vs->sasl.waitWriteSSF);
994 vs->sasl.waitWriteSSF) {
995 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
997 vs->sasl.waitWriteSSF -= ret;
999 #endif /* CONFIG_VNC_SASL */
1000 ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1004 memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1005 vs->output.offset -= ret;
1007 if (vs->output.offset == 0) {
1008 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1016 * First function called whenever there is data to be written to
1017 * the client socket. Will delegate actual work according to whether
1018 * SASL SSF layers are enabled (thus requiring encryption calls)
1020 void vnc_client_write(void *opaque)
1023 VncState *vs = opaque;
1025 #ifdef CONFIG_VNC_SASL
1026 if (vs->sasl.conn &&
1028 !vs->sasl.waitWriteSSF)
1029 ret = vnc_client_write_sasl(vs);
1031 #endif /* CONFIG_VNC_SASL */
1032 ret = vnc_client_write_plain(vs);
1035 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1037 vs->read_handler = func;
1038 vs->read_handler_expect = expecting;
1043 * Called to read a chunk of data from the client socket. The data may
1044 * be the raw data, or may need to be further decoded by SASL.
1045 * The data will be read either straight from to the socket, or
1046 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1048 * NB, it is theoretically possible to have 2 layers of encryption,
1049 * both SASL, and this TLS layer. It is highly unlikely in practice
1050 * though, since SASL encryption will typically be a no-op if TLS
1053 * Returns the number of bytes read, which may be less than
1054 * the requested 'datalen' if the socket would block. Returns
1055 * -1 on error, and disconnects the client socket.
1057 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1060 #ifdef CONFIG_VNC_TLS
1061 if (vs->tls.session) {
1062 ret = gnutls_read(vs->tls.session, data, datalen);
1064 if (ret == GNUTLS_E_AGAIN)
1071 #endif /* CONFIG_VNC_TLS */
1072 ret = recv(vs->csock, data, datalen, 0);
1073 VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1074 return vnc_client_io_error(vs, ret, socket_error());
1079 * Called to read data from the client socket to the input buffer,
1080 * when not using any SASL SSF encryption layers. Will read as much
1081 * data as possible without blocking.
1083 * Returns the number of bytes read. Returns -1 on error, and
1084 * disconnects the client socket.
1086 static long vnc_client_read_plain(VncState *vs)
1089 VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1090 vs->input.buffer, vs->input.capacity, vs->input.offset);
1091 buffer_reserve(&vs->input, 4096);
1092 ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1095 vs->input.offset += ret;
1101 * First function called whenever there is more data to be read from
1102 * the client socket. Will delegate actual work according to whether
1103 * SASL SSF layers are enabled (thus requiring decryption calls)
1105 void vnc_client_read(void *opaque)
1107 VncState *vs = opaque;
1110 #ifdef CONFIG_VNC_SASL
1111 if (vs->sasl.conn && vs->sasl.runSSF)
1112 ret = vnc_client_read_sasl(vs);
1114 #endif /* CONFIG_VNC_SASL */
1115 ret = vnc_client_read_plain(vs);
1119 while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1120 size_t len = vs->read_handler_expect;
1123 ret = vs->read_handler(vs, vs->input.buffer, len);
1124 if (vs->csock == -1)
1128 memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1129 vs->input.offset -= len;
1131 vs->read_handler_expect = ret;
1136 void vnc_write(VncState *vs, const void *data, size_t len)
1138 buffer_reserve(&vs->output, len);
1140 if (buffer_empty(&vs->output)) {
1141 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1144 buffer_append(&vs->output, data, len);
1147 void vnc_write_s32(VncState *vs, int32_t value)
1149 vnc_write_u32(vs, *(uint32_t *)&value);
1152 void vnc_write_u32(VncState *vs, uint32_t value)
1156 buf[0] = (value >> 24) & 0xFF;
1157 buf[1] = (value >> 16) & 0xFF;
1158 buf[2] = (value >> 8) & 0xFF;
1159 buf[3] = value & 0xFF;
1161 vnc_write(vs, buf, 4);
1164 void vnc_write_u16(VncState *vs, uint16_t value)
1168 buf[0] = (value >> 8) & 0xFF;
1169 buf[1] = value & 0xFF;
1171 vnc_write(vs, buf, 2);
1174 void vnc_write_u8(VncState *vs, uint8_t value)
1176 vnc_write(vs, (char *)&value, 1);
1179 void vnc_flush(VncState *vs)
1181 if (vs->output.offset)
1182 vnc_client_write(vs);
1185 uint8_t read_u8(uint8_t *data, size_t offset)
1187 return data[offset];
1190 uint16_t read_u16(uint8_t *data, size_t offset)
1192 return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1195 int32_t read_s32(uint8_t *data, size_t offset)
1197 return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1198 (data[offset + 2] << 8) | data[offset + 3]);
1201 uint32_t read_u32(uint8_t *data, size_t offset)
1203 return ((data[offset] << 24) | (data[offset + 1] << 16) |
1204 (data[offset + 2] << 8) | data[offset + 3]);
1207 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1211 static void check_pointer_type_change(VncState *vs, int absolute)
1213 if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1214 vnc_write_u8(vs, 0);
1215 vnc_write_u8(vs, 0);
1216 vnc_write_u16(vs, 1);
1217 vnc_framebuffer_update(vs, absolute, 0,
1218 ds_get_width(vs->ds), ds_get_height(vs->ds),
1219 VNC_ENCODING_POINTER_TYPE_CHANGE);
1222 vs->absolute = absolute;
1225 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1230 if (button_mask & 0x01)
1231 buttons |= MOUSE_EVENT_LBUTTON;
1232 if (button_mask & 0x02)
1233 buttons |= MOUSE_EVENT_MBUTTON;
1234 if (button_mask & 0x04)
1235 buttons |= MOUSE_EVENT_RBUTTON;
1236 if (button_mask & 0x08)
1238 if (button_mask & 0x10)
1242 kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1243 y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1245 } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1249 kbd_mouse_event(x, y, dz, buttons);
1251 if (vs->last_x != -1)
1252 kbd_mouse_event(x - vs->last_x,
1259 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1262 static void reset_keys(VncState *vs)
1265 for(i = 0; i < 256; i++) {
1266 if (vs->modifiers_state[i]) {
1268 kbd_put_keycode(0xe0);
1269 kbd_put_keycode(i | 0x80);
1270 vs->modifiers_state[i] = 0;
1275 static void press_key(VncState *vs, int keysym)
1277 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1278 kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
1281 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1283 /* QEMU console switch */
1285 case 0x2a: /* Left Shift */
1286 case 0x36: /* Right Shift */
1287 case 0x1d: /* Left CTRL */
1288 case 0x9d: /* Right CTRL */
1289 case 0x38: /* Left ALT */
1290 case 0xb8: /* Right ALT */
1292 vs->modifiers_state[keycode] = 1;
1294 vs->modifiers_state[keycode] = 0;
1296 case 0x02 ... 0x0a: /* '1' to '9' keys */
1297 if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1298 /* Reset the modifiers sent to the current console */
1300 console_select(keycode - 0x02);
1304 case 0x3a: /* CapsLock */
1305 case 0x45: /* NumLock */
1307 vs->modifiers_state[keycode] ^= 1;
1311 if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1312 /* If the numlock state needs to change then simulate an additional
1313 keypress before sending this one. This will happen if the user
1314 toggles numlock away from the VNC window.
1316 if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1317 if (!vs->modifiers_state[0x45]) {
1318 vs->modifiers_state[0x45] = 1;
1319 press_key(vs, 0xff7f);
1322 if (vs->modifiers_state[0x45]) {
1323 vs->modifiers_state[0x45] = 0;
1324 press_key(vs, 0xff7f);
1329 if (is_graphic_console()) {
1331 kbd_put_keycode(0xe0);
1333 kbd_put_keycode(keycode & 0x7f);
1335 kbd_put_keycode(keycode | 0x80);
1337 /* QEMU console emulation */
1340 case 0x2a: /* Left Shift */
1341 case 0x36: /* Right Shift */
1342 case 0x1d: /* Left CTRL */
1343 case 0x9d: /* Right CTRL */
1344 case 0x38: /* Left ALT */
1345 case 0xb8: /* Right ALT */
1349 kbd_put_keysym(QEMU_KEY_UP);
1353 kbd_put_keysym(QEMU_KEY_DOWN);
1357 kbd_put_keysym(QEMU_KEY_LEFT);
1361 kbd_put_keysym(QEMU_KEY_RIGHT);
1365 kbd_put_keysym(QEMU_KEY_DELETE);
1369 kbd_put_keysym(QEMU_KEY_HOME);
1373 kbd_put_keysym(QEMU_KEY_END);
1377 kbd_put_keysym(QEMU_KEY_PAGEUP);
1381 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1384 kbd_put_keysym(sym);
1391 static void key_event(VncState *vs, int down, uint32_t sym)
1395 if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1396 sym = sym - 'A' + 'a';
1398 keycode = keysym2scancode(vs->vd->kbd_layout, sym & 0xFFFF);
1399 do_key_event(vs, down, keycode, sym);
1402 static void ext_key_event(VncState *vs, int down,
1403 uint32_t sym, uint16_t keycode)
1405 /* if the user specifies a keyboard layout, always use it */
1406 if (keyboard_layout)
1407 key_event(vs, down, sym);
1409 do_key_event(vs, down, keycode, sym);
1412 static void framebuffer_update_request(VncState *vs, int incremental,
1413 int x_position, int y_position,
1416 if (x_position > ds_get_width(vs->ds))
1417 x_position = ds_get_width(vs->ds);
1418 if (y_position > ds_get_height(vs->ds))
1419 y_position = ds_get_height(vs->ds);
1420 if (x_position + w >= ds_get_width(vs->ds))
1421 w = ds_get_width(vs->ds) - x_position;
1422 if (y_position + h >= ds_get_height(vs->ds))
1423 h = ds_get_height(vs->ds) - y_position;
1426 vs->need_update = 1;
1427 vs->force_update = 1;
1429 for (i = 0; i < h; i++) {
1430 vnc_set_bits(vs->guest.dirty[y_position + i],
1431 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1432 vnc_set_bits(vs->server.dirty[y_position + i],
1433 (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1438 static void send_ext_key_event_ack(VncState *vs)
1440 vnc_write_u8(vs, 0);
1441 vnc_write_u8(vs, 0);
1442 vnc_write_u16(vs, 1);
1443 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1444 VNC_ENCODING_EXT_KEY_EVENT);
1448 static void send_ext_audio_ack(VncState *vs)
1450 vnc_write_u8(vs, 0);
1451 vnc_write_u8(vs, 0);
1452 vnc_write_u16(vs, 1);
1453 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1454 VNC_ENCODING_AUDIO);
1458 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1461 unsigned int enc = 0;
1465 vs->vnc_encoding = 0;
1466 vs->tight_compression = 9;
1467 vs->tight_quality = 9;
1470 for (i = n_encodings - 1; i >= 0; i--) {
1473 case VNC_ENCODING_RAW:
1474 vs->vnc_encoding = enc;
1476 case VNC_ENCODING_COPYRECT:
1477 vs->features |= VNC_FEATURE_COPYRECT_MASK;
1479 case VNC_ENCODING_HEXTILE:
1480 vs->features |= VNC_FEATURE_HEXTILE_MASK;
1481 vs->vnc_encoding = enc;
1483 case VNC_ENCODING_ZLIB:
1484 vs->features |= VNC_FEATURE_ZLIB_MASK;
1485 vs->vnc_encoding = enc;
1487 case VNC_ENCODING_DESKTOPRESIZE:
1488 vs->features |= VNC_FEATURE_RESIZE_MASK;
1490 case VNC_ENCODING_POINTER_TYPE_CHANGE:
1491 vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1493 case VNC_ENCODING_EXT_KEY_EVENT:
1494 send_ext_key_event_ack(vs);
1496 case VNC_ENCODING_AUDIO:
1497 send_ext_audio_ack(vs);
1499 case VNC_ENCODING_WMVi:
1500 vs->features |= VNC_FEATURE_WMVI_MASK;
1502 case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1503 vs->tight_compression = (enc & 0x0F);
1505 case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1506 vs->tight_quality = (enc & 0x0F);
1509 VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1514 check_pointer_type_change(vs, kbd_mouse_is_absolute());
1517 static void set_pixel_conversion(VncState *vs)
1519 if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1520 (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1521 !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1522 vs->write_pixels = vnc_write_pixels_copy;
1523 switch (vs->ds->surface->pf.bits_per_pixel) {
1525 vs->send_hextile_tile = send_hextile_tile_8;
1528 vs->send_hextile_tile = send_hextile_tile_16;
1531 vs->send_hextile_tile = send_hextile_tile_32;
1535 vs->write_pixels = vnc_write_pixels_generic;
1536 switch (vs->ds->surface->pf.bits_per_pixel) {
1538 vs->send_hextile_tile = send_hextile_tile_generic_8;
1541 vs->send_hextile_tile = send_hextile_tile_generic_16;
1544 vs->send_hextile_tile = send_hextile_tile_generic_32;
1550 static void set_pixel_format(VncState *vs,
1551 int bits_per_pixel, int depth,
1552 int big_endian_flag, int true_color_flag,
1553 int red_max, int green_max, int blue_max,
1554 int red_shift, int green_shift, int blue_shift)
1556 if (!true_color_flag) {
1557 vnc_client_error(vs);
1561 vs->clientds = *(vs->guest.ds);
1562 vs->clientds.pf.rmax = red_max;
1563 count_bits(vs->clientds.pf.rbits, red_max);
1564 vs->clientds.pf.rshift = red_shift;
1565 vs->clientds.pf.rmask = red_max << red_shift;
1566 vs->clientds.pf.gmax = green_max;
1567 count_bits(vs->clientds.pf.gbits, green_max);
1568 vs->clientds.pf.gshift = green_shift;
1569 vs->clientds.pf.gmask = green_max << green_shift;
1570 vs->clientds.pf.bmax = blue_max;
1571 count_bits(vs->clientds.pf.bbits, blue_max);
1572 vs->clientds.pf.bshift = blue_shift;
1573 vs->clientds.pf.bmask = blue_max << blue_shift;
1574 vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1575 vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1576 vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1577 vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1579 set_pixel_conversion(vs);
1581 vga_hw_invalidate();
1585 static void pixel_format_message (VncState *vs) {
1586 char pad[3] = { 0, 0, 0 };
1588 vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1589 vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1591 #ifdef WORDS_BIGENDIAN
1592 vnc_write_u8(vs, 1); /* big-endian-flag */
1594 vnc_write_u8(vs, 0); /* big-endian-flag */
1596 vnc_write_u8(vs, 1); /* true-color-flag */
1597 vnc_write_u16(vs, vs->ds->surface->pf.rmax); /* red-max */
1598 vnc_write_u16(vs, vs->ds->surface->pf.gmax); /* green-max */
1599 vnc_write_u16(vs, vs->ds->surface->pf.bmax); /* blue-max */
1600 vnc_write_u8(vs, vs->ds->surface->pf.rshift); /* red-shift */
1601 vnc_write_u8(vs, vs->ds->surface->pf.gshift); /* green-shift */
1602 vnc_write_u8(vs, vs->ds->surface->pf.bshift); /* blue-shift */
1603 if (vs->ds->surface->pf.bits_per_pixel == 32)
1604 vs->send_hextile_tile = send_hextile_tile_32;
1605 else if (vs->ds->surface->pf.bits_per_pixel == 16)
1606 vs->send_hextile_tile = send_hextile_tile_16;
1607 else if (vs->ds->surface->pf.bits_per_pixel == 8)
1608 vs->send_hextile_tile = send_hextile_tile_8;
1609 vs->clientds = *(vs->ds->surface);
1610 vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1611 vs->write_pixels = vnc_write_pixels_copy;
1613 vnc_write(vs, pad, 3); /* padding */
1616 static void vnc_dpy_setdata(DisplayState *ds)
1618 /* We don't have to do anything */
1621 static void vnc_colordepth(VncState *vs)
1623 if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1624 /* Sending a WMVi message to notify the client*/
1625 vnc_write_u8(vs, 0); /* msg id */
1626 vnc_write_u8(vs, 0);
1627 vnc_write_u16(vs, 1); /* number of rects */
1628 vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1629 ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1630 pixel_format_message(vs);
1633 set_pixel_conversion(vs);
1637 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1647 set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1648 read_u8(data, 6), read_u8(data, 7),
1649 read_u16(data, 8), read_u16(data, 10),
1650 read_u16(data, 12), read_u8(data, 14),
1651 read_u8(data, 15), read_u8(data, 16));
1658 limit = read_u16(data, 2);
1660 return 4 + (limit * 4);
1662 limit = read_u16(data, 2);
1664 for (i = 0; i < limit; i++) {
1665 int32_t val = read_s32(data, 4 + (i * 4));
1666 memcpy(data + 4 + (i * 4), &val, sizeof(val));
1669 set_encodings(vs, (int32_t *)(data + 4), limit);
1675 framebuffer_update_request(vs,
1676 read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1677 read_u16(data, 6), read_u16(data, 8));
1683 key_event(vs, read_u8(data, 1), read_u32(data, 4));
1689 pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1696 uint32_t dlen = read_u32(data, 4);
1701 client_cut_text(vs, read_u32(data, 4), data + 8);
1707 switch (read_u8(data, 1)) {
1712 ext_key_event(vs, read_u16(data, 2),
1713 read_u32(data, 4), read_u32(data, 8));
1719 switch (read_u16 (data, 2)) {
1729 switch (read_u8(data, 4)) {
1730 case 0: vs->as.fmt = AUD_FMT_U8; break;
1731 case 1: vs->as.fmt = AUD_FMT_S8; break;
1732 case 2: vs->as.fmt = AUD_FMT_U16; break;
1733 case 3: vs->as.fmt = AUD_FMT_S16; break;
1734 case 4: vs->as.fmt = AUD_FMT_U32; break;
1735 case 5: vs->as.fmt = AUD_FMT_S32; break;
1737 printf("Invalid audio format %d\n", read_u8(data, 4));
1738 vnc_client_error(vs);
1741 vs->as.nchannels = read_u8(data, 5);
1742 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1743 printf("Invalid audio channel coount %d\n",
1745 vnc_client_error(vs);
1748 vs->as.freq = read_u32(data, 6);
1751 printf ("Invalid audio message %d\n", read_u8(data, 4));
1752 vnc_client_error(vs);
1758 printf("Msg: %d\n", read_u16(data, 0));
1759 vnc_client_error(vs);
1764 printf("Msg: %d\n", data[0]);
1765 vnc_client_error(vs);
1769 vnc_read_when(vs, protocol_client_msg, 1);
1773 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1778 vnc_write_u16(vs, ds_get_width(vs->ds));
1779 vnc_write_u16(vs, ds_get_height(vs->ds));
1781 pixel_format_message(vs);
1784 size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1786 size = snprintf(buf, sizeof(buf), "QEMU");
1788 vnc_write_u32(vs, size);
1789 vnc_write(vs, buf, size);
1792 vnc_read_when(vs, protocol_client_msg, 1);
1797 void start_client_init(VncState *vs)
1799 vnc_read_when(vs, protocol_client_init, 1);
1802 static void make_challenge(VncState *vs)
1806 srand(time(NULL)+getpid()+getpid()*987654+rand());
1808 for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1809 vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1812 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1814 unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1816 unsigned char key[8];
1818 if (!vs->vd->password || !vs->vd->password[0]) {
1819 VNC_DEBUG("No password configured on server");
1820 vnc_write_u32(vs, 1); /* Reject auth */
1821 if (vs->minor >= 8) {
1822 static const char err[] = "Authentication failed";
1823 vnc_write_u32(vs, sizeof(err));
1824 vnc_write(vs, err, sizeof(err));
1827 vnc_client_error(vs);
1831 memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1833 /* Calculate the expected challenge response */
1834 pwlen = strlen(vs->vd->password);
1835 for (i=0; i<sizeof(key); i++)
1836 key[i] = i<pwlen ? vs->vd->password[i] : 0;
1838 for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1839 des(response+j, response+j);
1841 /* Compare expected vs actual challenge response */
1842 if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1843 VNC_DEBUG("Client challenge reponse did not match\n");
1844 vnc_write_u32(vs, 1); /* Reject auth */
1845 if (vs->minor >= 8) {
1846 static const char err[] = "Authentication failed";
1847 vnc_write_u32(vs, sizeof(err));
1848 vnc_write(vs, err, sizeof(err));
1851 vnc_client_error(vs);
1853 VNC_DEBUG("Accepting VNC challenge response\n");
1854 vnc_write_u32(vs, 0); /* Accept auth */
1857 start_client_init(vs);
1862 void start_auth_vnc(VncState *vs)
1865 /* Send client a 'random' challenge */
1866 vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1869 vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1873 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
1875 /* We only advertise 1 auth scheme at a time, so client
1876 * must pick the one we sent. Verify this */
1877 if (data[0] != vs->vd->auth) { /* Reject auth */
1878 VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
1879 vnc_write_u32(vs, 1);
1880 if (vs->minor >= 8) {
1881 static const char err[] = "Authentication failed";
1882 vnc_write_u32(vs, sizeof(err));
1883 vnc_write(vs, err, sizeof(err));
1885 vnc_client_error(vs);
1886 } else { /* Accept requested auth */
1887 VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
1888 switch (vs->vd->auth) {
1890 VNC_DEBUG("Accept auth none\n");
1891 if (vs->minor >= 8) {
1892 vnc_write_u32(vs, 0); /* Accept auth completion */
1895 start_client_init(vs);
1899 VNC_DEBUG("Start VNC auth\n");
1903 #ifdef CONFIG_VNC_TLS
1904 case VNC_AUTH_VENCRYPT:
1905 VNC_DEBUG("Accept VeNCrypt auth\n");;
1906 start_auth_vencrypt(vs);
1908 #endif /* CONFIG_VNC_TLS */
1910 #ifdef CONFIG_VNC_SASL
1912 VNC_DEBUG("Accept SASL auth\n");
1913 start_auth_sasl(vs);
1915 #endif /* CONFIG_VNC_SASL */
1917 default: /* Should not be possible, but just in case */
1918 VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
1919 vnc_write_u8(vs, 1);
1920 if (vs->minor >= 8) {
1921 static const char err[] = "Authentication failed";
1922 vnc_write_u32(vs, sizeof(err));
1923 vnc_write(vs, err, sizeof(err));
1925 vnc_client_error(vs);
1931 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
1935 memcpy(local, version, 12);
1938 if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
1939 VNC_DEBUG("Malformed protocol version %s\n", local);
1940 vnc_client_error(vs);
1943 VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
1944 if (vs->major != 3 ||
1950 VNC_DEBUG("Unsupported client version\n");
1951 vnc_write_u32(vs, VNC_AUTH_INVALID);
1953 vnc_client_error(vs);
1956 /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
1957 * as equivalent to v3.3 by servers
1959 if (vs->minor == 4 || vs->minor == 5)
1962 if (vs->minor == 3) {
1963 if (vs->vd->auth == VNC_AUTH_NONE) {
1964 VNC_DEBUG("Tell client auth none\n");
1965 vnc_write_u32(vs, vs->vd->auth);
1967 start_client_init(vs);
1968 } else if (vs->vd->auth == VNC_AUTH_VNC) {
1969 VNC_DEBUG("Tell client VNC auth\n");
1970 vnc_write_u32(vs, vs->vd->auth);
1974 VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
1975 vnc_write_u32(vs, VNC_AUTH_INVALID);
1977 vnc_client_error(vs);
1980 VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
1981 vnc_write_u8(vs, 1); /* num auth */
1982 vnc_write_u8(vs, vs->vd->auth);
1983 vnc_read_when(vs, protocol_client_auth, 1);
1990 static void vnc_connect(VncDisplay *vd, int csock)
1992 VncState *vs = qemu_mallocz(sizeof(VncState));
1995 VNC_DEBUG("New client on socket %d\n", csock);
1997 socket_set_nonblock(vs->csock);
1998 qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2002 vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
2006 vs->as.freq = 44100;
2007 vs->as.nchannels = 2;
2008 vs->as.fmt = AUD_FMT_S16;
2009 vs->as.endianness = 0;
2012 vnc_write(vs, "RFB 003.008\n", 12);
2014 vnc_read_when(vs, protocol_version, 12);
2015 vnc_update_client(vs);
2018 vs->next = vd->clients;
2022 static void vnc_listen_read(void *opaque)
2024 VncDisplay *vs = opaque;
2025 struct sockaddr_in addr;
2026 socklen_t addrlen = sizeof(addr);
2031 int csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2033 vnc_connect(vs, csock);
2037 void vnc_display_init(DisplayState *ds)
2041 vs = qemu_mallocz(sizeof(VncState));
2042 dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2052 if (keyboard_layout)
2053 vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2055 vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2057 if (!vs->kbd_layout)
2060 dcl->dpy_copy = vnc_dpy_copy;
2061 dcl->dpy_update = vnc_dpy_update;
2062 dcl->dpy_resize = vnc_dpy_resize;
2063 dcl->dpy_setdata = vnc_dpy_setdata;
2064 register_displaychangelistener(ds, dcl);
2068 void vnc_display_close(DisplayState *ds)
2070 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2075 qemu_free(vs->display);
2078 if (vs->lsock != -1) {
2079 qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2083 vs->auth = VNC_AUTH_INVALID;
2084 #ifdef CONFIG_VNC_TLS
2085 vs->subauth = VNC_AUTH_INVALID;
2086 vs->tls.x509verify = 0;
2090 int vnc_display_password(DisplayState *ds, const char *password)
2092 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2095 qemu_free(vs->password);
2096 vs->password = NULL;
2098 if (password && password[0]) {
2099 if (!(vs->password = qemu_strdup(password)))
2106 int vnc_display_open(DisplayState *ds, const char *display)
2108 VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2109 const char *options;
2113 #ifdef CONFIG_VNC_TLS
2114 int tls = 0, x509 = 0;
2116 #ifdef CONFIG_VNC_SASL
2124 vnc_display_close(ds);
2125 if (strcmp(display, "none") == 0)
2128 if (!(vs->display = strdup(display)))
2132 while ((options = strchr(options, ','))) {
2134 if (strncmp(options, "password", 8) == 0) {
2135 password = 1; /* Require password auth */
2136 } else if (strncmp(options, "reverse", 7) == 0) {
2138 } else if (strncmp(options, "to=", 3) == 0) {
2139 to_port = atoi(options+3) + 5900;
2140 #ifdef CONFIG_VNC_SASL
2141 } else if (strncmp(options, "sasl", 4) == 0) {
2142 sasl = 1; /* Require SASL auth */
2144 #ifdef CONFIG_VNC_TLS
2145 } else if (strncmp(options, "tls", 3) == 0) {
2146 tls = 1; /* Require TLS */
2147 } else if (strncmp(options, "x509", 4) == 0) {
2149 x509 = 1; /* Require x509 certificates */
2150 if (strncmp(options, "x509verify", 10) == 0)
2151 vs->tls.x509verify = 1; /* ...and verify client certs */
2153 /* Now check for 'x509=/some/path' postfix
2154 * and use that to setup x509 certificate/key paths */
2155 start = strchr(options, '=');
2156 end = strchr(options, ',');
2157 if (start && (!end || (start < end))) {
2158 int len = end ? end-(start+1) : strlen(start+1);
2159 char *path = qemu_strndup(start + 1, len);
2161 VNC_DEBUG("Trying certificate path '%s'\n", path);
2162 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2163 fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2165 qemu_free(vs->display);
2171 fprintf(stderr, "No certificate path provided\n");
2172 qemu_free(vs->display);
2177 } else if (strncmp(options, "acl", 3) == 0) {
2182 #ifdef CONFIG_VNC_TLS
2183 if (acl && x509 && vs->tls.x509verify) {
2184 if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2185 fprintf(stderr, "Failed to create x509 dname ACL\n");
2190 #ifdef CONFIG_VNC_SASL
2192 if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2193 fprintf(stderr, "Failed to create username ACL\n");
2200 * Combinations we support here:
2202 * - no-auth (clear text, no auth)
2203 * - password (clear text, weak auth)
2204 * - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
2205 * - tls (encrypt, weak anonymous creds, no auth)
2206 * - tls + password (encrypt, weak anonymous creds, weak auth)
2207 * - tls + sasl (encrypt, weak anonymous creds, good auth)
2208 * - tls + x509 (encrypt, good x509 creds, no auth)
2209 * - tls + x509 + password (encrypt, good x509 creds, weak auth)
2210 * - tls + x509 + sasl (encrypt, good x509 creds, good auth)
2212 * NB1. TLS is a stackable auth scheme.
2213 * NB2. the x509 schemes have option to validate a client cert dname
2216 #ifdef CONFIG_VNC_TLS
2218 vs->auth = VNC_AUTH_VENCRYPT;
2220 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2221 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2223 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2224 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2227 #endif /* CONFIG_VNC_TLS */
2228 VNC_DEBUG("Initializing VNC server with password auth\n");
2229 vs->auth = VNC_AUTH_VNC;
2230 #ifdef CONFIG_VNC_TLS
2231 vs->subauth = VNC_AUTH_INVALID;
2233 #endif /* CONFIG_VNC_TLS */
2234 #ifdef CONFIG_VNC_SASL
2236 #ifdef CONFIG_VNC_TLS
2238 vs->auth = VNC_AUTH_VENCRYPT;
2240 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2241 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2243 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2244 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2247 #endif /* CONFIG_VNC_TLS */
2248 VNC_DEBUG("Initializing VNC server with SASL auth\n");
2249 vs->auth = VNC_AUTH_SASL;
2250 #ifdef CONFIG_VNC_TLS
2251 vs->subauth = VNC_AUTH_INVALID;
2253 #endif /* CONFIG_VNC_TLS */
2254 #endif /* CONFIG_VNC_SASL */
2256 #ifdef CONFIG_VNC_TLS
2258 vs->auth = VNC_AUTH_VENCRYPT;
2260 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2261 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2263 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2264 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2268 VNC_DEBUG("Initializing VNC server with no auth\n");
2269 vs->auth = VNC_AUTH_NONE;
2270 #ifdef CONFIG_VNC_TLS
2271 vs->subauth = VNC_AUTH_INVALID;
2276 #ifdef CONFIG_VNC_SASL
2277 if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2278 fprintf(stderr, "Failed to initialize SASL auth %s",
2279 sasl_errstring(saslErr, NULL, NULL));
2287 /* connect to viewer */
2288 if (strncmp(display, "unix:", 5) == 0)
2289 vs->lsock = unix_connect(display+5);
2291 vs->lsock = inet_connect(display, SOCK_STREAM);
2292 if (-1 == vs->lsock) {
2297 int csock = vs->lsock;
2299 vnc_connect(vs, csock);
2304 /* listen for connects */
2306 dpy = qemu_malloc(256);
2307 if (strncmp(display, "unix:", 5) == 0) {
2308 pstrcpy(dpy, 256, "unix:");
2309 vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2311 vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2313 if (-1 == vs->lsock) {
2321 return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);