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