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