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