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