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