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