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