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