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