xref: /openbmc/qemu/ui/vnc.c (revision de3f7de7f4e257ce44cdabb90f5f17ee99624557)
13e230dd2SCorentin Chary /*
23e230dd2SCorentin Chary  * QEMU VNC display driver
33e230dd2SCorentin Chary  *
43e230dd2SCorentin Chary  * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
53e230dd2SCorentin Chary  * Copyright (C) 2006 Fabrice Bellard
63e230dd2SCorentin Chary  * Copyright (C) 2009 Red Hat, Inc
73e230dd2SCorentin Chary  *
83e230dd2SCorentin Chary  * Permission is hereby granted, free of charge, to any person obtaining a copy
93e230dd2SCorentin Chary  * of this software and associated documentation files (the "Software"), to deal
103e230dd2SCorentin Chary  * in the Software without restriction, including without limitation the rights
113e230dd2SCorentin Chary  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
123e230dd2SCorentin Chary  * copies of the Software, and to permit persons to whom the Software is
133e230dd2SCorentin Chary  * furnished to do so, subject to the following conditions:
143e230dd2SCorentin Chary  *
153e230dd2SCorentin Chary  * The above copyright notice and this permission notice shall be included in
163e230dd2SCorentin Chary  * all copies or substantial portions of the Software.
173e230dd2SCorentin Chary  *
183e230dd2SCorentin Chary  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
193e230dd2SCorentin Chary  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
203e230dd2SCorentin Chary  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
213e230dd2SCorentin Chary  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
223e230dd2SCorentin Chary  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
233e230dd2SCorentin Chary  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
243e230dd2SCorentin Chary  * THE SOFTWARE.
253e230dd2SCorentin Chary  */
263e230dd2SCorentin Chary 
273e230dd2SCorentin Chary #include "vnc.h"
28bd023f95SCorentin Chary #include "vnc-jobs.h"
2940066175SGerd Hoffmann #include "trace.h"
301d0d59feSGerd Hoffmann #include "hw/qdev.h"
319c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
32d49b6836SMarkus Armbruster #include "qemu/error-report.h"
331de7afc9SPaolo Bonzini #include "qemu/sockets.h"
341de7afc9SPaolo Bonzini #include "qemu/timer.h"
351de7afc9SPaolo Bonzini #include "qemu/acl.h"
364db14629SGerd Hoffmann #include "qemu/config-file.h"
37cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
387b1b5d19SPaolo Bonzini #include "qapi/qmp/types.h"
392b54aa87SLuiz Capitulino #include "qmp-commands.h"
401de7afc9SPaolo Bonzini #include "qemu/osdep.h"
418d447d10SGerd Hoffmann #include "ui/input.h"
42fb6ba0d5SWenchao Xia #include "qapi-event.h"
438e9b0d24SDaniel P. Berrange #include "crypto/hash.h"
443e305e4aSDaniel P. Berrange #include "crypto/tlscredsanon.h"
453e305e4aSDaniel P. Berrange #include "crypto/tlscredsx509.h"
463e305e4aSDaniel P. Berrange #include "qom/object_interfaces.h"
473e230dd2SCorentin Chary 
480f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
493e230dd2SCorentin Chary #define VNC_REFRESH_INTERVAL_INC  50
500f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
51999342a0SCorentin Chary static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
52999342a0SCorentin Chary static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
533e230dd2SCorentin Chary 
543e230dd2SCorentin Chary #include "vnc_keysym.h"
55800567a6SDaniel P. Berrange #include "crypto/cipher.h"
563e230dd2SCorentin Chary 
57d616ccc5SGerd Hoffmann static QTAILQ_HEAD(, VncDisplay) vnc_displays =
58d616ccc5SGerd Hoffmann     QTAILQ_HEAD_INITIALIZER(vnc_displays);
593e230dd2SCorentin Chary 
603e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs);
617bc9318bSGerd Hoffmann static void vnc_release_modifiers(VncState *vs);
623e230dd2SCorentin Chary 
638cf36489SGerd Hoffmann static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
648cf36489SGerd Hoffmann {
658cf36489SGerd Hoffmann #ifdef _VNC_DEBUG
668cf36489SGerd Hoffmann     static const char *mn[] = {
678cf36489SGerd Hoffmann         [0]                           = "undefined",
688cf36489SGerd Hoffmann         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
698cf36489SGerd Hoffmann         [VNC_SHARE_MODE_SHARED]       = "shared",
708cf36489SGerd Hoffmann         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
718cf36489SGerd Hoffmann         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
728cf36489SGerd Hoffmann     };
738cf36489SGerd Hoffmann     fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
748cf36489SGerd Hoffmann             vs->csock, mn[vs->share_mode], mn[mode]);
758cf36489SGerd Hoffmann #endif
768cf36489SGerd Hoffmann 
77e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
78e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
79e5f34cddSGerd Hoffmann         vs->vd->num_connecting--;
80e5f34cddSGerd Hoffmann         break;
81e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
82e5f34cddSGerd Hoffmann         vs->vd->num_shared--;
83e5f34cddSGerd Hoffmann         break;
84e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
858cf36489SGerd Hoffmann         vs->vd->num_exclusive--;
86e5f34cddSGerd Hoffmann         break;
87e5f34cddSGerd Hoffmann     default:
88e5f34cddSGerd Hoffmann         break;
898cf36489SGerd Hoffmann     }
90e5f34cddSGerd Hoffmann 
918cf36489SGerd Hoffmann     vs->share_mode = mode;
92e5f34cddSGerd Hoffmann 
93e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
94e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
95e5f34cddSGerd Hoffmann         vs->vd->num_connecting++;
96e5f34cddSGerd Hoffmann         break;
97e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
98e5f34cddSGerd Hoffmann         vs->vd->num_shared++;
99e5f34cddSGerd Hoffmann         break;
100e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
1018cf36489SGerd Hoffmann         vs->vd->num_exclusive++;
102e5f34cddSGerd Hoffmann         break;
103e5f34cddSGerd Hoffmann     default:
104e5f34cddSGerd Hoffmann         break;
1058cf36489SGerd Hoffmann     }
1068cf36489SGerd Hoffmann }
1078cf36489SGerd Hoffmann 
1083e230dd2SCorentin Chary static char *addr_to_string(const char *format,
1093e230dd2SCorentin Chary                             struct sockaddr_storage *sa,
1103e230dd2SCorentin Chary                             socklen_t salen) {
1113e230dd2SCorentin Chary     char *addr;
1123e230dd2SCorentin Chary     char host[NI_MAXHOST];
1133e230dd2SCorentin Chary     char serv[NI_MAXSERV];
1143e230dd2SCorentin Chary     int err;
1153e230dd2SCorentin Chary     size_t addrlen;
1163e230dd2SCorentin Chary 
1173e230dd2SCorentin Chary     if ((err = getnameinfo((struct sockaddr *)sa, salen,
1183e230dd2SCorentin Chary                            host, sizeof(host),
1193e230dd2SCorentin Chary                            serv, sizeof(serv),
1203e230dd2SCorentin Chary                            NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
1213e230dd2SCorentin Chary         VNC_DEBUG("Cannot resolve address %d: %s\n",
1223e230dd2SCorentin Chary                   err, gai_strerror(err));
1233e230dd2SCorentin Chary         return NULL;
1243e230dd2SCorentin Chary     }
1253e230dd2SCorentin Chary 
1263e230dd2SCorentin Chary     /* Enough for the existing format + the 2 vars we're
1273e230dd2SCorentin Chary      * substituting in. */
1283e230dd2SCorentin Chary     addrlen = strlen(format) + strlen(host) + strlen(serv);
1297267c094SAnthony Liguori     addr = g_malloc(addrlen + 1);
1303e230dd2SCorentin Chary     snprintf(addr, addrlen, format, host, serv);
1313e230dd2SCorentin Chary     addr[addrlen] = '\0';
1323e230dd2SCorentin Chary 
1333e230dd2SCorentin Chary     return addr;
1343e230dd2SCorentin Chary }
1353e230dd2SCorentin Chary 
1363e230dd2SCorentin Chary 
1373e230dd2SCorentin Chary char *vnc_socket_local_addr(const char *format, int fd) {
1383e230dd2SCorentin Chary     struct sockaddr_storage sa;
1393e230dd2SCorentin Chary     socklen_t salen;
1403e230dd2SCorentin Chary 
1413e230dd2SCorentin Chary     salen = sizeof(sa);
1423e230dd2SCorentin Chary     if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
1433e230dd2SCorentin Chary         return NULL;
1443e230dd2SCorentin Chary 
1453e230dd2SCorentin Chary     return addr_to_string(format, &sa, salen);
1463e230dd2SCorentin Chary }
1473e230dd2SCorentin Chary 
1483e230dd2SCorentin Chary char *vnc_socket_remote_addr(const char *format, int fd) {
1493e230dd2SCorentin Chary     struct sockaddr_storage sa;
1503e230dd2SCorentin Chary     socklen_t salen;
1513e230dd2SCorentin Chary 
1523e230dd2SCorentin Chary     salen = sizeof(sa);
1533e230dd2SCorentin Chary     if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
1543e230dd2SCorentin Chary         return NULL;
1553e230dd2SCorentin Chary 
1563e230dd2SCorentin Chary     return addr_to_string(format, &sa, salen);
1573e230dd2SCorentin Chary }
1583e230dd2SCorentin Chary 
15998481bfcSEric Blake static void vnc_init_basic_info(struct sockaddr_storage *sa,
16098481bfcSEric Blake                                 socklen_t salen,
16198481bfcSEric Blake                                 VncBasicInfo *info,
16298481bfcSEric Blake                                 Error **errp)
1633e230dd2SCorentin Chary {
1643e230dd2SCorentin Chary     char host[NI_MAXHOST];
1653e230dd2SCorentin Chary     char serv[NI_MAXSERV];
1663e230dd2SCorentin Chary     int err;
1673e230dd2SCorentin Chary 
1683e230dd2SCorentin Chary     if ((err = getnameinfo((struct sockaddr *)sa, salen,
1693e230dd2SCorentin Chary                            host, sizeof(host),
1703e230dd2SCorentin Chary                            serv, sizeof(serv),
1713e230dd2SCorentin Chary                            NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
17298481bfcSEric Blake         error_setg(errp, "Cannot resolve address: %s",
17398481bfcSEric Blake                    gai_strerror(err));
17498481bfcSEric Blake         return;
1753e230dd2SCorentin Chary     }
1763e230dd2SCorentin Chary 
177fb6ba0d5SWenchao Xia     info->host = g_strdup(host);
178fb6ba0d5SWenchao Xia     info->service = g_strdup(serv);
179fb6ba0d5SWenchao Xia     info->family = inet_netfamily(sa->ss_family);
1803e230dd2SCorentin Chary }
1813e230dd2SCorentin Chary 
18298481bfcSEric Blake static void vnc_init_basic_info_from_server_addr(int fd, VncBasicInfo *info,
18398481bfcSEric Blake                                                  Error **errp)
1843e230dd2SCorentin Chary {
1853e230dd2SCorentin Chary     struct sockaddr_storage sa;
1863e230dd2SCorentin Chary     socklen_t salen;
1873e230dd2SCorentin Chary 
1883e230dd2SCorentin Chary     salen = sizeof(sa);
1893e230dd2SCorentin Chary     if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
19098481bfcSEric Blake         error_setg_errno(errp, errno, "getsockname failed");
19198481bfcSEric Blake         return;
1923e230dd2SCorentin Chary     }
1933e230dd2SCorentin Chary 
19498481bfcSEric Blake     vnc_init_basic_info(&sa, salen, info, errp);
1953e230dd2SCorentin Chary }
1963e230dd2SCorentin Chary 
19798481bfcSEric Blake static void vnc_init_basic_info_from_remote_addr(int fd, VncBasicInfo *info,
19898481bfcSEric Blake                                                  Error **errp)
1993e230dd2SCorentin Chary {
2003e230dd2SCorentin Chary     struct sockaddr_storage sa;
2013e230dd2SCorentin Chary     socklen_t salen;
2023e230dd2SCorentin Chary 
2033e230dd2SCorentin Chary     salen = sizeof(sa);
2043e230dd2SCorentin Chary     if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
20598481bfcSEric Blake         error_setg_errno(errp, errno, "getpeername failed");
20698481bfcSEric Blake         return;
2073e230dd2SCorentin Chary     }
2083e230dd2SCorentin Chary 
20998481bfcSEric Blake     vnc_init_basic_info(&sa, salen, info, errp);
2103e230dd2SCorentin Chary }
2113e230dd2SCorentin Chary 
2123e230dd2SCorentin Chary static const char *vnc_auth_name(VncDisplay *vd) {
2133e230dd2SCorentin Chary     switch (vd->auth) {
2143e230dd2SCorentin Chary     case VNC_AUTH_INVALID:
2153e230dd2SCorentin Chary         return "invalid";
2163e230dd2SCorentin Chary     case VNC_AUTH_NONE:
2173e230dd2SCorentin Chary         return "none";
2183e230dd2SCorentin Chary     case VNC_AUTH_VNC:
2193e230dd2SCorentin Chary         return "vnc";
2203e230dd2SCorentin Chary     case VNC_AUTH_RA2:
2213e230dd2SCorentin Chary         return "ra2";
2223e230dd2SCorentin Chary     case VNC_AUTH_RA2NE:
2233e230dd2SCorentin Chary         return "ra2ne";
2243e230dd2SCorentin Chary     case VNC_AUTH_TIGHT:
2253e230dd2SCorentin Chary         return "tight";
2263e230dd2SCorentin Chary     case VNC_AUTH_ULTRA:
2273e230dd2SCorentin Chary         return "ultra";
2283e230dd2SCorentin Chary     case VNC_AUTH_TLS:
2293e230dd2SCorentin Chary         return "tls";
2303e230dd2SCorentin Chary     case VNC_AUTH_VENCRYPT:
2313e230dd2SCorentin Chary         switch (vd->subauth) {
2323e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_PLAIN:
2333e230dd2SCorentin Chary             return "vencrypt+plain";
2343e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSNONE:
2353e230dd2SCorentin Chary             return "vencrypt+tls+none";
2363e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSVNC:
2373e230dd2SCorentin Chary             return "vencrypt+tls+vnc";
2383e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSPLAIN:
2393e230dd2SCorentin Chary             return "vencrypt+tls+plain";
2403e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509NONE:
2413e230dd2SCorentin Chary             return "vencrypt+x509+none";
2423e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509VNC:
2433e230dd2SCorentin Chary             return "vencrypt+x509+vnc";
2443e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509PLAIN:
2453e230dd2SCorentin Chary             return "vencrypt+x509+plain";
2463e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSSASL:
2473e230dd2SCorentin Chary             return "vencrypt+tls+sasl";
2483e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509SASL:
2493e230dd2SCorentin Chary             return "vencrypt+x509+sasl";
2503e230dd2SCorentin Chary         default:
2513e230dd2SCorentin Chary             return "vencrypt";
2523e230dd2SCorentin Chary         }
2533e230dd2SCorentin Chary     case VNC_AUTH_SASL:
2543e230dd2SCorentin Chary         return "sasl";
2553e230dd2SCorentin Chary     }
2563e230dd2SCorentin Chary     return "unknown";
2573e230dd2SCorentin Chary }
2583e230dd2SCorentin Chary 
259d616ccc5SGerd Hoffmann static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
2603e230dd2SCorentin Chary {
261fb6ba0d5SWenchao Xia     VncServerInfo *info;
26298481bfcSEric Blake     Error *err = NULL;
2633e230dd2SCorentin Chary 
264fb6ba0d5SWenchao Xia     info = g_malloc(sizeof(*info));
265ddf21908SEric Blake     vnc_init_basic_info_from_server_addr(vd->lsock,
266ddf21908SEric Blake                                          qapi_VncServerInfo_base(info), &err);
267fb6ba0d5SWenchao Xia     info->has_auth = true;
268d616ccc5SGerd Hoffmann     info->auth = g_strdup(vnc_auth_name(vd));
26998481bfcSEric Blake     if (err) {
27098481bfcSEric Blake         qapi_free_VncServerInfo(info);
27198481bfcSEric Blake         info = NULL;
27298481bfcSEric Blake         error_free(err);
27398481bfcSEric Blake     }
274fb6ba0d5SWenchao Xia     return info;
2753e230dd2SCorentin Chary }
2763e230dd2SCorentin Chary 
2773e230dd2SCorentin Chary static void vnc_client_cache_auth(VncState *client)
2783e230dd2SCorentin Chary {
2793e230dd2SCorentin Chary     if (!client->info) {
2803e230dd2SCorentin Chary         return;
2813e230dd2SCorentin Chary     }
2823e230dd2SCorentin Chary 
2833e305e4aSDaniel P. Berrange     if (client->tls) {
2843e305e4aSDaniel P. Berrange         client->info->x509_dname =
2853e305e4aSDaniel P. Berrange             qcrypto_tls_session_get_peer_name(client->tls);
2863e305e4aSDaniel P. Berrange         client->info->has_x509_dname =
2873e305e4aSDaniel P. Berrange             client->info->x509_dname != NULL;
2883e230dd2SCorentin Chary     }
2893e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
2903e230dd2SCorentin Chary     if (client->sasl.conn &&
2913e230dd2SCorentin Chary         client->sasl.username) {
292fb6ba0d5SWenchao Xia         client->info->has_sasl_username = true;
293fb6ba0d5SWenchao Xia         client->info->sasl_username = g_strdup(client->sasl.username);
2943e230dd2SCorentin Chary     }
2953e230dd2SCorentin Chary #endif
2963e230dd2SCorentin Chary }
2973e230dd2SCorentin Chary 
2983e230dd2SCorentin Chary static void vnc_client_cache_addr(VncState *client)
2993e230dd2SCorentin Chary {
30098481bfcSEric Blake     Error *err = NULL;
3013e230dd2SCorentin Chary 
302fb6ba0d5SWenchao Xia     client->info = g_malloc0(sizeof(*client->info));
303ddf21908SEric Blake     vnc_init_basic_info_from_remote_addr(client->csock,
304ddf21908SEric Blake                                          qapi_VncClientInfo_base(client->info),
30598481bfcSEric Blake                                          &err);
30698481bfcSEric Blake     if (err) {
30798481bfcSEric Blake         qapi_free_VncClientInfo(client->info);
30898481bfcSEric Blake         client->info = NULL;
30998481bfcSEric Blake         error_free(err);
310fb6ba0d5SWenchao Xia     }
3113e230dd2SCorentin Chary }
3123e230dd2SCorentin Chary 
313fb6ba0d5SWenchao Xia static void vnc_qmp_event(VncState *vs, QAPIEvent event)
3143e230dd2SCorentin Chary {
315fb6ba0d5SWenchao Xia     VncServerInfo *si;
3163e230dd2SCorentin Chary 
3173e230dd2SCorentin Chary     if (!vs->info) {
3183e230dd2SCorentin Chary         return;
3193e230dd2SCorentin Chary     }
3203e230dd2SCorentin Chary 
321d616ccc5SGerd Hoffmann     si = vnc_server_info_get(vs->vd);
322fb6ba0d5SWenchao Xia     if (!si) {
3233e230dd2SCorentin Chary         return;
3243e230dd2SCorentin Chary     }
3253e230dd2SCorentin Chary 
326fb6ba0d5SWenchao Xia     switch (event) {
327fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_CONNECTED:
328ddf21908SEric Blake         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info),
329ddf21908SEric Blake                                       &error_abort);
330fb6ba0d5SWenchao Xia         break;
331fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_INITIALIZED:
332fb6ba0d5SWenchao Xia         qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
333fb6ba0d5SWenchao Xia         break;
334fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_DISCONNECTED:
335fb6ba0d5SWenchao Xia         qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
336fb6ba0d5SWenchao Xia         break;
337fb6ba0d5SWenchao Xia     default:
338fb6ba0d5SWenchao Xia         break;
339fb6ba0d5SWenchao Xia     }
3403e230dd2SCorentin Chary 
341fb6ba0d5SWenchao Xia     qapi_free_VncServerInfo(si);
3423e230dd2SCorentin Chary }
3433e230dd2SCorentin Chary 
3442b54aa87SLuiz Capitulino static VncClientInfo *qmp_query_vnc_client(const VncState *client)
3453e230dd2SCorentin Chary {
3462b54aa87SLuiz Capitulino     struct sockaddr_storage sa;
3472b54aa87SLuiz Capitulino     socklen_t salen = sizeof(sa);
3482b54aa87SLuiz Capitulino     char host[NI_MAXHOST];
3492b54aa87SLuiz Capitulino     char serv[NI_MAXSERV];
3502b54aa87SLuiz Capitulino     VncClientInfo *info;
3513e230dd2SCorentin Chary 
3522b54aa87SLuiz Capitulino     if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
3532b54aa87SLuiz Capitulino         return NULL;
3542b54aa87SLuiz Capitulino     }
3552b54aa87SLuiz Capitulino 
3562b54aa87SLuiz Capitulino     if (getnameinfo((struct sockaddr *)&sa, salen,
3572b54aa87SLuiz Capitulino                     host, sizeof(host),
3582b54aa87SLuiz Capitulino                     serv, sizeof(serv),
3592b54aa87SLuiz Capitulino                     NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
3602b54aa87SLuiz Capitulino         return NULL;
3612b54aa87SLuiz Capitulino     }
3622b54aa87SLuiz Capitulino 
3632b54aa87SLuiz Capitulino     info = g_malloc0(sizeof(*info));
364ddf21908SEric Blake     info->host = g_strdup(host);
365ddf21908SEric Blake     info->service = g_strdup(serv);
366ddf21908SEric Blake     info->family = inet_netfamily(sa.ss_family);
367ddf21908SEric Blake     info->websocket = client->websocket;
3683e230dd2SCorentin Chary 
3693e305e4aSDaniel P. Berrange     if (client->tls) {
3703e305e4aSDaniel P. Berrange         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
3713e305e4aSDaniel P. Berrange         info->has_x509_dname = info->x509_dname != NULL;
3722b54aa87SLuiz Capitulino     }
3733e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
3742b54aa87SLuiz Capitulino     if (client->sasl.conn && client->sasl.username) {
3752b54aa87SLuiz Capitulino         info->has_sasl_username = true;
3762b54aa87SLuiz Capitulino         info->sasl_username = g_strdup(client->sasl.username);
3772b54aa87SLuiz Capitulino     }
3783e230dd2SCorentin Chary #endif
3792b54aa87SLuiz Capitulino 
3802b54aa87SLuiz Capitulino     return info;
3813e230dd2SCorentin Chary }
3823e230dd2SCorentin Chary 
383d616ccc5SGerd Hoffmann static VncDisplay *vnc_display_find(const char *id)
384d616ccc5SGerd Hoffmann {
385d616ccc5SGerd Hoffmann     VncDisplay *vd;
386d616ccc5SGerd Hoffmann 
387d616ccc5SGerd Hoffmann     if (id == NULL) {
388d616ccc5SGerd Hoffmann         return QTAILQ_FIRST(&vnc_displays);
389d616ccc5SGerd Hoffmann     }
390d616ccc5SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
391d616ccc5SGerd Hoffmann         if (strcmp(id, vd->id) == 0) {
392d616ccc5SGerd Hoffmann             return vd;
393d616ccc5SGerd Hoffmann         }
394d616ccc5SGerd Hoffmann     }
395d616ccc5SGerd Hoffmann     return NULL;
396d616ccc5SGerd Hoffmann }
397d616ccc5SGerd Hoffmann 
3982d29a436SGerd Hoffmann static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
3992d29a436SGerd Hoffmann {
4002d29a436SGerd Hoffmann     VncClientInfoList *cinfo, *prev = NULL;
4012d29a436SGerd Hoffmann     VncState *client;
4022d29a436SGerd Hoffmann 
4032d29a436SGerd Hoffmann     QTAILQ_FOREACH(client, &vd->clients, next) {
4042d29a436SGerd Hoffmann         cinfo = g_new0(VncClientInfoList, 1);
4052d29a436SGerd Hoffmann         cinfo->value = qmp_query_vnc_client(client);
4062d29a436SGerd Hoffmann         cinfo->next = prev;
4072d29a436SGerd Hoffmann         prev = cinfo;
4082d29a436SGerd Hoffmann     }
4092d29a436SGerd Hoffmann     return prev;
4102d29a436SGerd Hoffmann }
4112d29a436SGerd Hoffmann 
4122b54aa87SLuiz Capitulino VncInfo *qmp_query_vnc(Error **errp)
4133e230dd2SCorentin Chary {
4142b54aa87SLuiz Capitulino     VncInfo *info = g_malloc0(sizeof(*info));
415d616ccc5SGerd Hoffmann     VncDisplay *vd = vnc_display_find(NULL);
4163e230dd2SCorentin Chary 
417bf7aa45eSGerd Hoffmann     if (vd == NULL || !vd->enabled) {
4182b54aa87SLuiz Capitulino         info->enabled = false;
4193e230dd2SCorentin Chary     } else {
4202b54aa87SLuiz Capitulino         struct sockaddr_storage sa;
4212b54aa87SLuiz Capitulino         socklen_t salen = sizeof(sa);
4222b54aa87SLuiz Capitulino         char host[NI_MAXHOST];
4232b54aa87SLuiz Capitulino         char serv[NI_MAXSERV];
4243e230dd2SCorentin Chary 
4252b54aa87SLuiz Capitulino         info->enabled = true;
4262b54aa87SLuiz Capitulino 
4272b54aa87SLuiz Capitulino         /* for compatibility with the original command */
4282b54aa87SLuiz Capitulino         info->has_clients = true;
4292d29a436SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
4303e230dd2SCorentin Chary 
431d616ccc5SGerd Hoffmann         if (vd->lsock == -1) {
432417b0b88SPaolo Bonzini             return info;
433417b0b88SPaolo Bonzini         }
434417b0b88SPaolo Bonzini 
435d616ccc5SGerd Hoffmann         if (getsockname(vd->lsock, (struct sockaddr *)&sa,
4362b54aa87SLuiz Capitulino                         &salen) == -1) {
437c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_UNDEFINED_ERROR);
4382b54aa87SLuiz Capitulino             goto out_error;
4392b54aa87SLuiz Capitulino         }
4403e230dd2SCorentin Chary 
4412b54aa87SLuiz Capitulino         if (getnameinfo((struct sockaddr *)&sa, salen,
4422b54aa87SLuiz Capitulino                         host, sizeof(host),
4432b54aa87SLuiz Capitulino                         serv, sizeof(serv),
4442b54aa87SLuiz Capitulino                         NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
445c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_UNDEFINED_ERROR);
4462b54aa87SLuiz Capitulino             goto out_error;
4473e230dd2SCorentin Chary         }
4482b54aa87SLuiz Capitulino 
4492b54aa87SLuiz Capitulino         info->has_host = true;
4502b54aa87SLuiz Capitulino         info->host = g_strdup(host);
4512b54aa87SLuiz Capitulino 
4522b54aa87SLuiz Capitulino         info->has_service = true;
4532b54aa87SLuiz Capitulino         info->service = g_strdup(serv);
4542b54aa87SLuiz Capitulino 
4552b54aa87SLuiz Capitulino         info->has_family = true;
456a589569fSWenchao Xia         info->family = inet_netfamily(sa.ss_family);
4572b54aa87SLuiz Capitulino 
4582b54aa87SLuiz Capitulino         info->has_auth = true;
459d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4603e230dd2SCorentin Chary     }
4612b54aa87SLuiz Capitulino 
4622b54aa87SLuiz Capitulino     return info;
4632b54aa87SLuiz Capitulino 
4642b54aa87SLuiz Capitulino out_error:
4652b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4662b54aa87SLuiz Capitulino     return NULL;
4673e230dd2SCorentin Chary }
4683e230dd2SCorentin Chary 
469df887684SGerd Hoffmann static VncBasicInfoList *qmp_query_server_entry(int socket,
4704478aa76SGerd Hoffmann                                                 bool websocket,
471df887684SGerd Hoffmann                                                 VncBasicInfoList *prev)
472df887684SGerd Hoffmann {
473df887684SGerd Hoffmann     VncBasicInfoList *list;
474df887684SGerd Hoffmann     VncBasicInfo *info;
475df887684SGerd Hoffmann     struct sockaddr_storage sa;
476df887684SGerd Hoffmann     socklen_t salen = sizeof(sa);
477df887684SGerd Hoffmann     char host[NI_MAXHOST];
478df887684SGerd Hoffmann     char serv[NI_MAXSERV];
479df887684SGerd Hoffmann 
480df887684SGerd Hoffmann     if (getsockname(socket, (struct sockaddr *)&sa, &salen) < 0 ||
481df887684SGerd Hoffmann         getnameinfo((struct sockaddr *)&sa, salen,
482df887684SGerd Hoffmann                     host, sizeof(host), serv, sizeof(serv),
483df887684SGerd Hoffmann                     NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
484df887684SGerd Hoffmann         return prev;
485df887684SGerd Hoffmann     }
486df887684SGerd Hoffmann 
487df887684SGerd Hoffmann     info = g_new0(VncBasicInfo, 1);
488df887684SGerd Hoffmann     info->host = g_strdup(host);
489df887684SGerd Hoffmann     info->service = g_strdup(serv);
490df887684SGerd Hoffmann     info->family = inet_netfamily(sa.ss_family);
4914478aa76SGerd Hoffmann     info->websocket = websocket;
492df887684SGerd Hoffmann 
493df887684SGerd Hoffmann     list = g_new0(VncBasicInfoList, 1);
494df887684SGerd Hoffmann     list->value = info;
495df887684SGerd Hoffmann     list->next = prev;
496df887684SGerd Hoffmann     return list;
497df887684SGerd Hoffmann }
498df887684SGerd Hoffmann 
499df887684SGerd Hoffmann static void qmp_query_auth(VncDisplay *vd, VncInfo2 *info)
500df887684SGerd Hoffmann {
501df887684SGerd Hoffmann     switch (vd->auth) {
502df887684SGerd Hoffmann     case VNC_AUTH_VNC:
503df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_VNC;
504df887684SGerd Hoffmann         break;
505df887684SGerd Hoffmann     case VNC_AUTH_RA2:
506df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_RA2;
507df887684SGerd Hoffmann         break;
508df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
509df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_RA2NE;
510df887684SGerd Hoffmann         break;
511df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
512df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_TIGHT;
513df887684SGerd Hoffmann         break;
514df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
515df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_ULTRA;
516df887684SGerd Hoffmann         break;
517df887684SGerd Hoffmann     case VNC_AUTH_TLS:
518df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_TLS;
519df887684SGerd Hoffmann         break;
520df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
521df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_VENCRYPT;
522df887684SGerd Hoffmann         info->has_vencrypt = true;
523df887684SGerd Hoffmann         switch (vd->subauth) {
524df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
525df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
526df887684SGerd Hoffmann             break;
527df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
528df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
529df887684SGerd Hoffmann             break;
530df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
531df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
532df887684SGerd Hoffmann             break;
533df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
534df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
535df887684SGerd Hoffmann             break;
536df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
537df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
538df887684SGerd Hoffmann             break;
539df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
540df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
541df887684SGerd Hoffmann             break;
542df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
543df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
544df887684SGerd Hoffmann             break;
545df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
546df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
547df887684SGerd Hoffmann             break;
548df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
549df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
550df887684SGerd Hoffmann             break;
551df887684SGerd Hoffmann         default:
552df887684SGerd Hoffmann             info->has_vencrypt = false;
553df887684SGerd Hoffmann             break;
554df887684SGerd Hoffmann         }
555df887684SGerd Hoffmann         break;
556df887684SGerd Hoffmann     case VNC_AUTH_SASL:
557df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_SASL;
558df887684SGerd Hoffmann         break;
559df887684SGerd Hoffmann     case VNC_AUTH_NONE:
560df887684SGerd Hoffmann     default:
561df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_NONE;
562df887684SGerd Hoffmann         break;
563df887684SGerd Hoffmann     }
564df887684SGerd Hoffmann }
565df887684SGerd Hoffmann 
566df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
567df887684SGerd Hoffmann {
568df887684SGerd Hoffmann     VncInfo2List *item, *prev = NULL;
569df887684SGerd Hoffmann     VncInfo2 *info;
570df887684SGerd Hoffmann     VncDisplay *vd;
571df887684SGerd Hoffmann     DeviceState *dev;
572df887684SGerd Hoffmann 
573df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
574df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
575df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
576df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
577df887684SGerd Hoffmann         qmp_query_auth(vd, info);
578df887684SGerd Hoffmann         if (vd->dcl.con) {
579df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
580df887684SGerd Hoffmann                                                   "device", NULL));
581df887684SGerd Hoffmann             info->has_display = true;
582df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
583df887684SGerd Hoffmann         }
584df887684SGerd Hoffmann         if (vd->lsock != -1) {
5854478aa76SGerd Hoffmann             info->server = qmp_query_server_entry(vd->lsock, false,
586df887684SGerd Hoffmann                                                   info->server);
587df887684SGerd Hoffmann         }
588df887684SGerd Hoffmann         if (vd->lwebsock != -1) {
5894478aa76SGerd Hoffmann             info->server = qmp_query_server_entry(vd->lwebsock, true,
5904478aa76SGerd Hoffmann                                                   info->server);
591df887684SGerd Hoffmann         }
592df887684SGerd Hoffmann 
593df887684SGerd Hoffmann         item = g_new0(VncInfo2List, 1);
594df887684SGerd Hoffmann         item->value = info;
595df887684SGerd Hoffmann         item->next = prev;
596df887684SGerd Hoffmann         prev = item;
597df887684SGerd Hoffmann     }
598df887684SGerd Hoffmann     return prev;
599df887684SGerd Hoffmann }
600df887684SGerd Hoffmann 
6013e230dd2SCorentin Chary /* TODO
6023e230dd2SCorentin Chary    1) Get the queue working for IO.
6033e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
6043e230dd2SCorentin Chary       and not totally invalidated
6053e230dd2SCorentin Chary    3) resolutions > 1024
6063e230dd2SCorentin Chary */
6073e230dd2SCorentin Chary 
60838ee14f4SGerd Hoffmann static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
6093e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
6103e230dd2SCorentin Chary 
6113e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
6123e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
6133e230dd2SCorentin Chary                                        int x_position, int y_position,
6143e230dd2SCorentin Chary                                        int w, int h);
6150f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
6163e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
6173e230dd2SCorentin Chary 
618bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
619bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
620bea60dd7SPeter Lieven                                int width, int height,
621bea60dd7SPeter Lieven                                int x, int y, int w, int h) {
62291937225SPeter Lieven     /* this is needed this to ensure we updated all affected
62391937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
624b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
625b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6263e230dd2SCorentin Chary 
6279f64916dSGerd Hoffmann     x = MIN(x, width);
6289f64916dSGerd Hoffmann     y = MIN(y, height);
6299f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
63091937225SPeter Lieven     h = MIN(y + h, height);
6313e230dd2SCorentin Chary 
632b4c85ddcSPeter Lieven     for (; y < h; y++) {
633bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
63491937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
635b4c85ddcSPeter Lieven     }
6363e230dd2SCorentin Chary }
6373e230dd2SCorentin Chary 
638bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
639bea60dd7SPeter Lieven                            int x, int y, int w, int h)
640bea60dd7SPeter Lieven {
641bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
642bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
643bea60dd7SPeter Lieven     int width = pixman_image_get_width(vd->server);
644bea60dd7SPeter Lieven     int height = pixman_image_get_height(vd->server);
645bea60dd7SPeter Lieven 
646bea60dd7SPeter Lieven     vnc_set_area_dirty(s->dirty, width, height, x, y, w, h);
647bea60dd7SPeter Lieven }
648bea60dd7SPeter Lieven 
6493e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6503e230dd2SCorentin Chary                             int32_t encoding)
6513e230dd2SCorentin Chary {
6523e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6533e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6543e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6553e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6563e230dd2SCorentin Chary 
6573e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6583e230dd2SCorentin Chary }
6593e230dd2SCorentin Chary 
66032ed2680STim Hardeck 
6613e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
6623e230dd2SCorentin Chary {
6633e230dd2SCorentin Chary     if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
6643e230dd2SCorentin Chary         return;
6653e230dd2SCorentin Chary     }
666bea60dd7SPeter Lieven     if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
667bea60dd7SPeter Lieven         vs->client_height == pixman_image_get_height(vs->vd->server)) {
6683e230dd2SCorentin Chary         return;
6693e230dd2SCorentin Chary     }
670bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
671bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
672bd023f95SCorentin Chary     vnc_lock_output(vs);
6733e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
6743e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
6753e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
6763e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
6773e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
678bd023f95SCorentin Chary     vnc_unlock_output(vs);
6793e230dd2SCorentin Chary     vnc_flush(vs);
6803e230dd2SCorentin Chary }
6813e230dd2SCorentin Chary 
682bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
683bd023f95SCorentin Chary {
684bd023f95SCorentin Chary     VncState *vs;
685bd023f95SCorentin Chary 
686bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
687bd023f95SCorentin Chary         vnc_lock_output(vs);
688bd023f95SCorentin Chary         vs->abort = true;
689bd023f95SCorentin Chary         vnc_unlock_output(vs);
690bd023f95SCorentin Chary     }
691bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
692bd023f95SCorentin Chary         vnc_jobs_join(vs);
693bd023f95SCorentin Chary     }
694bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
695bd023f95SCorentin Chary         vnc_lock_output(vs);
696bd023f95SCorentin Chary         vs->abort = false;
697bd023f95SCorentin Chary         vnc_unlock_output(vs);
698bd023f95SCorentin Chary     }
699bd023f95SCorentin Chary }
700bd023f95SCorentin Chary 
7019f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
7029f64916dSGerd Hoffmann {
7039f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
7049f64916dSGerd Hoffmann }
7059f64916dSGerd Hoffmann 
7069f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
7079f64916dSGerd Hoffmann {
7089f64916dSGerd Hoffmann     uint8_t *ptr;
7099f64916dSGerd Hoffmann 
7109f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
7119f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
7129f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
7139f64916dSGerd Hoffmann     return ptr;
7149f64916dSGerd Hoffmann }
7159f64916dSGerd Hoffmann 
716c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
717c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
7183e230dd2SCorentin Chary {
71921ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
7203e230dd2SCorentin Chary     VncState *vs;
721bea60dd7SPeter Lieven     int width, height;
7223e230dd2SCorentin Chary 
723bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
724bd023f95SCorentin Chary 
7253e230dd2SCorentin Chary     /* server surface */
7269f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
727d39fa6d8SGerd Hoffmann     vd->ds = surface;
728bea60dd7SPeter Lieven     width = MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
729bea60dd7SPeter Lieven                                         VNC_DIRTY_PIXELS_PER_BIT));
730bea60dd7SPeter Lieven     height = MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
7319f64916dSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
732bea60dd7SPeter Lieven                                           width, height, NULL, 0);
7333e230dd2SCorentin Chary 
7343e230dd2SCorentin Chary     /* guest surface */
7359f64916dSGerd Hoffmann #if 0 /* FIXME */
7363e230dd2SCorentin Chary     if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
7373e230dd2SCorentin Chary         console_color_init(ds);
7389f64916dSGerd Hoffmann #endif
7399f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
740d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
741d39fa6d8SGerd Hoffmann     vd->guest.format = surface->format;
742bea60dd7SPeter Lieven     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
743bea60dd7SPeter Lieven     vnc_set_area_dirty(vd->guest.dirty, width, height, 0, 0,
744bea60dd7SPeter Lieven                        width, height);
7453e230dd2SCorentin Chary 
7463e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
7473e230dd2SCorentin Chary         vnc_colordepth(vs);
7483e230dd2SCorentin Chary         vnc_desktop_resize(vs);
7493e230dd2SCorentin Chary         if (vs->vd->cursor) {
7503e230dd2SCorentin Chary             vnc_cursor_define(vs);
7513e230dd2SCorentin Chary         }
752bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
753bea60dd7SPeter Lieven         vnc_set_area_dirty(vs->dirty, width, height, 0, 0,
754bea60dd7SPeter Lieven                            width, height);
7553e230dd2SCorentin Chary     }
7563e230dd2SCorentin Chary }
7573e230dd2SCorentin Chary 
7583e230dd2SCorentin Chary /* fastest code */
7599f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
7603e230dd2SCorentin Chary                                   void *pixels, int size)
7613e230dd2SCorentin Chary {
7623e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
7633e230dd2SCorentin Chary }
7643e230dd2SCorentin Chary 
7653e230dd2SCorentin Chary /* slowest but generic code. */
7663e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
7673e230dd2SCorentin Chary {
7683e230dd2SCorentin Chary     uint8_t r, g, b;
7693e230dd2SCorentin Chary 
7709f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
7719f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
7729f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
7739f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
7749f64916dSGerd Hoffmann #else
7759f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
7769f64916dSGerd Hoffmann #endif
7779f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
7789f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
7799f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
7809f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
7813e230dd2SCorentin Chary     case 1:
7823e230dd2SCorentin Chary         buf[0] = v;
7833e230dd2SCorentin Chary         break;
7843e230dd2SCorentin Chary     case 2:
7859f64916dSGerd Hoffmann         if (vs->client_be) {
7863e230dd2SCorentin Chary             buf[0] = v >> 8;
7873e230dd2SCorentin Chary             buf[1] = v;
7883e230dd2SCorentin Chary         } else {
7893e230dd2SCorentin Chary             buf[1] = v >> 8;
7903e230dd2SCorentin Chary             buf[0] = v;
7913e230dd2SCorentin Chary         }
7923e230dd2SCorentin Chary         break;
7933e230dd2SCorentin Chary     default:
7943e230dd2SCorentin Chary     case 4:
7959f64916dSGerd Hoffmann         if (vs->client_be) {
7963e230dd2SCorentin Chary             buf[0] = v >> 24;
7973e230dd2SCorentin Chary             buf[1] = v >> 16;
7983e230dd2SCorentin Chary             buf[2] = v >> 8;
7993e230dd2SCorentin Chary             buf[3] = v;
8003e230dd2SCorentin Chary         } else {
8013e230dd2SCorentin Chary             buf[3] = v >> 24;
8023e230dd2SCorentin Chary             buf[2] = v >> 16;
8033e230dd2SCorentin Chary             buf[1] = v >> 8;
8043e230dd2SCorentin Chary             buf[0] = v;
8053e230dd2SCorentin Chary         }
8063e230dd2SCorentin Chary         break;
8073e230dd2SCorentin Chary     }
8083e230dd2SCorentin Chary }
8093e230dd2SCorentin Chary 
8109f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
8113e230dd2SCorentin Chary                                      void *pixels1, int size)
8123e230dd2SCorentin Chary {
8133e230dd2SCorentin Chary     uint8_t buf[4];
8143e230dd2SCorentin Chary 
8159f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
8163e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
8173e230dd2SCorentin Chary         int n, i;
8183e230dd2SCorentin Chary         n = size >> 2;
8193e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
8203e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
8219f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
8223e230dd2SCorentin Chary         }
8233e230dd2SCorentin Chary     }
8243e230dd2SCorentin Chary }
8253e230dd2SCorentin Chary 
8263e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8273e230dd2SCorentin Chary {
8283e230dd2SCorentin Chary     int i;
8293e230dd2SCorentin Chary     uint8_t *row;
8303e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
8313e230dd2SCorentin Chary 
8329f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
8333e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
8349f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
8359f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
8363e230dd2SCorentin Chary     }
8373e230dd2SCorentin Chary     return 1;
8383e230dd2SCorentin Chary }
8393e230dd2SCorentin Chary 
840bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8413e230dd2SCorentin Chary {
8423e230dd2SCorentin Chary     int n = 0;
843*de3f7de7SPeter Lieven     bool encode_raw = false;
844*de3f7de7SPeter Lieven     size_t saved_offs = vs->output.offset;
8453e230dd2SCorentin Chary 
8463e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
8473e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
8483e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
8493e230dd2SCorentin Chary             break;
8503e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
8513e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
8523e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
8533e230dd2SCorentin Chary             break;
8543e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
8553e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
8563e230dd2SCorentin Chary             break;
857efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
858efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
859efe556adSCorentin Chary             break;
860148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
861148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
862148954faSCorentin Chary             break;
863148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
864148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
865148954faSCorentin Chary             break;
8663e230dd2SCorentin Chary         default:
867*de3f7de7SPeter Lieven             encode_raw = true;
8683e230dd2SCorentin Chary             break;
8693e230dd2SCorentin Chary     }
870*de3f7de7SPeter Lieven 
871*de3f7de7SPeter Lieven     /* If the client has the same pixel format as our internal buffer and
872*de3f7de7SPeter Lieven      * a RAW encoding would need less space fall back to RAW encoding to
873*de3f7de7SPeter Lieven      * save bandwidth and processing power in the client. */
874*de3f7de7SPeter Lieven     if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
875*de3f7de7SPeter Lieven         12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
876*de3f7de7SPeter Lieven         vs->output.offset = saved_offs;
877*de3f7de7SPeter Lieven         encode_raw = true;
878*de3f7de7SPeter Lieven     }
879*de3f7de7SPeter Lieven 
880*de3f7de7SPeter Lieven     if (encode_raw) {
881*de3f7de7SPeter Lieven         vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
882*de3f7de7SPeter Lieven         n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
883*de3f7de7SPeter Lieven     }
884*de3f7de7SPeter Lieven 
8853e230dd2SCorentin Chary     return n;
8863e230dd2SCorentin Chary }
8873e230dd2SCorentin Chary 
8883e230dd2SCorentin Chary static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
8893e230dd2SCorentin Chary {
8903e230dd2SCorentin Chary     /* send bitblit op to the vnc client */
891bd023f95SCorentin Chary     vnc_lock_output(vs);
8923e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
8933e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
8943e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
8953e230dd2SCorentin Chary     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
8963e230dd2SCorentin Chary     vnc_write_u16(vs, src_x);
8973e230dd2SCorentin Chary     vnc_write_u16(vs, src_y);
898bd023f95SCorentin Chary     vnc_unlock_output(vs);
8993e230dd2SCorentin Chary     vnc_flush(vs);
9003e230dd2SCorentin Chary }
9013e230dd2SCorentin Chary 
9027c20b4a3SGerd Hoffmann static void vnc_dpy_copy(DisplayChangeListener *dcl,
9037c20b4a3SGerd Hoffmann                          int src_x, int src_y,
9047c20b4a3SGerd Hoffmann                          int dst_x, int dst_y, int w, int h)
9053e230dd2SCorentin Chary {
90621ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
9073e230dd2SCorentin Chary     VncState *vs, *vn;
9083e230dd2SCorentin Chary     uint8_t *src_row;
9093e230dd2SCorentin Chary     uint8_t *dst_row;
9109f64916dSGerd Hoffmann     int i, x, y, pitch, inc, w_lim, s;
9113e230dd2SCorentin Chary     int cmp_bytes;
9123e230dd2SCorentin Chary 
9133e230dd2SCorentin Chary     vnc_refresh_server_surface(vd);
9143e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
9153e230dd2SCorentin Chary         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
9163e230dd2SCorentin Chary             vs->force_update = 1;
91738ee14f4SGerd Hoffmann             vnc_update_client(vs, 1, true);
9183e230dd2SCorentin Chary             /* vs might be free()ed here */
9193e230dd2SCorentin Chary         }
9203e230dd2SCorentin Chary     }
9213e230dd2SCorentin Chary 
9223e230dd2SCorentin Chary     /* do bitblit op on the local surface too */
9239f64916dSGerd Hoffmann     pitch = vnc_server_fb_stride(vd);
9249f64916dSGerd Hoffmann     src_row = vnc_server_fb_ptr(vd, src_x, src_y);
9259f64916dSGerd Hoffmann     dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
9263e230dd2SCorentin Chary     y = dst_y;
9273e230dd2SCorentin Chary     inc = 1;
9283e230dd2SCorentin Chary     if (dst_y > src_y) {
9293e230dd2SCorentin Chary         /* copy backwards */
9303e230dd2SCorentin Chary         src_row += pitch * (h-1);
9313e230dd2SCorentin Chary         dst_row += pitch * (h-1);
9323e230dd2SCorentin Chary         pitch = -pitch;
9333e230dd2SCorentin Chary         y = dst_y + h - 1;
9343e230dd2SCorentin Chary         inc = -1;
9353e230dd2SCorentin Chary     }
936b4c85ddcSPeter Lieven     w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
937b4c85ddcSPeter Lieven     if (w_lim < 0) {
9383e230dd2SCorentin Chary         w_lim = w;
939b4c85ddcSPeter Lieven     } else {
940b4c85ddcSPeter Lieven         w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
941b4c85ddcSPeter Lieven     }
9423e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
9433e230dd2SCorentin Chary         for (x = 0; x <= w_lim;
9443e230dd2SCorentin Chary                 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
9453e230dd2SCorentin Chary             if (x == w_lim) {
9463e230dd2SCorentin Chary                 if ((s = w - w_lim) == 0)
9473e230dd2SCorentin Chary                     break;
9483e230dd2SCorentin Chary             } else if (!x) {
949b4c85ddcSPeter Lieven                 s = (VNC_DIRTY_PIXELS_PER_BIT -
950b4c85ddcSPeter Lieven                     (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
9513e230dd2SCorentin Chary                 s = MIN(s, w_lim);
9523e230dd2SCorentin Chary             } else {
953b4c85ddcSPeter Lieven                 s = VNC_DIRTY_PIXELS_PER_BIT;
9543e230dd2SCorentin Chary             }
9559f64916dSGerd Hoffmann             cmp_bytes = s * VNC_SERVER_FB_BYTES;
9563e230dd2SCorentin Chary             if (memcmp(src_row, dst_row, cmp_bytes) == 0)
9573e230dd2SCorentin Chary                 continue;
9583e230dd2SCorentin Chary             memmove(dst_row, src_row, cmp_bytes);
9593e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
9603e230dd2SCorentin Chary                 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
961b4c85ddcSPeter Lieven                     set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
962b4c85ddcSPeter Lieven                             vs->dirty[y]);
9633e230dd2SCorentin Chary                 }
9643e230dd2SCorentin Chary             }
9653e230dd2SCorentin Chary         }
9669f64916dSGerd Hoffmann         src_row += pitch - w * VNC_SERVER_FB_BYTES;
9679f64916dSGerd Hoffmann         dst_row += pitch - w * VNC_SERVER_FB_BYTES;
9683e230dd2SCorentin Chary         y += inc;
9693e230dd2SCorentin Chary     }
9703e230dd2SCorentin Chary 
9713e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
9723e230dd2SCorentin Chary         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
9733e230dd2SCorentin Chary             vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
9743e230dd2SCorentin Chary         }
9753e230dd2SCorentin Chary     }
9763e230dd2SCorentin Chary }
9773e230dd2SCorentin Chary 
9787c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9797c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9803e230dd2SCorentin Chary {
9813e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9823e230dd2SCorentin Chary }
9833e230dd2SCorentin Chary 
9843e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
9853e230dd2SCorentin Chary {
9863e230dd2SCorentin Chary     QEMUCursor *c = vs->vd->cursor;
9873e230dd2SCorentin Chary     int isize;
9883e230dd2SCorentin Chary 
9893e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
990d01f9595SCorentin Chary         vnc_lock_output(vs);
9913e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
9923e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
9933e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
9943e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
9953e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
9969f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
9979f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
9983e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
999d01f9595SCorentin Chary         vnc_unlock_output(vs);
10003e230dd2SCorentin Chary         return 0;
10013e230dd2SCorentin Chary     }
10023e230dd2SCorentin Chary     return -1;
10033e230dd2SCorentin Chary }
10043e230dd2SCorentin Chary 
10057c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
10067c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
10073e230dd2SCorentin Chary {
1008d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
10093e230dd2SCorentin Chary     VncState *vs;
10103e230dd2SCorentin Chary 
10113e230dd2SCorentin Chary     cursor_put(vd->cursor);
10127267c094SAnthony Liguori     g_free(vd->cursor_mask);
10133e230dd2SCorentin Chary 
10143e230dd2SCorentin Chary     vd->cursor = c;
10153e230dd2SCorentin Chary     cursor_get(vd->cursor);
10163e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
10177267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
10183e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
10193e230dd2SCorentin Chary 
10203e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
10213e230dd2SCorentin Chary         vnc_cursor_define(vs);
10223e230dd2SCorentin Chary     }
10233e230dd2SCorentin Chary }
10243e230dd2SCorentin Chary 
10254769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
10266c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
10273e230dd2SCorentin Chary {
10283e230dd2SCorentin Chary     int h;
10293e230dd2SCorentin Chary 
10306c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
1031bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
10323e230dd2SCorentin Chary             break;
1033bc2429b9SCorentin Chary         }
1034863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
10353e230dd2SCorentin Chary     }
10363e230dd2SCorentin Chary 
10373e230dd2SCorentin Chary     return h;
10383e230dd2SCorentin Chary }
10393e230dd2SCorentin Chary 
104038ee14f4SGerd Hoffmann static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
10413e230dd2SCorentin Chary {
104263658280SGerd Hoffmann     vs->has_dirty += has_dirty;
10433e230dd2SCorentin Chary     if (vs->need_update && vs->csock != -1) {
10443e230dd2SCorentin Chary         VncDisplay *vd = vs->vd;
1045bd023f95SCorentin Chary         VncJob *job;
10463e230dd2SCorentin Chary         int y;
10472f487a3dSPeter Lieven         int height, width;
1048bd023f95SCorentin Chary         int n = 0;
1049bd023f95SCorentin Chary 
10503e230dd2SCorentin Chary         if (vs->output.offset && !vs->audio_cap && !vs->force_update)
10513e230dd2SCorentin Chary             /* kernel send buffers are full -> drop frames to throttle */
10523e230dd2SCorentin Chary             return 0;
10533e230dd2SCorentin Chary 
105463658280SGerd Hoffmann         if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)
10553e230dd2SCorentin Chary             return 0;
10563e230dd2SCorentin Chary 
10573e230dd2SCorentin Chary         /*
10583e230dd2SCorentin Chary          * Send screen updates to the vnc client using the server
10593e230dd2SCorentin Chary          * surface and server dirty map.  guest surface updates
10603e230dd2SCorentin Chary          * happening in parallel don't disturb us, the next pass will
10613e230dd2SCorentin Chary          * send them to the client.
10623e230dd2SCorentin Chary          */
1063bd023f95SCorentin Chary         job = vnc_job_new(vs);
10643e230dd2SCorentin Chary 
1065bea60dd7SPeter Lieven         height = pixman_image_get_height(vd->server);
1066bea60dd7SPeter Lieven         width = pixman_image_get_width(vd->server);
10673e230dd2SCorentin Chary 
106812b316d4SPeter Lieven         y = 0;
106912b316d4SPeter Lieven         for (;;) {
107012b316d4SPeter Lieven             int x, h;
107112b316d4SPeter Lieven             unsigned long x2;
107212b316d4SPeter Lieven             unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
107312b316d4SPeter Lieven                                                  height * VNC_DIRTY_BPL(vs),
107412b316d4SPeter Lieven                                                  y * VNC_DIRTY_BPL(vs));
107512b316d4SPeter Lieven             if (offset == height * VNC_DIRTY_BPL(vs)) {
107612b316d4SPeter Lieven                 /* no more dirty bits */
107712b316d4SPeter Lieven                 break;
10783e230dd2SCorentin Chary             }
107912b316d4SPeter Lieven             y = offset / VNC_DIRTY_BPL(vs);
108012b316d4SPeter Lieven             x = offset % VNC_DIRTY_BPL(vs);
108112b316d4SPeter Lieven             x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
108212b316d4SPeter Lieven                                     VNC_DIRTY_BPL(vs), x);
108312b316d4SPeter Lieven             bitmap_clear(vs->dirty[y], x, x2 - x);
108412b316d4SPeter Lieven             h = find_and_clear_dirty_height(vs, y, x, x2, height);
10852f487a3dSPeter Lieven             x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
10862f487a3dSPeter Lieven             if (x2 > x) {
108712b316d4SPeter Lieven                 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
108812b316d4SPeter Lieven                                       (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
10893e230dd2SCorentin Chary             }
10900e7d6f60SPeter Lieven             if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
10910e7d6f60SPeter Lieven                 y += h;
10920e7d6f60SPeter Lieven                 if (y == height) {
10930e7d6f60SPeter Lieven                     break;
10940e7d6f60SPeter Lieven                 }
10950e7d6f60SPeter Lieven             }
10962f487a3dSPeter Lieven         }
1097bd023f95SCorentin Chary 
1098bd023f95SCorentin Chary         vnc_job_push(job);
1099eb214ff8SGerd Hoffmann         if (sync) {
1100eb214ff8SGerd Hoffmann             vnc_jobs_join(vs);
1101eb214ff8SGerd Hoffmann         }
11023e230dd2SCorentin Chary         vs->force_update = 0;
110363658280SGerd Hoffmann         vs->has_dirty = 0;
1104bd023f95SCorentin Chary         return n;
11053e230dd2SCorentin Chary     }
11063e230dd2SCorentin Chary 
110738ee14f4SGerd Hoffmann     if (vs->csock == -1) {
11083e230dd2SCorentin Chary         vnc_disconnect_finish(vs);
110938ee14f4SGerd Hoffmann     } else if (sync) {
111038ee14f4SGerd Hoffmann         vnc_jobs_join(vs);
111138ee14f4SGerd Hoffmann     }
11123e230dd2SCorentin Chary 
11133e230dd2SCorentin Chary     return 0;
11143e230dd2SCorentin Chary }
11153e230dd2SCorentin Chary 
11163e230dd2SCorentin Chary /* audio */
11173e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
11183e230dd2SCorentin Chary {
11193e230dd2SCorentin Chary     VncState *vs = opaque;
11203e230dd2SCorentin Chary 
11213e230dd2SCorentin Chary     switch (cmd) {
11223e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1123bd023f95SCorentin Chary         vnc_lock_output(vs);
11243e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11253e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11263e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1127bd023f95SCorentin Chary         vnc_unlock_output(vs);
11283e230dd2SCorentin Chary         vnc_flush(vs);
11293e230dd2SCorentin Chary         break;
11303e230dd2SCorentin Chary 
11313e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1132bd023f95SCorentin Chary         vnc_lock_output(vs);
11333e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11343e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11353e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1136bd023f95SCorentin Chary         vnc_unlock_output(vs);
11373e230dd2SCorentin Chary         vnc_flush(vs);
11383e230dd2SCorentin Chary         break;
11393e230dd2SCorentin Chary     }
11403e230dd2SCorentin Chary }
11413e230dd2SCorentin Chary 
11423e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
11433e230dd2SCorentin Chary {
11443e230dd2SCorentin Chary }
11453e230dd2SCorentin Chary 
11463e230dd2SCorentin Chary static void audio_capture(void *opaque, void *buf, int size)
11473e230dd2SCorentin Chary {
11483e230dd2SCorentin Chary     VncState *vs = opaque;
11493e230dd2SCorentin Chary 
1150bd023f95SCorentin Chary     vnc_lock_output(vs);
11513e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11523e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11533e230dd2SCorentin Chary     vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
11543e230dd2SCorentin Chary     vnc_write_u32(vs, size);
11553e230dd2SCorentin Chary     vnc_write(vs, buf, size);
1156bd023f95SCorentin Chary     vnc_unlock_output(vs);
11573e230dd2SCorentin Chary     vnc_flush(vs);
11583e230dd2SCorentin Chary }
11593e230dd2SCorentin Chary 
11603e230dd2SCorentin Chary static void audio_add(VncState *vs)
11613e230dd2SCorentin Chary {
11623e230dd2SCorentin Chary     struct audio_capture_ops ops;
11633e230dd2SCorentin Chary 
11643e230dd2SCorentin Chary     if (vs->audio_cap) {
1165027a79c3SCole Robinson         error_report("audio already running");
11663e230dd2SCorentin Chary         return;
11673e230dd2SCorentin Chary     }
11683e230dd2SCorentin Chary 
11693e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
11703e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
11713e230dd2SCorentin Chary     ops.capture = audio_capture;
11723e230dd2SCorentin Chary 
11733e230dd2SCorentin Chary     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
11743e230dd2SCorentin Chary     if (!vs->audio_cap) {
1175027a79c3SCole Robinson         error_report("Failed to add audio capture");
11763e230dd2SCorentin Chary     }
11773e230dd2SCorentin Chary }
11783e230dd2SCorentin Chary 
11793e230dd2SCorentin Chary static void audio_del(VncState *vs)
11803e230dd2SCorentin Chary {
11813e230dd2SCorentin Chary     if (vs->audio_cap) {
11823e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
11833e230dd2SCorentin Chary         vs->audio_cap = NULL;
11843e230dd2SCorentin Chary     }
11853e230dd2SCorentin Chary }
11863e230dd2SCorentin Chary 
11873e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
11883e230dd2SCorentin Chary {
11893e230dd2SCorentin Chary     if (vs->csock == -1)
11903e230dd2SCorentin Chary         return;
11918cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
119282e1cc4bSFam Zheng     qemu_set_fd_handler(vs->csock, NULL, NULL, NULL);
11933e230dd2SCorentin Chary     closesocket(vs->csock);
11943e230dd2SCorentin Chary     vs->csock = -1;
11953e230dd2SCorentin Chary }
11963e230dd2SCorentin Chary 
11977536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
11983e230dd2SCorentin Chary {
11997d964c9dSCorentin Chary     int i;
12007d964c9dSCorentin Chary 
1201bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1202bd023f95SCorentin Chary 
1203bd023f95SCorentin Chary     vnc_lock_output(vs);
1204fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
12053e230dd2SCorentin Chary 
12063e230dd2SCorentin Chary     buffer_free(&vs->input);
12073e230dd2SCorentin Chary     buffer_free(&vs->output);
12087536ee4bSTim Hardeck     buffer_free(&vs->ws_input);
12097536ee4bSTim Hardeck     buffer_free(&vs->ws_output);
12103e230dd2SCorentin Chary 
1211fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
12123e230dd2SCorentin Chary 
12133e230dd2SCorentin Chary     vnc_zlib_clear(vs);
12143e230dd2SCorentin Chary     vnc_tight_clear(vs);
1215148954faSCorentin Chary     vnc_zrle_clear(vs);
12163e230dd2SCorentin Chary 
12173e305e4aSDaniel P. Berrange     qcrypto_tls_session_free(vs->tls);
12183e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
12193e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
12203e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
12213e230dd2SCorentin Chary     audio_del(vs);
12227bc9318bSGerd Hoffmann     vnc_release_modifiers(vs);
12233e230dd2SCorentin Chary 
12246fd8e79aSTim Hardeck     if (vs->initialized) {
12253e230dd2SCorentin Chary         QTAILQ_REMOVE(&vs->vd->clients, vs, next);
12266fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
12276fd8e79aSTim Hardeck     }
12283e230dd2SCorentin Chary 
12293e230dd2SCorentin Chary     if (vs->vd->lock_key_sync)
12303e230dd2SCorentin Chary         qemu_remove_led_event_handler(vs->led);
1231bd023f95SCorentin Chary     vnc_unlock_output(vs);
1232bd023f95SCorentin Chary 
1233bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
12346fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1235175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
12366fd8e79aSTim Hardeck     }
1237175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1238175b2a6eSCorentin Chary 
12397d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
12407267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
12417d964c9dSCorentin Chary     }
12427267c094SAnthony Liguori     g_free(vs->lossy_rect);
12437267c094SAnthony Liguori     g_free(vs);
12443e230dd2SCorentin Chary }
12453e230dd2SCorentin Chary 
1246fdd1ab6aSDaniel P. Berrange ssize_t vnc_client_io_error(VncState *vs, ssize_t ret, int last_errno)
12473e230dd2SCorentin Chary {
12483e230dd2SCorentin Chary     if (ret == 0 || ret == -1) {
12493e230dd2SCorentin Chary         if (ret == -1) {
12503e230dd2SCorentin Chary             switch (last_errno) {
12513e230dd2SCorentin Chary                 case EINTR:
12523e230dd2SCorentin Chary                 case EAGAIN:
12533e230dd2SCorentin Chary #ifdef _WIN32
12543e230dd2SCorentin Chary                 case WSAEWOULDBLOCK:
12553e230dd2SCorentin Chary #endif
12563e230dd2SCorentin Chary                     return 0;
12573e230dd2SCorentin Chary                 default:
12583e230dd2SCorentin Chary                     break;
12593e230dd2SCorentin Chary             }
12603e230dd2SCorentin Chary         }
12613e230dd2SCorentin Chary 
1262fdd1ab6aSDaniel P. Berrange         VNC_DEBUG("Closing down client sock: ret %zd, errno %d\n",
12633e230dd2SCorentin Chary                   ret, ret < 0 ? last_errno : 0);
12643e230dd2SCorentin Chary         vnc_disconnect_start(vs);
12653e230dd2SCorentin Chary 
12663e230dd2SCorentin Chary         return 0;
12673e230dd2SCorentin Chary     }
12683e230dd2SCorentin Chary     return ret;
12693e230dd2SCorentin Chary }
12703e230dd2SCorentin Chary 
12713e230dd2SCorentin Chary 
12723e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
12733e230dd2SCorentin Chary {
12743e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
12753e230dd2SCorentin Chary     vnc_disconnect_start(vs);
12763e230dd2SCorentin Chary }
12773e230dd2SCorentin Chary 
12783e305e4aSDaniel P. Berrange 
12793e305e4aSDaniel P. Berrange ssize_t vnc_tls_pull(char *buf, size_t len, void *opaque)
12800057a0d5STim Hardeck {
12813e305e4aSDaniel P. Berrange     VncState *vs = opaque;
12823e305e4aSDaniel P. Berrange     ssize_t ret;
12833e305e4aSDaniel P. Berrange 
12843e305e4aSDaniel P. Berrange  retry:
12853e305e4aSDaniel P. Berrange     ret = qemu_recv(vs->csock, buf, len, 0);
12860057a0d5STim Hardeck     if (ret < 0) {
12873e305e4aSDaniel P. Berrange         if (errno == EINTR) {
12883e305e4aSDaniel P. Berrange             goto retry;
12890057a0d5STim Hardeck         }
12903e305e4aSDaniel P. Berrange         return -1;
12910057a0d5STim Hardeck     }
12920057a0d5STim Hardeck     return ret;
12930057a0d5STim Hardeck }
12943e305e4aSDaniel P. Berrange 
12953e305e4aSDaniel P. Berrange 
12963e305e4aSDaniel P. Berrange ssize_t vnc_tls_push(const char *buf, size_t len, void *opaque)
12973e305e4aSDaniel P. Berrange {
12983e305e4aSDaniel P. Berrange     VncState *vs = opaque;
12993e305e4aSDaniel P. Berrange     ssize_t ret;
13003e305e4aSDaniel P. Berrange 
13013e305e4aSDaniel P. Berrange  retry:
13023e305e4aSDaniel P. Berrange     ret = send(vs->csock, buf, len, 0);
13033e305e4aSDaniel P. Berrange     if (ret < 0) {
13043e305e4aSDaniel P. Berrange         if (errno == EINTR) {
13053e305e4aSDaniel P. Berrange             goto retry;
13063e305e4aSDaniel P. Berrange         }
13073e305e4aSDaniel P. Berrange         return -1;
13083e305e4aSDaniel P. Berrange     }
13093e305e4aSDaniel P. Berrange     return ret;
13103e305e4aSDaniel P. Berrange }
13113e305e4aSDaniel P. Berrange 
13123e230dd2SCorentin Chary 
13133e230dd2SCorentin Chary /*
13143e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
13153e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
13163e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
13173e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
13183e230dd2SCorentin Chary  *
13193e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
13203e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
13213e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
13223e230dd2SCorentin Chary  * is active
13233e230dd2SCorentin Chary  *
13243e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13253e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
13263e230dd2SCorentin Chary  * -1 on error, and disconnects the client socket.
13273e230dd2SCorentin Chary  */
1328fdd1ab6aSDaniel P. Berrange ssize_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
13293e230dd2SCorentin Chary {
1330fdd1ab6aSDaniel P. Berrange     ssize_t ret;
13313e305e4aSDaniel P. Berrange     int err = 0;
13323e305e4aSDaniel P. Berrange     if (vs->tls) {
13333e305e4aSDaniel P. Berrange         ret = qcrypto_tls_session_write(vs->tls, (const char *)data, datalen);
13343e305e4aSDaniel P. Berrange         if (ret < 0) {
13353e305e4aSDaniel P. Berrange             err = errno;
13360057a0d5STim Hardeck         }
13373e305e4aSDaniel P. Berrange     } else {
13383e305e4aSDaniel P. Berrange         ret = send(vs->csock, (const void *)data, datalen, 0);
13393e305e4aSDaniel P. Berrange         if (ret < 0) {
13403e305e4aSDaniel P. Berrange             err = socket_error();
13413e305e4aSDaniel P. Berrange         }
13423e305e4aSDaniel P. Berrange     }
13433e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
13443e305e4aSDaniel P. Berrange     return vnc_client_io_error(vs, ret, err);
13453e230dd2SCorentin Chary }
13463e230dd2SCorentin Chary 
13473e230dd2SCorentin Chary 
13483e230dd2SCorentin Chary /*
13493e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
13503e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
13513e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
13523e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
13533e230dd2SCorentin Chary  *
13543e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13553e230dd2SCorentin Chary  * the buffered output data if the socket would block. Returns
13563e230dd2SCorentin Chary  * -1 on error, and disconnects the client socket.
13573e230dd2SCorentin Chary  */
1358fdd1ab6aSDaniel P. Berrange static ssize_t vnc_client_write_plain(VncState *vs)
13593e230dd2SCorentin Chary {
1360fdd1ab6aSDaniel P. Berrange     ssize_t ret;
13613e230dd2SCorentin Chary 
13623e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13633e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
13643e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
13653e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
13663e230dd2SCorentin Chary 
13673e230dd2SCorentin Chary     if (vs->sasl.conn &&
13683e230dd2SCorentin Chary         vs->sasl.runSSF &&
13693e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
13703e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
13713e230dd2SCorentin Chary         if (ret)
13723e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
13733e230dd2SCorentin Chary     } else
13743e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13753e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
13763e230dd2SCorentin Chary     if (!ret)
13773e230dd2SCorentin Chary         return 0;
13783e230dd2SCorentin Chary 
137932ed2680STim Hardeck     buffer_advance(&vs->output, ret);
13803e230dd2SCorentin Chary 
13813e230dd2SCorentin Chary     if (vs->output.offset == 0) {
138282e1cc4bSFam Zheng         qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
13833e230dd2SCorentin Chary     }
13843e230dd2SCorentin Chary 
13853e230dd2SCorentin Chary     return ret;
13863e230dd2SCorentin Chary }
13873e230dd2SCorentin Chary 
13883e230dd2SCorentin Chary 
13893e230dd2SCorentin Chary /*
13903e230dd2SCorentin Chary  * First function called whenever there is data to be written to
13913e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
13923e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
13933e230dd2SCorentin Chary  */
1394bd023f95SCorentin Chary static void vnc_client_write_locked(void *opaque)
13953e230dd2SCorentin Chary {
13963e230dd2SCorentin Chary     VncState *vs = opaque;
13973e230dd2SCorentin Chary 
13983e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13993e230dd2SCorentin Chary     if (vs->sasl.conn &&
14003e230dd2SCorentin Chary         vs->sasl.runSSF &&
14013e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
14023e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
14033e230dd2SCorentin Chary     } else
14043e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14057536ee4bSTim Hardeck     {
14067536ee4bSTim Hardeck         if (vs->encode_ws) {
14077536ee4bSTim Hardeck             vnc_client_write_ws(vs);
14088e9b0d24SDaniel P. Berrange         } else {
14093e230dd2SCorentin Chary             vnc_client_write_plain(vs);
14103e230dd2SCorentin Chary         }
14117536ee4bSTim Hardeck     }
14127536ee4bSTim Hardeck }
14133e230dd2SCorentin Chary 
1414bd023f95SCorentin Chary void vnc_client_write(void *opaque)
1415bd023f95SCorentin Chary {
1416bd023f95SCorentin Chary     VncState *vs = opaque;
1417bd023f95SCorentin Chary 
1418bd023f95SCorentin Chary     vnc_lock_output(vs);
14198e9b0d24SDaniel P. Berrange     if (vs->output.offset || vs->ws_output.offset) {
1420bd023f95SCorentin Chary         vnc_client_write_locked(opaque);
1421ac71103dSYoshiaki Tamura     } else if (vs->csock != -1) {
142282e1cc4bSFam Zheng         qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
1423bd023f95SCorentin Chary     }
1424bd023f95SCorentin Chary     vnc_unlock_output(vs);
1425bd023f95SCorentin Chary }
1426bd023f95SCorentin Chary 
14273e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
14283e230dd2SCorentin Chary {
14293e230dd2SCorentin Chary     vs->read_handler = func;
14303e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
14313e230dd2SCorentin Chary }
14323e230dd2SCorentin Chary 
14333e230dd2SCorentin Chary 
14343e230dd2SCorentin Chary /*
14353e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
14363e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
14373e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
14383e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
14393e230dd2SCorentin Chary  *
14403e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
14413e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
14423e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
14433e230dd2SCorentin Chary  * is active
14443e230dd2SCorentin Chary  *
14453e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
14463e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
14473e230dd2SCorentin Chary  * -1 on error, and disconnects the client socket.
14483e230dd2SCorentin Chary  */
1449fdd1ab6aSDaniel P. Berrange ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
14503e230dd2SCorentin Chary {
1451fdd1ab6aSDaniel P. Berrange     ssize_t ret;
14523e305e4aSDaniel P. Berrange     int err = -1;
14533e305e4aSDaniel P. Berrange     if (vs->tls) {
14543e305e4aSDaniel P. Berrange         ret = qcrypto_tls_session_read(vs->tls, (char *)data, datalen);
14553e305e4aSDaniel P. Berrange         if (ret < 0) {
14563e305e4aSDaniel P. Berrange             err = errno;
14570057a0d5STim Hardeck         }
14583e305e4aSDaniel P. Berrange     } else {
14593e305e4aSDaniel P. Berrange         ret = qemu_recv(vs->csock, data, datalen, 0);
14603e305e4aSDaniel P. Berrange         if (ret < 0) {
14613e305e4aSDaniel P. Berrange             err = socket_error();
14623e305e4aSDaniel P. Berrange         }
14633e305e4aSDaniel P. Berrange     }
14643e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
14653e305e4aSDaniel P. Berrange     return vnc_client_io_error(vs, ret, err);
14663e230dd2SCorentin Chary }
14673e230dd2SCorentin Chary 
14683e230dd2SCorentin Chary 
14693e230dd2SCorentin Chary /*
14703e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
14713e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
14723e230dd2SCorentin Chary  * data as possible without blocking.
14733e230dd2SCorentin Chary  *
14743e230dd2SCorentin Chary  * Returns the number of bytes read. Returns -1 on error, and
14753e230dd2SCorentin Chary  * disconnects the client socket.
14763e230dd2SCorentin Chary  */
1477fdd1ab6aSDaniel P. Berrange static ssize_t vnc_client_read_plain(VncState *vs)
14783e230dd2SCorentin Chary {
1479fdd1ab6aSDaniel P. Berrange     ssize_t ret;
14803e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
14813e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
14823e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
14833e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
14843e230dd2SCorentin Chary     if (!ret)
14853e230dd2SCorentin Chary         return 0;
14863e230dd2SCorentin Chary     vs->input.offset += ret;
14873e230dd2SCorentin Chary     return ret;
14883e230dd2SCorentin Chary }
14893e230dd2SCorentin Chary 
1490175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1491175b2a6eSCorentin Chary {
1492175b2a6eSCorentin Chary     VncState *vs = opaque;
1493175b2a6eSCorentin Chary 
1494175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1495175b2a6eSCorentin Chary }
14963e230dd2SCorentin Chary 
14973e230dd2SCorentin Chary /*
14983e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
14993e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
15003e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
15013e230dd2SCorentin Chary  */
15023e230dd2SCorentin Chary void vnc_client_read(void *opaque)
15033e230dd2SCorentin Chary {
15043e230dd2SCorentin Chary     VncState *vs = opaque;
1505fdd1ab6aSDaniel P. Berrange     ssize_t ret;
15063e230dd2SCorentin Chary 
15073e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
15083e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
15093e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
15103e230dd2SCorentin Chary     else
15113e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
15127536ee4bSTim Hardeck         if (vs->encode_ws) {
15137536ee4bSTim Hardeck             ret = vnc_client_read_ws(vs);
15147536ee4bSTim Hardeck             if (ret == -1) {
15157536ee4bSTim Hardeck                 vnc_disconnect_start(vs);
15167536ee4bSTim Hardeck                 return;
15177536ee4bSTim Hardeck             } else if (ret == -2) {
15187536ee4bSTim Hardeck                 vnc_client_error(vs);
15197536ee4bSTim Hardeck                 return;
15207536ee4bSTim Hardeck             }
15218e9b0d24SDaniel P. Berrange         } else {
15223e230dd2SCorentin Chary             ret = vnc_client_read_plain(vs);
15237536ee4bSTim Hardeck         }
15243e230dd2SCorentin Chary     if (!ret) {
15253e230dd2SCorentin Chary         if (vs->csock == -1)
15263e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
15273e230dd2SCorentin Chary         return;
15283e230dd2SCorentin Chary     }
15293e230dd2SCorentin Chary 
15303e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
15313e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
15323e230dd2SCorentin Chary         int ret;
15333e230dd2SCorentin Chary 
15343e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
15353e230dd2SCorentin Chary         if (vs->csock == -1) {
15363e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
15373e230dd2SCorentin Chary             return;
15383e230dd2SCorentin Chary         }
15393e230dd2SCorentin Chary 
15403e230dd2SCorentin Chary         if (!ret) {
154132ed2680STim Hardeck             buffer_advance(&vs->input, len);
15423e230dd2SCorentin Chary         } else {
15433e230dd2SCorentin Chary             vs->read_handler_expect = ret;
15443e230dd2SCorentin Chary         }
15453e230dd2SCorentin Chary     }
15463e230dd2SCorentin Chary }
15473e230dd2SCorentin Chary 
15483e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
15493e230dd2SCorentin Chary {
15503e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
15513e230dd2SCorentin Chary 
15523e230dd2SCorentin Chary     if (vs->csock != -1 && buffer_empty(&vs->output)) {
155382e1cc4bSFam Zheng         qemu_set_fd_handler(vs->csock, vnc_client_read, vnc_client_write, vs);
15543e230dd2SCorentin Chary     }
15553e230dd2SCorentin Chary 
15563e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
15573e230dd2SCorentin Chary }
15583e230dd2SCorentin Chary 
15593e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
15603e230dd2SCorentin Chary {
15613e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
15623e230dd2SCorentin Chary }
15633e230dd2SCorentin Chary 
15643e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
15653e230dd2SCorentin Chary {
15663e230dd2SCorentin Chary     uint8_t buf[4];
15673e230dd2SCorentin Chary 
15683e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
15693e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
15703e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
15713e230dd2SCorentin Chary     buf[3] = value & 0xFF;
15723e230dd2SCorentin Chary 
15733e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
15743e230dd2SCorentin Chary }
15753e230dd2SCorentin Chary 
15763e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
15773e230dd2SCorentin Chary {
15783e230dd2SCorentin Chary     uint8_t buf[2];
15793e230dd2SCorentin Chary 
15803e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
15813e230dd2SCorentin Chary     buf[1] = value & 0xFF;
15823e230dd2SCorentin Chary 
15833e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
15843e230dd2SCorentin Chary }
15853e230dd2SCorentin Chary 
15863e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
15873e230dd2SCorentin Chary {
15883e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
15893e230dd2SCorentin Chary }
15903e230dd2SCorentin Chary 
15913e230dd2SCorentin Chary void vnc_flush(VncState *vs)
15923e230dd2SCorentin Chary {
1593bd023f95SCorentin Chary     vnc_lock_output(vs);
15948e9b0d24SDaniel P. Berrange     if (vs->csock != -1 && (vs->output.offset ||
15958e9b0d24SDaniel P. Berrange                             vs->ws_output.offset)) {
1596bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1597bd023f95SCorentin Chary     }
1598bd023f95SCorentin Chary     vnc_unlock_output(vs);
15993e230dd2SCorentin Chary }
16003e230dd2SCorentin Chary 
160171a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
16023e230dd2SCorentin Chary {
16033e230dd2SCorentin Chary     return data[offset];
16043e230dd2SCorentin Chary }
16053e230dd2SCorentin Chary 
160671a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
16073e230dd2SCorentin Chary {
16083e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
16093e230dd2SCorentin Chary }
16103e230dd2SCorentin Chary 
161171a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
16123e230dd2SCorentin Chary {
16133e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
16143e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
16153e230dd2SCorentin Chary }
16163e230dd2SCorentin Chary 
16173e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
16183e230dd2SCorentin Chary {
16193e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
16203e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
16213e230dd2SCorentin Chary }
16223e230dd2SCorentin Chary 
16233e230dd2SCorentin Chary static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
16243e230dd2SCorentin Chary {
16253e230dd2SCorentin Chary }
16263e230dd2SCorentin Chary 
16279e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
16283e230dd2SCorentin Chary {
16293e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
163014768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
16313e230dd2SCorentin Chary 
16323e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1633bd023f95SCorentin Chary         vnc_lock_output(vs);
16343e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
16353e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
16363e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
16373e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1638bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1639bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
16403e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1641bd023f95SCorentin Chary         vnc_unlock_output(vs);
16423e230dd2SCorentin Chary         vnc_flush(vs);
16433e230dd2SCorentin Chary     }
16443e230dd2SCorentin Chary     vs->absolute = absolute;
16453e230dd2SCorentin Chary }
16463e230dd2SCorentin Chary 
16473e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
16483e230dd2SCorentin Chary {
164914768ebaSGerd Hoffmann     static uint32_t bmap[INPUT_BUTTON_MAX] = {
165014768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
165114768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
165214768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
165314768ebaSGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
165414768ebaSGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
165514768ebaSGerd Hoffmann     };
165614768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1657bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1658bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
16593e230dd2SCorentin Chary 
166014768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
166114768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
166214768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
166314768ebaSGerd Hoffmann     }
16643e230dd2SCorentin Chary 
16653e230dd2SCorentin Chary     if (vs->absolute) {
166614768ebaSGerd Hoffmann         qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
166714768ebaSGerd Hoffmann         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
16683e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
166914768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
167014768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
16713e230dd2SCorentin Chary     } else {
167214768ebaSGerd Hoffmann         if (vs->last_x != -1) {
167314768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
167414768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
167514768ebaSGerd Hoffmann         }
16763e230dd2SCorentin Chary         vs->last_x = x;
16773e230dd2SCorentin Chary         vs->last_y = y;
16783e230dd2SCorentin Chary     }
167914768ebaSGerd Hoffmann     qemu_input_event_sync();
16803e230dd2SCorentin Chary }
16813e230dd2SCorentin Chary 
16823e230dd2SCorentin Chary static void reset_keys(VncState *vs)
16833e230dd2SCorentin Chary {
16843e230dd2SCorentin Chary     int i;
16853e230dd2SCorentin Chary     for(i = 0; i < 256; i++) {
16863e230dd2SCorentin Chary         if (vs->modifiers_state[i]) {
16878d447d10SGerd Hoffmann             qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
16883e230dd2SCorentin Chary             vs->modifiers_state[i] = 0;
16893e230dd2SCorentin Chary         }
16903e230dd2SCorentin Chary     }
16913e230dd2SCorentin Chary }
16923e230dd2SCorentin Chary 
16933e230dd2SCorentin Chary static void press_key(VncState *vs, int keysym)
16943e230dd2SCorentin Chary {
16953e230dd2SCorentin Chary     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
16968d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
16972deb4accSGerd Hoffmann     qemu_input_event_send_key_delay(0);
16988d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
16992deb4accSGerd Hoffmann     qemu_input_event_send_key_delay(0);
17003e230dd2SCorentin Chary }
17013e230dd2SCorentin Chary 
1702ab99e5c1SLei Li static int current_led_state(VncState *vs)
1703ab99e5c1SLei Li {
1704ab99e5c1SLei Li     int ledstate = 0;
1705ab99e5c1SLei Li 
1706ab99e5c1SLei Li     if (vs->modifiers_state[0x46]) {
1707ab99e5c1SLei Li         ledstate |= QEMU_SCROLL_LOCK_LED;
1708ab99e5c1SLei Li     }
1709ab99e5c1SLei Li     if (vs->modifiers_state[0x45]) {
1710ab99e5c1SLei Li         ledstate |= QEMU_NUM_LOCK_LED;
1711ab99e5c1SLei Li     }
1712ab99e5c1SLei Li     if (vs->modifiers_state[0x3a]) {
1713ab99e5c1SLei Li         ledstate |= QEMU_CAPS_LOCK_LED;
1714ab99e5c1SLei Li     }
1715ab99e5c1SLei Li 
1716ab99e5c1SLei Li     return ledstate;
1717ab99e5c1SLei Li }
1718ab99e5c1SLei Li 
1719ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1720ab99e5c1SLei Li {
1721ab99e5c1SLei Li     int ledstate = 0;
1722ab99e5c1SLei Li 
1723ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1724ab99e5c1SLei Li         return;
1725ab99e5c1SLei Li     }
1726ab99e5c1SLei Li 
1727ab99e5c1SLei Li     ledstate = current_led_state(vs);
1728ab99e5c1SLei Li     vnc_lock_output(vs);
1729ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1730ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1731ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1732ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1733ab99e5c1SLei Li     vnc_write_u8(vs, ledstate);
1734ab99e5c1SLei Li     vnc_unlock_output(vs);
1735ab99e5c1SLei Li     vnc_flush(vs);
1736ab99e5c1SLei Li }
1737ab99e5c1SLei Li 
17383e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
17393e230dd2SCorentin Chary {
17403e230dd2SCorentin Chary     VncState *vs = opaque;
174196f3d174SLei Li     int caps, num, scr;
17421483adcfSLei Li     bool has_changed = (ledstate != current_led_state(vs));
17433e230dd2SCorentin Chary 
174440066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
174540066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
174640066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
174740066175SGerd Hoffmann 
17483e230dd2SCorentin Chary     caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
17493e230dd2SCorentin Chary     num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
175096f3d174SLei Li     scr  = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
17513e230dd2SCorentin Chary 
17523e230dd2SCorentin Chary     if (vs->modifiers_state[0x3a] != caps) {
17533e230dd2SCorentin Chary         vs->modifiers_state[0x3a] = caps;
17543e230dd2SCorentin Chary     }
17553e230dd2SCorentin Chary     if (vs->modifiers_state[0x45] != num) {
17563e230dd2SCorentin Chary         vs->modifiers_state[0x45] = num;
17573e230dd2SCorentin Chary     }
175896f3d174SLei Li     if (vs->modifiers_state[0x46] != scr) {
175996f3d174SLei Li         vs->modifiers_state[0x46] = scr;
176096f3d174SLei Li     }
1761ab99e5c1SLei Li 
1762ab99e5c1SLei Li     /* Sending the current led state message to the client */
17631483adcfSLei Li     if (has_changed) {
1764ab99e5c1SLei Li         vnc_led_state_change(vs);
1765ab99e5c1SLei Li     }
17663e230dd2SCorentin Chary }
17673e230dd2SCorentin Chary 
17683e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
17693e230dd2SCorentin Chary {
17703e230dd2SCorentin Chary     /* QEMU console switch */
17713e230dd2SCorentin Chary     switch(keycode) {
17723e230dd2SCorentin Chary     case 0x2a:                          /* Left Shift */
17733e230dd2SCorentin Chary     case 0x36:                          /* Right Shift */
17743e230dd2SCorentin Chary     case 0x1d:                          /* Left CTRL */
17753e230dd2SCorentin Chary     case 0x9d:                          /* Right CTRL */
17763e230dd2SCorentin Chary     case 0x38:                          /* Left ALT */
17773e230dd2SCorentin Chary     case 0xb8:                          /* Right ALT */
17783e230dd2SCorentin Chary         if (down)
17793e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 1;
17803e230dd2SCorentin Chary         else
17813e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 0;
17823e230dd2SCorentin Chary         break;
17833e230dd2SCorentin Chary     case 0x02 ... 0x0a: /* '1' to '9' keys */
17841d0d59feSGerd Hoffmann         if (vs->vd->dcl.con == NULL &&
17851d0d59feSGerd Hoffmann             down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
17863e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
17873e230dd2SCorentin Chary             reset_keys(vs);
17883e230dd2SCorentin Chary             console_select(keycode - 0x02);
17893e230dd2SCorentin Chary             return;
17903e230dd2SCorentin Chary         }
17913e230dd2SCorentin Chary         break;
17923e230dd2SCorentin Chary     case 0x3a:                        /* CapsLock */
17933e230dd2SCorentin Chary     case 0x45:                        /* NumLock */
17943e230dd2SCorentin Chary         if (down)
17953e230dd2SCorentin Chary             vs->modifiers_state[keycode] ^= 1;
17963e230dd2SCorentin Chary         break;
17973e230dd2SCorentin Chary     }
17983e230dd2SCorentin Chary 
1799e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1800e7b2aaccSLei Li        state extension.
1801e7b2aaccSLei Li     */
18029892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1803e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18043e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
18053e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
18063e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18073e230dd2SCorentin Chary            toggles numlock away from the VNC window.
18083e230dd2SCorentin Chary         */
18093e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
18103e230dd2SCorentin Chary             if (!vs->modifiers_state[0x45]) {
181140066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
18123e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 1;
18133e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
18143e230dd2SCorentin Chary             }
18153e230dd2SCorentin Chary         } else {
18163e230dd2SCorentin Chary             if (vs->modifiers_state[0x45]) {
181740066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
18183e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 0;
18193e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
18203e230dd2SCorentin Chary             }
18213e230dd2SCorentin Chary         }
18223e230dd2SCorentin Chary     }
18233e230dd2SCorentin Chary 
18249892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1825e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18263e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
18273e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
18283e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18293e230dd2SCorentin Chary            toggles capslock away from the VNC window.
18303e230dd2SCorentin Chary         */
18313e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
18323e230dd2SCorentin Chary         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
18333e230dd2SCorentin Chary         int capslock = !!(vs->modifiers_state[0x3a]);
18343e230dd2SCorentin Chary         if (capslock) {
18353e230dd2SCorentin Chary             if (uppercase == shift) {
183640066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
18373e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 0;
18383e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18393e230dd2SCorentin Chary             }
18403e230dd2SCorentin Chary         } else {
18413e230dd2SCorentin Chary             if (uppercase != shift) {
184240066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
18433e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 1;
18443e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18453e230dd2SCorentin Chary             }
18463e230dd2SCorentin Chary         }
18473e230dd2SCorentin Chary     }
18483e230dd2SCorentin Chary 
184981c0d5a6SGerd Hoffmann     if (qemu_console_is_graphic(NULL)) {
18508d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
18513e230dd2SCorentin Chary     } else {
1852e26437c2SGerd Hoffmann         bool numlock = vs->modifiers_state[0x45];
1853e26437c2SGerd Hoffmann         bool control = (vs->modifiers_state[0x1d] ||
1854e26437c2SGerd Hoffmann                         vs->modifiers_state[0x9d]);
18553e230dd2SCorentin Chary         /* QEMU console emulation */
18563e230dd2SCorentin Chary         if (down) {
18573e230dd2SCorentin Chary             switch (keycode) {
18583e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
18593e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
18603e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
18613e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
18623e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
18633e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
18643e230dd2SCorentin Chary                 break;
18653e230dd2SCorentin Chary             case 0xc8:
18663e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_UP);
18673e230dd2SCorentin Chary                 break;
18683e230dd2SCorentin Chary             case 0xd0:
18693e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DOWN);
18703e230dd2SCorentin Chary                 break;
18713e230dd2SCorentin Chary             case 0xcb:
18723e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_LEFT);
18733e230dd2SCorentin Chary                 break;
18743e230dd2SCorentin Chary             case 0xcd:
18753e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_RIGHT);
18763e230dd2SCorentin Chary                 break;
18773e230dd2SCorentin Chary             case 0xd3:
18783e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DELETE);
18793e230dd2SCorentin Chary                 break;
18803e230dd2SCorentin Chary             case 0xc7:
18813e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_HOME);
18823e230dd2SCorentin Chary                 break;
18833e230dd2SCorentin Chary             case 0xcf:
18843e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_END);
18853e230dd2SCorentin Chary                 break;
18863e230dd2SCorentin Chary             case 0xc9:
18873e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEUP);
18883e230dd2SCorentin Chary                 break;
18893e230dd2SCorentin Chary             case 0xd1:
18903e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
18913e230dd2SCorentin Chary                 break;
18923e230dd2SCorentin Chary 
18933e230dd2SCorentin Chary             case 0x47:
18943e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
18953e230dd2SCorentin Chary                 break;
18963e230dd2SCorentin Chary             case 0x48:
18973e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
18983e230dd2SCorentin Chary                 break;
18993e230dd2SCorentin Chary             case 0x49:
19003e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
19013e230dd2SCorentin Chary                 break;
19023e230dd2SCorentin Chary             case 0x4b:
19033e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
19043e230dd2SCorentin Chary                 break;
19053e230dd2SCorentin Chary             case 0x4c:
19063e230dd2SCorentin Chary                 kbd_put_keysym('5');
19073e230dd2SCorentin Chary                 break;
19083e230dd2SCorentin Chary             case 0x4d:
19093e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
19103e230dd2SCorentin Chary                 break;
19113e230dd2SCorentin Chary             case 0x4f:
19123e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
19133e230dd2SCorentin Chary                 break;
19143e230dd2SCorentin Chary             case 0x50:
19153e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
19163e230dd2SCorentin Chary                 break;
19173e230dd2SCorentin Chary             case 0x51:
19183e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
19193e230dd2SCorentin Chary                 break;
19203e230dd2SCorentin Chary             case 0x52:
19213e230dd2SCorentin Chary                 kbd_put_keysym('0');
19223e230dd2SCorentin Chary                 break;
19233e230dd2SCorentin Chary             case 0x53:
19243e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
19253e230dd2SCorentin Chary                 break;
19263e230dd2SCorentin Chary 
19273e230dd2SCorentin Chary             case 0xb5:
19283e230dd2SCorentin Chary                 kbd_put_keysym('/');
19293e230dd2SCorentin Chary                 break;
19303e230dd2SCorentin Chary             case 0x37:
19313e230dd2SCorentin Chary                 kbd_put_keysym('*');
19323e230dd2SCorentin Chary                 break;
19333e230dd2SCorentin Chary             case 0x4a:
19343e230dd2SCorentin Chary                 kbd_put_keysym('-');
19353e230dd2SCorentin Chary                 break;
19363e230dd2SCorentin Chary             case 0x4e:
19373e230dd2SCorentin Chary                 kbd_put_keysym('+');
19383e230dd2SCorentin Chary                 break;
19393e230dd2SCorentin Chary             case 0x9c:
19403e230dd2SCorentin Chary                 kbd_put_keysym('\n');
19413e230dd2SCorentin Chary                 break;
19423e230dd2SCorentin Chary 
19433e230dd2SCorentin Chary             default:
1944e26437c2SGerd Hoffmann                 if (control) {
1945e26437c2SGerd Hoffmann                     kbd_put_keysym(sym & 0x1f);
1946e26437c2SGerd Hoffmann                 } else {
19473e230dd2SCorentin Chary                     kbd_put_keysym(sym);
1948e26437c2SGerd Hoffmann                 }
19493e230dd2SCorentin Chary                 break;
19503e230dd2SCorentin Chary             }
19513e230dd2SCorentin Chary         }
19523e230dd2SCorentin Chary     }
19533e230dd2SCorentin Chary }
19543e230dd2SCorentin Chary 
19557bc9318bSGerd Hoffmann static void vnc_release_modifiers(VncState *vs)
19567bc9318bSGerd Hoffmann {
19577bc9318bSGerd Hoffmann     static const int keycodes[] = {
19587bc9318bSGerd Hoffmann         /* shift, control, alt keys, both left & right */
19597bc9318bSGerd Hoffmann         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
19607bc9318bSGerd Hoffmann     };
19617bc9318bSGerd Hoffmann     int i, keycode;
19627bc9318bSGerd Hoffmann 
196381c0d5a6SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
19647bc9318bSGerd Hoffmann         return;
19657bc9318bSGerd Hoffmann     }
19667bc9318bSGerd Hoffmann     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
19677bc9318bSGerd Hoffmann         keycode = keycodes[i];
19687bc9318bSGerd Hoffmann         if (!vs->modifiers_state[keycode]) {
19697bc9318bSGerd Hoffmann             continue;
19707bc9318bSGerd Hoffmann         }
19718d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
19727bc9318bSGerd Hoffmann     }
19737bc9318bSGerd Hoffmann }
19747bc9318bSGerd Hoffmann 
197540066175SGerd Hoffmann static const char *code2name(int keycode)
197640066175SGerd Hoffmann {
197740066175SGerd Hoffmann     return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
197840066175SGerd Hoffmann }
197940066175SGerd Hoffmann 
19803e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
19813e230dd2SCorentin Chary {
19823e230dd2SCorentin Chary     int keycode;
19833e230dd2SCorentin Chary     int lsym = sym;
19843e230dd2SCorentin Chary 
198581c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
19863e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
19873e230dd2SCorentin Chary     }
19883e230dd2SCorentin Chary 
19893e230dd2SCorentin Chary     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
199040066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
19913e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
19923e230dd2SCorentin Chary }
19933e230dd2SCorentin Chary 
19943e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
19953e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
19963e230dd2SCorentin Chary {
19973e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
199840066175SGerd Hoffmann     if (keyboard_layout) {
19993e230dd2SCorentin Chary         key_event(vs, down, sym);
200040066175SGerd Hoffmann     } else {
200140066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
20023e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
20033e230dd2SCorentin Chary     }
200440066175SGerd Hoffmann }
20053e230dd2SCorentin Chary 
20063e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
2007bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
20083e230dd2SCorentin Chary {
2009bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
2010bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
20113e230dd2SCorentin Chary 
20123e230dd2SCorentin Chary     vs->need_update = 1;
2013bea60dd7SPeter Lieven 
2014bea60dd7SPeter Lieven     if (incremental) {
2015bea60dd7SPeter Lieven         return;
20163e230dd2SCorentin Chary     }
2017bea60dd7SPeter Lieven 
201807535a89SStephan Kulow     vs->force_update = 1;
2019bea60dd7SPeter Lieven     vnc_set_area_dirty(vs->dirty, width, height, x, y, w, h);
20203e230dd2SCorentin Chary }
20213e230dd2SCorentin Chary 
20223e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
20233e230dd2SCorentin Chary {
2024bd023f95SCorentin Chary     vnc_lock_output(vs);
20253e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20263e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20273e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2028d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2029bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2030bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20313e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
2032bd023f95SCorentin Chary     vnc_unlock_output(vs);
20333e230dd2SCorentin Chary     vnc_flush(vs);
20343e230dd2SCorentin Chary }
20353e230dd2SCorentin Chary 
20363e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
20373e230dd2SCorentin Chary {
2038bd023f95SCorentin Chary     vnc_lock_output(vs);
20393e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20403e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20413e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2042d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2043bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2044bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20453e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2046bd023f95SCorentin Chary     vnc_unlock_output(vs);
20473e230dd2SCorentin Chary     vnc_flush(vs);
20483e230dd2SCorentin Chary }
20493e230dd2SCorentin Chary 
20503e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
20513e230dd2SCorentin Chary {
20523e230dd2SCorentin Chary     int i;
20533e230dd2SCorentin Chary     unsigned int enc = 0;
20543e230dd2SCorentin Chary 
20553e230dd2SCorentin Chary     vs->features = 0;
20563e230dd2SCorentin Chary     vs->vnc_encoding = 0;
2057d1af0e05SCorentin Chary     vs->tight.compression = 9;
2058d1af0e05SCorentin Chary     vs->tight.quality = -1; /* Lossless by default */
20593e230dd2SCorentin Chary     vs->absolute = -1;
20603e230dd2SCorentin Chary 
20613e230dd2SCorentin Chary     /*
20623e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2063e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
20643e230dd2SCorentin Chary      * will be set at the end of the loop.
20653e230dd2SCorentin Chary      */
20663e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
20673e230dd2SCorentin Chary         enc = encodings[i];
20683e230dd2SCorentin Chary         switch (enc) {
20693e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
20703e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20713e230dd2SCorentin Chary             break;
20723e230dd2SCorentin Chary         case VNC_ENCODING_COPYRECT:
20733e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_COPYRECT_MASK;
20743e230dd2SCorentin Chary             break;
20753e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
20763e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
20773e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20783e230dd2SCorentin Chary             break;
20793e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
20803e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
20813e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20823e230dd2SCorentin Chary             break;
2083fe3e7f2dSJoel Martin #ifdef CONFIG_VNC_PNG
2084efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2085efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2086efe556adSCorentin Chary             vs->vnc_encoding = enc;
2087efe556adSCorentin Chary             break;
2088fe3e7f2dSJoel Martin #endif
20893e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
20903e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_ZLIB_MASK;
20913e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20923e230dd2SCorentin Chary             break;
2093148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2094148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2095148954faSCorentin Chary             vs->vnc_encoding = enc;
2096148954faSCorentin Chary             break;
2097148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2098148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2099148954faSCorentin Chary             vs->vnc_encoding = enc;
2100148954faSCorentin Chary             break;
21013e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
21023e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
21033e230dd2SCorentin Chary             break;
21043e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
21053e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
21063e230dd2SCorentin Chary             break;
21073e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
21083e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
21093e230dd2SCorentin Chary             break;
21103e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
21113e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
21123e230dd2SCorentin Chary             break;
21133e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
21143e230dd2SCorentin Chary             send_ext_audio_ack(vs);
21153e230dd2SCorentin Chary             break;
21163e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
21173e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
21183e230dd2SCorentin Chary             break;
2119ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2120ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2121ab99e5c1SLei Li             break;
21223e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2123d1af0e05SCorentin Chary             vs->tight.compression = (enc & 0x0F);
21243e230dd2SCorentin Chary             break;
21253e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2126b31f519eSCorentin Chary             if (vs->vd->lossy) {
2127d1af0e05SCorentin Chary                 vs->tight.quality = (enc & 0x0F);
2128b31f519eSCorentin Chary             }
21293e230dd2SCorentin Chary             break;
21303e230dd2SCorentin Chary         default:
21313e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
21323e230dd2SCorentin Chary             break;
21333e230dd2SCorentin Chary         }
21343e230dd2SCorentin Chary     }
21353e230dd2SCorentin Chary     vnc_desktop_resize(vs);
21369e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2137ab99e5c1SLei Li     vnc_led_state_change(vs);
21383e230dd2SCorentin Chary }
21393e230dd2SCorentin Chary 
21403e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
21413e230dd2SCorentin Chary {
21429f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
21439f64916dSGerd Hoffmann 
21449f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
21453e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
21463e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
21473e230dd2SCorentin Chary     } else {
21483e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
21493e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
21503e230dd2SCorentin Chary     }
21513e230dd2SCorentin Chary }
21523e230dd2SCorentin Chary 
21533e230dd2SCorentin Chary static void set_pixel_format(VncState *vs,
21543e230dd2SCorentin Chary                              int bits_per_pixel, int depth,
21553e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
21563e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
21573e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
21583e230dd2SCorentin Chary {
21593e230dd2SCorentin Chary     if (!true_color_flag) {
21603e230dd2SCorentin Chary         vnc_client_error(vs);
21613e230dd2SCorentin Chary         return;
21623e230dd2SCorentin Chary     }
21633e230dd2SCorentin Chary 
2164e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2165e6908bfeSPetr Matousek     case 8:
2166e6908bfeSPetr Matousek     case 16:
2167e6908bfeSPetr Matousek     case 32:
2168e6908bfeSPetr Matousek         break;
2169e6908bfeSPetr Matousek     default:
2170e6908bfeSPetr Matousek         vnc_client_error(vs);
2171e6908bfeSPetr Matousek         return;
2172e6908bfeSPetr Matousek     }
2173e6908bfeSPetr Matousek 
21749f64916dSGerd Hoffmann     vs->client_pf.rmax = red_max;
21759f64916dSGerd Hoffmann     vs->client_pf.rbits = hweight_long(red_max);
21769f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
21779f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
21789f64916dSGerd Hoffmann     vs->client_pf.gmax = green_max;
21799f64916dSGerd Hoffmann     vs->client_pf.gbits = hweight_long(green_max);
21809f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
21819f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
21829f64916dSGerd Hoffmann     vs->client_pf.bmax = blue_max;
21839f64916dSGerd Hoffmann     vs->client_pf.bbits = hweight_long(blue_max);
21849f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
21859f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
21869f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
21879f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
21889f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
21899f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
21903e230dd2SCorentin Chary 
21913e230dd2SCorentin Chary     set_pixel_conversion(vs);
21923e230dd2SCorentin Chary 
21931d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
21941d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
21953e230dd2SCorentin Chary }
21963e230dd2SCorentin Chary 
21973e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
21983e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
21993e230dd2SCorentin Chary 
22009f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
22019f64916dSGerd Hoffmann 
22029f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
22039f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
22043e230dd2SCorentin Chary 
22053e230dd2SCorentin Chary #ifdef HOST_WORDS_BIGENDIAN
22063e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
22073e230dd2SCorentin Chary #else
22083e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
22093e230dd2SCorentin Chary #endif
22103e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
22119f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
22129f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
22139f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
22149f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
22159f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
22169f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
22179f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
22183e230dd2SCorentin Chary 
22193e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
22203e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
22213e230dd2SCorentin Chary }
22223e230dd2SCorentin Chary 
22233e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
22243e230dd2SCorentin Chary {
22253e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
22263e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2227bd023f95SCorentin Chary         vnc_lock_output(vs);
22283e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
22293e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
22303e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2231d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
2232bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
2233bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
2234d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
22353e230dd2SCorentin Chary         pixel_format_message(vs);
2236bd023f95SCorentin Chary         vnc_unlock_output(vs);
22373e230dd2SCorentin Chary         vnc_flush(vs);
22383e230dd2SCorentin Chary     } else {
22393e230dd2SCorentin Chary         set_pixel_conversion(vs);
22403e230dd2SCorentin Chary     }
22413e230dd2SCorentin Chary }
22423e230dd2SCorentin Chary 
22433e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
22443e230dd2SCorentin Chary {
22453e230dd2SCorentin Chary     int i;
22463e230dd2SCorentin Chary     uint16_t limit;
22473e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
22483e230dd2SCorentin Chary 
22493e230dd2SCorentin Chary     if (data[0] > 3) {
22500f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
22513e230dd2SCorentin Chary     }
22523e230dd2SCorentin Chary 
22533e230dd2SCorentin Chary     switch (data[0]) {
22543e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
22553e230dd2SCorentin Chary         if (len == 1)
22563e230dd2SCorentin Chary             return 20;
22573e230dd2SCorentin Chary 
22583e230dd2SCorentin Chary         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
22593e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
22603e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
22613e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
22623e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
22633e230dd2SCorentin Chary         break;
22643e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
22653e230dd2SCorentin Chary         if (len == 1)
22663e230dd2SCorentin Chary             return 4;
22673e230dd2SCorentin Chary 
22683e230dd2SCorentin Chary         if (len == 4) {
22693e230dd2SCorentin Chary             limit = read_u16(data, 2);
22703e230dd2SCorentin Chary             if (limit > 0)
22713e230dd2SCorentin Chary                 return 4 + (limit * 4);
22723e230dd2SCorentin Chary         } else
22733e230dd2SCorentin Chary             limit = read_u16(data, 2);
22743e230dd2SCorentin Chary 
22753e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
22763e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
22773e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
22783e230dd2SCorentin Chary         }
22793e230dd2SCorentin Chary 
22803e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
22813e230dd2SCorentin Chary         break;
22823e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
22833e230dd2SCorentin Chary         if (len == 1)
22843e230dd2SCorentin Chary             return 10;
22853e230dd2SCorentin Chary 
22863e230dd2SCorentin Chary         framebuffer_update_request(vs,
22873e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
22883e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
22893e230dd2SCorentin Chary         break;
22903e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
22913e230dd2SCorentin Chary         if (len == 1)
22923e230dd2SCorentin Chary             return 8;
22933e230dd2SCorentin Chary 
22943e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
22953e230dd2SCorentin Chary         break;
22963e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
22973e230dd2SCorentin Chary         if (len == 1)
22983e230dd2SCorentin Chary             return 6;
22993e230dd2SCorentin Chary 
23003e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
23013e230dd2SCorentin Chary         break;
23023e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2303f9a70e79SPeter Lieven         if (len == 1) {
23043e230dd2SCorentin Chary             return 8;
2305f9a70e79SPeter Lieven         }
23063e230dd2SCorentin Chary         if (len == 8) {
23073e230dd2SCorentin Chary             uint32_t dlen = read_u32(data, 4);
2308f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2309f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2310f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2311f9a70e79SPeter Lieven                 vnc_client_error(vs);
2312f9a70e79SPeter Lieven                 break;
2313f9a70e79SPeter Lieven             }
2314f9a70e79SPeter Lieven             if (dlen > 0) {
23153e230dd2SCorentin Chary                 return 8 + dlen;
23163e230dd2SCorentin Chary             }
2317f9a70e79SPeter Lieven         }
23183e230dd2SCorentin Chary 
23193e230dd2SCorentin Chary         client_cut_text(vs, read_u32(data, 4), data + 8);
23203e230dd2SCorentin Chary         break;
23213e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
23223e230dd2SCorentin Chary         if (len == 1)
23233e230dd2SCorentin Chary             return 2;
23243e230dd2SCorentin Chary 
23253e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
23263e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
23273e230dd2SCorentin Chary             if (len == 2)
23283e230dd2SCorentin Chary                 return 12;
23293e230dd2SCorentin Chary 
23303e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
23313e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
23323e230dd2SCorentin Chary             break;
23333e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
23343e230dd2SCorentin Chary             if (len == 2)
23353e230dd2SCorentin Chary                 return 4;
23363e230dd2SCorentin Chary 
23373e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
23383e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
23393e230dd2SCorentin Chary                 audio_add(vs);
23403e230dd2SCorentin Chary                 break;
23413e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
23423e230dd2SCorentin Chary                 audio_del(vs);
23433e230dd2SCorentin Chary                 break;
23443e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
23453e230dd2SCorentin Chary                 if (len == 4)
23463e230dd2SCorentin Chary                     return 10;
23473e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
23483e230dd2SCorentin Chary                 case 0: vs->as.fmt = AUD_FMT_U8; break;
23493e230dd2SCorentin Chary                 case 1: vs->as.fmt = AUD_FMT_S8; break;
23503e230dd2SCorentin Chary                 case 2: vs->as.fmt = AUD_FMT_U16; break;
23513e230dd2SCorentin Chary                 case 3: vs->as.fmt = AUD_FMT_S16; break;
23523e230dd2SCorentin Chary                 case 4: vs->as.fmt = AUD_FMT_U32; break;
23533e230dd2SCorentin Chary                 case 5: vs->as.fmt = AUD_FMT_S32; break;
23543e230dd2SCorentin Chary                 default:
2355153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
23563e230dd2SCorentin Chary                     vnc_client_error(vs);
23573e230dd2SCorentin Chary                     break;
23583e230dd2SCorentin Chary                 }
23593e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
23603e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2361153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio channel coount %d\n",
23623e230dd2SCorentin Chary                               read_u8(data, 5));
23633e230dd2SCorentin Chary                     vnc_client_error(vs);
23643e230dd2SCorentin Chary                     break;
23653e230dd2SCorentin Chary                 }
23663e230dd2SCorentin Chary                 vs->as.freq = read_u32(data, 6);
23673e230dd2SCorentin Chary                 break;
23683e230dd2SCorentin Chary             default:
2369153130cdSDaniel P. Berrange                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
23703e230dd2SCorentin Chary                 vnc_client_error(vs);
23713e230dd2SCorentin Chary                 break;
23723e230dd2SCorentin Chary             }
23733e230dd2SCorentin Chary             break;
23743e230dd2SCorentin Chary 
23753e230dd2SCorentin Chary         default:
2376153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
23773e230dd2SCorentin Chary             vnc_client_error(vs);
23783e230dd2SCorentin Chary             break;
23793e230dd2SCorentin Chary         }
23803e230dd2SCorentin Chary         break;
23813e230dd2SCorentin Chary     default:
2382153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
23833e230dd2SCorentin Chary         vnc_client_error(vs);
23843e230dd2SCorentin Chary         break;
23853e230dd2SCorentin Chary     }
23863e230dd2SCorentin Chary 
23873e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
23883e230dd2SCorentin Chary     return 0;
23893e230dd2SCorentin Chary }
23903e230dd2SCorentin Chary 
23913e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
23923e230dd2SCorentin Chary {
23933e230dd2SCorentin Chary     char buf[1024];
23948cf36489SGerd Hoffmann     VncShareMode mode;
23953e230dd2SCorentin Chary     int size;
23963e230dd2SCorentin Chary 
23978cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
23988cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
23998cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
24008cf36489SGerd Hoffmann         /*
24018cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
24028cf36489SGerd Hoffmann          *
24038cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
24048cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
24058cf36489SGerd Hoffmann          * reasons.
24068cf36489SGerd Hoffmann          */
24078cf36489SGerd Hoffmann         break;
24088cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
24098cf36489SGerd Hoffmann         /*
24108cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
24118cf36489SGerd Hoffmann          *
24128cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
24138cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
24148cf36489SGerd Hoffmann          * as no exclusive connection exists.
24158cf36489SGerd Hoffmann          *
24168cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
24178cf36489SGerd Hoffmann          */
24188cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24198cf36489SGerd Hoffmann             VncState *client;
24208cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
24218cf36489SGerd Hoffmann                 if (vs == client) {
24228cf36489SGerd Hoffmann                     continue;
24238cf36489SGerd Hoffmann                 }
24248cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
24258cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
24268cf36489SGerd Hoffmann                     continue;
24278cf36489SGerd Hoffmann                 }
24288cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
24298cf36489SGerd Hoffmann             }
24308cf36489SGerd Hoffmann         }
24318cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
24328cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
24338cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
24348cf36489SGerd Hoffmann                 return 0;
24358cf36489SGerd Hoffmann             }
24368cf36489SGerd Hoffmann         }
24378cf36489SGerd Hoffmann         break;
24388cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
24398cf36489SGerd Hoffmann         /*
24408cf36489SGerd Hoffmann          * Policy: Shared connects only.
24418cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
24428cf36489SGerd Hoffmann          *
24438cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
24448cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
24458cf36489SGerd Hoffmann          * client disconnect everybody else.
24468cf36489SGerd Hoffmann          */
24478cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24488cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
24498cf36489SGerd Hoffmann             return 0;
24508cf36489SGerd Hoffmann         }
24518cf36489SGerd Hoffmann         break;
24528cf36489SGerd Hoffmann     }
24538cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
24548cf36489SGerd Hoffmann 
2455e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2456e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2457e5f34cddSGerd Hoffmann         return 0;
2458e5f34cddSGerd Hoffmann     }
2459e5f34cddSGerd Hoffmann 
2460bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2461bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
24623e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
24633e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
24643e230dd2SCorentin Chary 
24653e230dd2SCorentin Chary     pixel_format_message(vs);
24663e230dd2SCorentin Chary 
24673e230dd2SCorentin Chary     if (qemu_name)
24683e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
24693e230dd2SCorentin Chary     else
24703e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
24713e230dd2SCorentin Chary 
24723e230dd2SCorentin Chary     vnc_write_u32(vs, size);
24733e230dd2SCorentin Chary     vnc_write(vs, buf, size);
24743e230dd2SCorentin Chary     vnc_flush(vs);
24753e230dd2SCorentin Chary 
24763e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2477fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
24783e230dd2SCorentin Chary 
24793e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
24803e230dd2SCorentin Chary 
24813e230dd2SCorentin Chary     return 0;
24823e230dd2SCorentin Chary }
24833e230dd2SCorentin Chary 
24843e230dd2SCorentin Chary void start_client_init(VncState *vs)
24853e230dd2SCorentin Chary {
24863e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
24873e230dd2SCorentin Chary }
24883e230dd2SCorentin Chary 
24893e230dd2SCorentin Chary static void make_challenge(VncState *vs)
24903e230dd2SCorentin Chary {
24913e230dd2SCorentin Chary     int i;
24923e230dd2SCorentin Chary 
24933e230dd2SCorentin Chary     srand(time(NULL)+getpid()+getpid()*987654+rand());
24943e230dd2SCorentin Chary 
24953e230dd2SCorentin Chary     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
24963e230dd2SCorentin Chary         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
24973e230dd2SCorentin Chary }
24983e230dd2SCorentin Chary 
24993e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
25003e230dd2SCorentin Chary {
25013e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2502800567a6SDaniel P. Berrange     size_t i, pwlen;
25033e230dd2SCorentin Chary     unsigned char key[8];
25043c9405a0SGerd Hoffmann     time_t now = time(NULL);
250560928458SGonglei     QCryptoCipher *cipher = NULL;
2506800567a6SDaniel P. Berrange     Error *err = NULL;
25073e230dd2SCorentin Chary 
25081cd20f8bSAnthony Liguori     if (!vs->vd->password) {
25093e230dd2SCorentin Chary         VNC_DEBUG("No password configured on server");
25106bffdf0fSGerd Hoffmann         goto reject;
25113e230dd2SCorentin Chary     }
25123c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
25133c9405a0SGerd Hoffmann         VNC_DEBUG("Password is expired");
25143c9405a0SGerd Hoffmann         goto reject;
25153c9405a0SGerd Hoffmann     }
25163e230dd2SCorentin Chary 
25173e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
25183e230dd2SCorentin Chary 
25193e230dd2SCorentin Chary     /* Calculate the expected challenge response */
25203e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
25213e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
25223e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2523800567a6SDaniel P. Berrange 
2524800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
2525800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_DES_RFB,
2526800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2527800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2528800567a6SDaniel P. Berrange         &err);
2529800567a6SDaniel P. Berrange     if (!cipher) {
2530800567a6SDaniel P. Berrange         VNC_DEBUG("Cannot initialize cipher %s",
2531800567a6SDaniel P. Berrange                   error_get_pretty(err));
2532800567a6SDaniel P. Berrange         error_free(err);
2533800567a6SDaniel P. Berrange         goto reject;
2534800567a6SDaniel P. Berrange     }
2535800567a6SDaniel P. Berrange 
2536a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2537800567a6SDaniel P. Berrange                                vs->challenge,
2538800567a6SDaniel P. Berrange                                response,
2539800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2540800567a6SDaniel P. Berrange                                &err) < 0) {
2541800567a6SDaniel P. Berrange         VNC_DEBUG("Cannot encrypt challenge %s",
2542800567a6SDaniel P. Berrange                   error_get_pretty(err));
2543800567a6SDaniel P. Berrange         error_free(err);
2544800567a6SDaniel P. Berrange         goto reject;
2545800567a6SDaniel P. Berrange     }
25463e230dd2SCorentin Chary 
25473e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
25483e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2549e5bed759SDong Xu Wang         VNC_DEBUG("Client challenge response did not match\n");
25506bffdf0fSGerd Hoffmann         goto reject;
25516bffdf0fSGerd Hoffmann     } else {
25526bffdf0fSGerd Hoffmann         VNC_DEBUG("Accepting VNC challenge response\n");
25536bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
25546bffdf0fSGerd Hoffmann         vnc_flush(vs);
25556bffdf0fSGerd Hoffmann 
25566bffdf0fSGerd Hoffmann         start_client_init(vs);
25576bffdf0fSGerd Hoffmann     }
255860928458SGonglei 
255960928458SGonglei     qcrypto_cipher_free(cipher);
25606bffdf0fSGerd Hoffmann     return 0;
25616bffdf0fSGerd Hoffmann 
25626bffdf0fSGerd Hoffmann reject:
25633e230dd2SCorentin Chary     vnc_write_u32(vs, 1); /* Reject auth */
25643e230dd2SCorentin Chary     if (vs->minor >= 8) {
25653e230dd2SCorentin Chary         static const char err[] = "Authentication failed";
25663e230dd2SCorentin Chary         vnc_write_u32(vs, sizeof(err));
25673e230dd2SCorentin Chary         vnc_write(vs, err, sizeof(err));
25683e230dd2SCorentin Chary     }
25693e230dd2SCorentin Chary     vnc_flush(vs);
25703e230dd2SCorentin Chary     vnc_client_error(vs);
257160928458SGonglei     qcrypto_cipher_free(cipher);
25723e230dd2SCorentin Chary     return 0;
25733e230dd2SCorentin Chary }
25743e230dd2SCorentin Chary 
25753e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
25763e230dd2SCorentin Chary {
25773e230dd2SCorentin Chary     make_challenge(vs);
25783e230dd2SCorentin Chary     /* Send client a 'random' challenge */
25793e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
25803e230dd2SCorentin Chary     vnc_flush(vs);
25813e230dd2SCorentin Chary 
25823e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
25833e230dd2SCorentin Chary }
25843e230dd2SCorentin Chary 
25853e230dd2SCorentin Chary 
25863e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
25873e230dd2SCorentin Chary {
25883e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
25893e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
25907e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
25913e230dd2SCorentin Chary        VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
25923e230dd2SCorentin Chary        vnc_write_u32(vs, 1);
25933e230dd2SCorentin Chary        if (vs->minor >= 8) {
25943e230dd2SCorentin Chary            static const char err[] = "Authentication failed";
25953e230dd2SCorentin Chary            vnc_write_u32(vs, sizeof(err));
25963e230dd2SCorentin Chary            vnc_write(vs, err, sizeof(err));
25973e230dd2SCorentin Chary        }
25983e230dd2SCorentin Chary        vnc_client_error(vs);
25993e230dd2SCorentin Chary     } else { /* Accept requested auth */
26003e230dd2SCorentin Chary        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
26017e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
26023e230dd2SCorentin Chary        case VNC_AUTH_NONE:
26033e230dd2SCorentin Chary            VNC_DEBUG("Accept auth none\n");
26043e230dd2SCorentin Chary            if (vs->minor >= 8) {
26053e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
26063e230dd2SCorentin Chary                vnc_flush(vs);
26073e230dd2SCorentin Chary            }
26083e230dd2SCorentin Chary            start_client_init(vs);
26093e230dd2SCorentin Chary            break;
26103e230dd2SCorentin Chary 
26113e230dd2SCorentin Chary        case VNC_AUTH_VNC:
26123e230dd2SCorentin Chary            VNC_DEBUG("Start VNC auth\n");
26133e230dd2SCorentin Chary            start_auth_vnc(vs);
26143e230dd2SCorentin Chary            break;
26153e230dd2SCorentin Chary 
26163e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
26173a93113aSDong Xu Wang            VNC_DEBUG("Accept VeNCrypt auth\n");
26183e230dd2SCorentin Chary            start_auth_vencrypt(vs);
26193e230dd2SCorentin Chary            break;
26203e230dd2SCorentin Chary 
26213e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
26223e230dd2SCorentin Chary        case VNC_AUTH_SASL:
26233e230dd2SCorentin Chary            VNC_DEBUG("Accept SASL auth\n");
26243e230dd2SCorentin Chary            start_auth_sasl(vs);
26253e230dd2SCorentin Chary            break;
26263e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
26273e230dd2SCorentin Chary 
26283e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
26297e7e2ebcSDaniel P. Berrange            VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
26303e230dd2SCorentin Chary            vnc_write_u8(vs, 1);
26313e230dd2SCorentin Chary            if (vs->minor >= 8) {
26323e230dd2SCorentin Chary                static const char err[] = "Authentication failed";
26333e230dd2SCorentin Chary                vnc_write_u32(vs, sizeof(err));
26343e230dd2SCorentin Chary                vnc_write(vs, err, sizeof(err));
26353e230dd2SCorentin Chary            }
26363e230dd2SCorentin Chary            vnc_client_error(vs);
26373e230dd2SCorentin Chary        }
26383e230dd2SCorentin Chary     }
26393e230dd2SCorentin Chary     return 0;
26403e230dd2SCorentin Chary }
26413e230dd2SCorentin Chary 
26423e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
26433e230dd2SCorentin Chary {
26443e230dd2SCorentin Chary     char local[13];
26453e230dd2SCorentin Chary 
26463e230dd2SCorentin Chary     memcpy(local, version, 12);
26473e230dd2SCorentin Chary     local[12] = 0;
26483e230dd2SCorentin Chary 
26493e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
26503e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
26513e230dd2SCorentin Chary         vnc_client_error(vs);
26523e230dd2SCorentin Chary         return 0;
26533e230dd2SCorentin Chary     }
26543e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
26553e230dd2SCorentin Chary     if (vs->major != 3 ||
26563e230dd2SCorentin Chary         (vs->minor != 3 &&
26573e230dd2SCorentin Chary          vs->minor != 4 &&
26583e230dd2SCorentin Chary          vs->minor != 5 &&
26593e230dd2SCorentin Chary          vs->minor != 7 &&
26603e230dd2SCorentin Chary          vs->minor != 8)) {
26613e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
26623e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
26633e230dd2SCorentin Chary         vnc_flush(vs);
26643e230dd2SCorentin Chary         vnc_client_error(vs);
26653e230dd2SCorentin Chary         return 0;
26663e230dd2SCorentin Chary     }
26673e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
26683e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
26693e230dd2SCorentin Chary      */
26703e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
26713e230dd2SCorentin Chary         vs->minor = 3;
26723e230dd2SCorentin Chary 
26733e230dd2SCorentin Chary     if (vs->minor == 3) {
26747e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
26753e230dd2SCorentin Chary             VNC_DEBUG("Tell client auth none\n");
26767e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
26773e230dd2SCorentin Chary             vnc_flush(vs);
26783e230dd2SCorentin Chary             start_client_init(vs);
26797e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
26803e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
26817e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
26823e230dd2SCorentin Chary             vnc_flush(vs);
26833e230dd2SCorentin Chary             start_auth_vnc(vs);
26843e230dd2SCorentin Chary        } else {
26857e7e2ebcSDaniel P. Berrange             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
26863e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
26873e230dd2SCorentin Chary             vnc_flush(vs);
26883e230dd2SCorentin Chary             vnc_client_error(vs);
26893e230dd2SCorentin Chary        }
26903e230dd2SCorentin Chary     } else {
26917e7e2ebcSDaniel P. Berrange         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
26923e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
26937e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
26943e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
26953e230dd2SCorentin Chary         vnc_flush(vs);
26963e230dd2SCorentin Chary     }
26973e230dd2SCorentin Chary 
26983e230dd2SCorentin Chary     return 0;
26993e230dd2SCorentin Chary }
27003e230dd2SCorentin Chary 
2701999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2702999342a0SCorentin Chary {
2703999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2704999342a0SCorentin Chary 
2705999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2706999342a0SCorentin Chary }
2707999342a0SCorentin Chary 
27087d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
27097d964c9dSCorentin Chary {
27107d964c9dSCorentin Chary     int i, j;
27117d964c9dSCorentin Chary 
27127d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
27137d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
27147d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
27157d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
27167d964c9dSCorentin Chary 
2717207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2718207f328aSCorentin Chary         for (i = x; i <= w; i++) {
27197d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
27207d964c9dSCorentin Chary         }
27217d964c9dSCorentin Chary     }
27227d964c9dSCorentin Chary }
27237d964c9dSCorentin Chary 
27247d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
27257d964c9dSCorentin Chary {
27267d964c9dSCorentin Chary     VncState *vs;
27277d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
27287d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
27297d964c9dSCorentin Chary     int has_dirty = 0;
27307d964c9dSCorentin Chary 
27317d964c9dSCorentin Chary     y = y / VNC_STAT_RECT * VNC_STAT_RECT;
27327d964c9dSCorentin Chary     x = x / VNC_STAT_RECT * VNC_STAT_RECT;
27337d964c9dSCorentin Chary 
27347d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2735bc2429b9SCorentin Chary         int j;
27367d964c9dSCorentin Chary 
27377d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
27387d964c9dSCorentin Chary         if (vs->output.offset) {
27397d964c9dSCorentin Chary             continue;
27407d964c9dSCorentin Chary         }
27417d964c9dSCorentin Chary 
27427d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
27437d964c9dSCorentin Chary             continue;
27447d964c9dSCorentin Chary         }
2745207f328aSCorentin Chary 
27467d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
27477d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2748b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2749b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2750b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
27517d964c9dSCorentin Chary         }
27527d964c9dSCorentin Chary         has_dirty++;
27537d964c9dSCorentin Chary     }
2754207f328aSCorentin Chary 
27557d964c9dSCorentin Chary     return has_dirty;
27567d964c9dSCorentin Chary }
27577d964c9dSCorentin Chary 
27587d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2759999342a0SCorentin Chary {
27609f64916dSGerd Hoffmann     int width = pixman_image_get_width(vd->guest.fb);
27619f64916dSGerd Hoffmann     int height = pixman_image_get_height(vd->guest.fb);
2762999342a0SCorentin Chary     int x, y;
2763999342a0SCorentin Chary     struct timeval res;
27647d964c9dSCorentin Chary     int has_dirty = 0;
2765999342a0SCorentin Chary 
27669f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
27679f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2768999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2769999342a0SCorentin Chary 
2770999342a0SCorentin Chary             rect->updated = false;
2771999342a0SCorentin Chary         }
2772999342a0SCorentin Chary     }
2773999342a0SCorentin Chary 
2774ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2775999342a0SCorentin Chary 
2776999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
27777d964c9dSCorentin Chary         return has_dirty;
2778999342a0SCorentin Chary     }
2779999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
2780999342a0SCorentin Chary 
27819f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
27829f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2783999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2784999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
2785999342a0SCorentin Chary             struct timeval min, max;
2786999342a0SCorentin Chary 
2787999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
2788999342a0SCorentin Chary                 continue ;
2789999342a0SCorentin Chary             }
2790999342a0SCorentin Chary 
2791999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2792ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
2793999342a0SCorentin Chary 
2794999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2795999342a0SCorentin Chary                 rect->freq = 0;
27967d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2797999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
2798999342a0SCorentin Chary                 continue ;
2799999342a0SCorentin Chary             }
2800999342a0SCorentin Chary 
2801999342a0SCorentin Chary             min = rect->times[rect->idx];
2802999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2803ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
2804999342a0SCorentin Chary 
2805999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2806999342a0SCorentin Chary             rect->freq /= count;
2807999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
2808999342a0SCorentin Chary         }
2809999342a0SCorentin Chary     }
28107d964c9dSCorentin Chary     return has_dirty;
2811999342a0SCorentin Chary }
2812999342a0SCorentin Chary 
2813999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2814999342a0SCorentin Chary {
2815999342a0SCorentin Chary     int i, j;
2816999342a0SCorentin Chary     double total = 0;
2817999342a0SCorentin Chary     int num = 0;
2818999342a0SCorentin Chary 
2819999342a0SCorentin Chary     x =  (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2820999342a0SCorentin Chary     y =  (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2821999342a0SCorentin Chary 
2822999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2823999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2824999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
2825999342a0SCorentin Chary             num++;
2826999342a0SCorentin Chary         }
2827999342a0SCorentin Chary     }
2828999342a0SCorentin Chary 
2829999342a0SCorentin Chary     if (num) {
2830999342a0SCorentin Chary         return total / num;
2831999342a0SCorentin Chary     } else {
2832999342a0SCorentin Chary         return 0;
2833999342a0SCorentin Chary     }
2834999342a0SCorentin Chary }
2835999342a0SCorentin Chary 
2836999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2837999342a0SCorentin Chary {
2838999342a0SCorentin Chary     VncRectStat *rect;
2839999342a0SCorentin Chary 
2840999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
2841999342a0SCorentin Chary     if (rect->updated) {
2842999342a0SCorentin Chary         return ;
2843999342a0SCorentin Chary     }
2844999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
2845999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2846999342a0SCorentin Chary     rect->updated = true;
2847999342a0SCorentin Chary }
2848999342a0SCorentin Chary 
28493e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
28503e230dd2SCorentin Chary {
2851bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
2852bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
2853bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
2854bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
2855eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
285612b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
28573e230dd2SCorentin Chary     VncState *vs;
28583e230dd2SCorentin Chary     int has_dirty = 0;
28599f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
28603e230dd2SCorentin Chary 
286180e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
2862999342a0SCorentin Chary 
286380e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
2864999342a0SCorentin Chary         gettimeofday(&tv, NULL);
28657d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
286680e0c8c3SCorentin Chary     }
2867999342a0SCorentin Chary 
28683e230dd2SCorentin Chary     /*
28693e230dd2SCorentin Chary      * Walk through the guest dirty map.
28703e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
28713e230dd2SCorentin Chary      * Update server dirty map.
28723e230dd2SCorentin Chary      */
2873bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2874eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
2875eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
2876bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2877bea60dd7SPeter Lieven                     server_stride);
28789f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
28799f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
28809f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
288112b316d4SPeter Lieven     } else {
2882eb8934b0SGerd Hoffmann         int guest_bpp =
2883eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
288412b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
288512b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
2886eb8934b0SGerd Hoffmann         guest_ll = pixman_image_get_width(vd->guest.fb) * ((guest_bpp + 7) / 8);
28879f64916dSGerd Hoffmann     }
2888eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
288912b316d4SPeter Lieven 
289012b316d4SPeter Lieven     for (;;) {
28913e230dd2SCorentin Chary         int x;
289212b316d4SPeter Lieven         uint8_t *guest_ptr, *server_ptr;
289312b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
289412b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(&vd->guest),
289512b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(&vd->guest));
289612b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
289712b316d4SPeter Lieven             /* no more dirty bits */
289812b316d4SPeter Lieven             break;
289912b316d4SPeter Lieven         }
290012b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
290112b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
290212b316d4SPeter Lieven 
290312b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
29043e230dd2SCorentin Chary 
29059f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2906bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
29079f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
29089f64916dSGerd Hoffmann         } else {
290912b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
29109f64916dSGerd Hoffmann         }
291112b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
29123e230dd2SCorentin Chary 
291312b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
291412b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2915bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
291612b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
29173e230dd2SCorentin Chary                 continue;
2918b4c85ddcSPeter Lieven             }
2919eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
2920eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
2921bea60dd7SPeter Lieven             }
2922eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
2923bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
29243e230dd2SCorentin Chary                 continue;
2925b4c85ddcSPeter Lieven             }
2926bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
292712b316d4SPeter Lieven             if (!vd->non_adaptive) {
292812b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
292912b316d4SPeter Lieven                                  y, &tv);
293012b316d4SPeter Lieven             }
29313e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
293212b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
29333e230dd2SCorentin Chary             }
29343e230dd2SCorentin Chary             has_dirty++;
29353e230dd2SCorentin Chary         }
293612b316d4SPeter Lieven 
293712b316d4SPeter Lieven         y++;
29383e230dd2SCorentin Chary     }
29399f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
29403e230dd2SCorentin Chary     return has_dirty;
29413e230dd2SCorentin Chary }
29423e230dd2SCorentin Chary 
29430f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
29443e230dd2SCorentin Chary {
29450f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
29463e230dd2SCorentin Chary     VncState *vs, *vn;
29473e230dd2SCorentin Chary     int has_dirty, rects = 0;
29483e230dd2SCorentin Chary 
29499d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
29509d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
29519d6b2070SChenLiang         return;
29529d6b2070SChenLiang     }
29539d6b2070SChenLiang 
29541d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
29553e230dd2SCorentin Chary 
2956bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
29570f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2958bd023f95SCorentin Chary         return;
2959bd023f95SCorentin Chary     }
2960bd023f95SCorentin Chary 
29613e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
2962bd023f95SCorentin Chary     vnc_unlock_display(vd);
29633e230dd2SCorentin Chary 
29643e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
296538ee14f4SGerd Hoffmann         rects += vnc_update_client(vs, has_dirty, false);
29663e230dd2SCorentin Chary         /* vs might be free()ed here */
29673e230dd2SCorentin Chary     }
2968bd023f95SCorentin Chary 
29693e230dd2SCorentin Chary     if (has_dirty && rects) {
29700f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
29710f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
29720f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
29730f7b2864SGerd Hoffmann         }
29743e230dd2SCorentin Chary     } else {
29750f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
29760f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
29770f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
29783e230dd2SCorentin Chary         }
29793e230dd2SCorentin Chary     }
29803e230dd2SCorentin Chary }
29813e230dd2SCorentin Chary 
29822c8cf549SMichael Tokarev static void vnc_connect(VncDisplay *vd, int csock,
29832c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
29843e230dd2SCorentin Chary {
29857267c094SAnthony Liguori     VncState *vs = g_malloc0(sizeof(VncState));
29867d964c9dSCorentin Chary     int i;
29877d964c9dSCorentin Chary 
29883e230dd2SCorentin Chary     vs->csock = csock;
2989d616ccc5SGerd Hoffmann     vs->vd = vd;
29907e7e2ebcSDaniel P. Berrange 
29917e7e2ebcSDaniel P. Berrange     if (skipauth) {
29927e7e2ebcSDaniel P. Berrange 	vs->auth = VNC_AUTH_NONE;
29937e7e2ebcSDaniel P. Berrange 	vs->subauth = VNC_AUTH_INVALID;
29947e7e2ebcSDaniel P. Berrange     } else {
2995f9148c8aSDaniel P. Berrange         if (websocket) {
2996f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
2997f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
2998f9148c8aSDaniel P. Berrange         } else {
29997e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
30007e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
30017e7e2ebcSDaniel P. Berrange         }
3002f9148c8aSDaniel P. Berrange     }
3003f9148c8aSDaniel P. Berrange     VNC_DEBUG("Client sock=%d ws=%d auth=%d subauth=%d\n",
3004f9148c8aSDaniel P. Berrange               csock, websocket, vs->auth, vs->subauth);
30057e7e2ebcSDaniel P. Berrange 
30067267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
30077d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
30087267c094SAnthony Liguori         vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
30097d964c9dSCorentin Chary     }
30103e230dd2SCorentin Chary 
30113e230dd2SCorentin Chary     VNC_DEBUG("New client on socket %d\n", csock);
30120f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3013f9e8caccSStefan Hajnoczi     qemu_set_nonblock(vs->csock);
30147536ee4bSTim Hardeck     if (websocket) {
30157536ee4bSTim Hardeck         vs->websocket = 1;
3016f9148c8aSDaniel P. Berrange         if (vd->ws_tls) {
301782e1cc4bSFam Zheng             qemu_set_fd_handler(vs->csock, vncws_tls_handshake_io, NULL, vs);
30183e305e4aSDaniel P. Berrange         } else {
301982e1cc4bSFam Zheng             qemu_set_fd_handler(vs->csock, vncws_handshake_read, NULL, vs);
30200057a0d5STim Hardeck         }
30217536ee4bSTim Hardeck     } else
30227536ee4bSTim Hardeck     {
302382e1cc4bSFam Zheng         qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);
30247536ee4bSTim Hardeck     }
30253e230dd2SCorentin Chary 
30263e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3027fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
30288cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
30293e230dd2SCorentin Chary 
30308e9b0d24SDaniel P. Berrange     if (!vs->websocket) {
30317536ee4bSTim Hardeck         vnc_init_state(vs);
30327536ee4bSTim Hardeck     }
3033e5f34cddSGerd Hoffmann 
3034e5f34cddSGerd Hoffmann     if (vd->num_connecting > vd->connections_limit) {
3035e5f34cddSGerd Hoffmann         QTAILQ_FOREACH(vs, &vd->clients, next) {
3036e5f34cddSGerd Hoffmann             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3037e5f34cddSGerd Hoffmann                 vnc_disconnect_start(vs);
3038e5f34cddSGerd Hoffmann                 return;
3039e5f34cddSGerd Hoffmann             }
3040e5f34cddSGerd Hoffmann         }
3041e5f34cddSGerd Hoffmann     }
30427536ee4bSTim Hardeck }
30437536ee4bSTim Hardeck 
30447536ee4bSTim Hardeck void vnc_init_state(VncState *vs)
30457536ee4bSTim Hardeck {
30466fd8e79aSTim Hardeck     vs->initialized = true;
30477536ee4bSTim Hardeck     VncDisplay *vd = vs->vd;
30487536ee4bSTim Hardeck 
30493e230dd2SCorentin Chary     vs->last_x = -1;
30503e230dd2SCorentin Chary     vs->last_y = -1;
30513e230dd2SCorentin Chary 
30523e230dd2SCorentin Chary     vs->as.freq = 44100;
30533e230dd2SCorentin Chary     vs->as.nchannels = 2;
30543e230dd2SCorentin Chary     vs->as.fmt = AUD_FMT_S16;
30553e230dd2SCorentin Chary     vs->as.endianness = 0;
30563e230dd2SCorentin Chary 
3057bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3058175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3059bd023f95SCorentin Chary 
3060e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
30613e230dd2SCorentin Chary 
30621d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
30633e230dd2SCorentin Chary 
30643e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
30653e230dd2SCorentin Chary     vnc_flush(vs);
30663e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
30673e230dd2SCorentin Chary     reset_keys(vs);
30683e230dd2SCorentin Chary     if (vs->vd->lock_key_sync)
30693e230dd2SCorentin Chary         vs->led = qemu_add_led_event_handler(kbd_leds, vs);
30703e230dd2SCorentin Chary 
30713e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
30723e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
30733e230dd2SCorentin Chary 
30743e230dd2SCorentin Chary     /* vs might be free()ed here */
30753e230dd2SCorentin Chary }
30763e230dd2SCorentin Chary 
30777536ee4bSTim Hardeck static void vnc_listen_read(void *opaque, bool websocket)
30783e230dd2SCorentin Chary {
30793e230dd2SCorentin Chary     VncDisplay *vs = opaque;
30803e230dd2SCorentin Chary     struct sockaddr_in addr;
30813e230dd2SCorentin Chary     socklen_t addrlen = sizeof(addr);
30827536ee4bSTim Hardeck     int csock;
30833e230dd2SCorentin Chary 
30843e230dd2SCorentin Chary     /* Catch-up */
30851d0d59feSGerd Hoffmann     graphic_hw_update(vs->dcl.con);
30867536ee4bSTim Hardeck     if (websocket) {
30877536ee4bSTim Hardeck         csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
30888e9b0d24SDaniel P. Berrange     } else {
30897536ee4bSTim Hardeck         csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
30907536ee4bSTim Hardeck     }
30913e230dd2SCorentin Chary 
30923e230dd2SCorentin Chary     if (csock != -1) {
309386152436SPeter Lieven         socket_set_nodelay(csock);
30942c8cf549SMichael Tokarev         vnc_connect(vs, csock, false, websocket);
30953e230dd2SCorentin Chary     }
30963e230dd2SCorentin Chary }
30973e230dd2SCorentin Chary 
30987536ee4bSTim Hardeck static void vnc_listen_regular_read(void *opaque)
30997536ee4bSTim Hardeck {
31002c8cf549SMichael Tokarev     vnc_listen_read(opaque, false);
31017536ee4bSTim Hardeck }
31027536ee4bSTim Hardeck 
31037536ee4bSTim Hardeck static void vnc_listen_websocket_read(void *opaque)
31047536ee4bSTim Hardeck {
31052c8cf549SMichael Tokarev     vnc_listen_read(opaque, true);
31067536ee4bSTim Hardeck }
31077536ee4bSTim Hardeck 
31087c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
31097c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
31100f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
31117c20b4a3SGerd Hoffmann     .dpy_gfx_copy         = vnc_dpy_copy,
31127c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3113c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
311434da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
31157c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
31167c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
31177c20b4a3SGerd Hoffmann };
31187c20b4a3SGerd Hoffmann 
311914f7143eSGerd Hoffmann void vnc_display_init(const char *id)
31203e230dd2SCorentin Chary {
31214db14629SGerd Hoffmann     VncDisplay *vs;
31224db14629SGerd Hoffmann 
31234db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
31244db14629SGerd Hoffmann         return;
31254db14629SGerd Hoffmann     }
31264db14629SGerd Hoffmann     vs = g_malloc0(sizeof(*vs));
31273e230dd2SCorentin Chary 
312814f7143eSGerd Hoffmann     vs->id = strdup(id);
3129d616ccc5SGerd Hoffmann     QTAILQ_INSERT_TAIL(&vnc_displays, vs, next);
31303e230dd2SCorentin Chary 
31313e230dd2SCorentin Chary     vs->lsock = -1;
31327536ee4bSTim Hardeck     vs->lwebsock = -1;
31333e230dd2SCorentin Chary 
31343e230dd2SCorentin Chary     QTAILQ_INIT(&vs->clients);
31353c9405a0SGerd Hoffmann     vs->expires = TIME_MAX;
31363e230dd2SCorentin Chary 
313740066175SGerd Hoffmann     if (keyboard_layout) {
313840066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
31393e230dd2SCorentin Chary         vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
314040066175SGerd Hoffmann     } else {
31413e230dd2SCorentin Chary         vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
314240066175SGerd Hoffmann     }
31433e230dd2SCorentin Chary 
31443e230dd2SCorentin Chary     if (!vs->kbd_layout)
31453e230dd2SCorentin Chary         exit(1);
31463e230dd2SCorentin Chary 
3147bd023f95SCorentin Chary     qemu_mutex_init(&vs->mutex);
3148bd023f95SCorentin Chary     vnc_start_worker_thread();
3149bd023f95SCorentin Chary 
315021ef45d7SGerd Hoffmann     vs->dcl.ops = &dcl_ops;
31515209089fSGerd Hoffmann     register_displaychangelistener(&vs->dcl);
31523e230dd2SCorentin Chary }
31533e230dd2SCorentin Chary 
31543e230dd2SCorentin Chary 
315514f7143eSGerd Hoffmann static void vnc_display_close(VncDisplay *vs)
31563e230dd2SCorentin Chary {
31573e230dd2SCorentin Chary     if (!vs)
31583e230dd2SCorentin Chary         return;
3159bf7aa45eSGerd Hoffmann     vs->enabled = false;
3160bf7aa45eSGerd Hoffmann     vs->is_unix = false;
31613e230dd2SCorentin Chary     if (vs->lsock != -1) {
316282e1cc4bSFam Zheng         qemu_set_fd_handler(vs->lsock, NULL, NULL, NULL);
31633e230dd2SCorentin Chary         close(vs->lsock);
31643e230dd2SCorentin Chary         vs->lsock = -1;
31653e230dd2SCorentin Chary     }
3166bf7aa45eSGerd Hoffmann     vs->ws_enabled = false;
31677536ee4bSTim Hardeck     if (vs->lwebsock != -1) {
316882e1cc4bSFam Zheng         qemu_set_fd_handler(vs->lwebsock, NULL, NULL, NULL);
31697536ee4bSTim Hardeck         close(vs->lwebsock);
31707536ee4bSTim Hardeck         vs->lwebsock = -1;
31717536ee4bSTim Hardeck     }
31723e230dd2SCorentin Chary     vs->auth = VNC_AUTH_INVALID;
31733e230dd2SCorentin Chary     vs->subauth = VNC_AUTH_INVALID;
31743e305e4aSDaniel P. Berrange     if (vs->tlscreds) {
31753e305e4aSDaniel P. Berrange         object_unparent(OBJECT(vs->tlscreds));
31763e305e4aSDaniel P. Berrange     }
31773e305e4aSDaniel P. Berrange     g_free(vs->tlsaclname);
31783e305e4aSDaniel P. Berrange     vs->tlsaclname = NULL;
31793e230dd2SCorentin Chary }
31803e230dd2SCorentin Chary 
318114f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
31821cd20f8bSAnthony Liguori {
318314f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
31841cd20f8bSAnthony Liguori 
31851cd20f8bSAnthony Liguori     if (!vs) {
3186a6aa9d3eSLuiz Capitulino         return -EINVAL;
31871cd20f8bSAnthony Liguori     }
3188cf864569SGerd Hoffmann     if (vs->auth == VNC_AUTH_NONE) {
3189cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
3190cf864569SGerd Hoffmann                                 "password auth using '-vnc ${dpy},password'.");
3191cf864569SGerd Hoffmann         return -EINVAL;
31921cd20f8bSAnthony Liguori     }
31931cd20f8bSAnthony Liguori 
31947267c094SAnthony Liguori     g_free(vs->password);
31957267c094SAnthony Liguori     vs->password = g_strdup(password);
3196a6aa9d3eSLuiz Capitulino 
3197a6aa9d3eSLuiz Capitulino     return 0;
31983e230dd2SCorentin Chary }
31993e230dd2SCorentin Chary 
320014f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
32013c9405a0SGerd Hoffmann {
320214f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
32033c9405a0SGerd Hoffmann 
32041643f2b2SGerd Hoffmann     if (!vs) {
32051643f2b2SGerd Hoffmann         return -EINVAL;
32061643f2b2SGerd Hoffmann     }
32071643f2b2SGerd Hoffmann 
32083c9405a0SGerd Hoffmann     vs->expires = expires;
32093c9405a0SGerd Hoffmann     return 0;
32103c9405a0SGerd Hoffmann }
32113c9405a0SGerd Hoffmann 
321214f7143eSGerd Hoffmann char *vnc_display_local_addr(const char *id)
32133e230dd2SCorentin Chary {
321414f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
32153e230dd2SCorentin Chary 
32169e0ff75eSGerd Hoffmann     assert(vs);
32173e230dd2SCorentin Chary     return vnc_socket_local_addr("%s:%s", vs->lsock);
32183e230dd2SCorentin Chary }
32193e230dd2SCorentin Chary 
32204db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
32214db14629SGerd Hoffmann     .name = "vnc",
32224db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
32234db14629SGerd Hoffmann     .implied_opt_name = "vnc",
32244db14629SGerd Hoffmann     .desc = {
32254db14629SGerd Hoffmann         {
32264db14629SGerd Hoffmann             .name = "vnc",
32274db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32284db14629SGerd Hoffmann         },{
32294db14629SGerd Hoffmann             .name = "websocket",
32304db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32314db14629SGerd Hoffmann         },{
32323e305e4aSDaniel P. Berrange             .name = "tls-creds",
32333e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
32343e305e4aSDaniel P. Berrange         },{
32353e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
32364db14629SGerd Hoffmann             .name = "x509",
32374db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32384db14629SGerd Hoffmann         },{
32394db14629SGerd Hoffmann             .name = "share",
32404db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32414db14629SGerd Hoffmann         },{
32421d0d59feSGerd Hoffmann             .name = "display",
32431d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
32441d0d59feSGerd Hoffmann         },{
32451d0d59feSGerd Hoffmann             .name = "head",
32461d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
32471d0d59feSGerd Hoffmann         },{
3248e5f34cddSGerd Hoffmann             .name = "connections",
3249e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3250e5f34cddSGerd Hoffmann         },{
325188428b7aSGonglei             .name = "to",
325288428b7aSGonglei             .type = QEMU_OPT_NUMBER,
325388428b7aSGonglei         },{
325488428b7aSGonglei             .name = "ipv4",
325588428b7aSGonglei             .type = QEMU_OPT_BOOL,
325688428b7aSGonglei         },{
325788428b7aSGonglei             .name = "ipv6",
325888428b7aSGonglei             .type = QEMU_OPT_BOOL,
325988428b7aSGonglei         },{
32604db14629SGerd Hoffmann             .name = "password",
32614db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32624db14629SGerd Hoffmann         },{
32634db14629SGerd Hoffmann             .name = "reverse",
32644db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32654db14629SGerd Hoffmann         },{
32664db14629SGerd Hoffmann             .name = "lock-key-sync",
32674db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32684db14629SGerd Hoffmann         },{
32694db14629SGerd Hoffmann             .name = "sasl",
32704db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32714db14629SGerd Hoffmann         },{
32723e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
32734db14629SGerd Hoffmann             .name = "tls",
32744db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32754db14629SGerd Hoffmann         },{
32763e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
32774db14629SGerd Hoffmann             .name = "x509verify",
32788c7d0645SDaniel P. Berrange             .type = QEMU_OPT_STRING,
32794db14629SGerd Hoffmann         },{
32804db14629SGerd Hoffmann             .name = "acl",
32814db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32824db14629SGerd Hoffmann         },{
32834db14629SGerd Hoffmann             .name = "lossy",
32844db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32854db14629SGerd Hoffmann         },{
32864db14629SGerd Hoffmann             .name = "non-adaptive",
32874db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32884db14629SGerd Hoffmann         },
32894db14629SGerd Hoffmann         { /* end of list */ }
32904db14629SGerd Hoffmann     },
32914db14629SGerd Hoffmann };
32924db14629SGerd Hoffmann 
32930dd72e15SDaniel P. Berrange 
32943e305e4aSDaniel P. Berrange static int
32950dd72e15SDaniel P. Berrange vnc_display_setup_auth(VncDisplay *vs,
32960dd72e15SDaniel P. Berrange                        bool password,
32970dd72e15SDaniel P. Berrange                        bool sasl,
32983e305e4aSDaniel P. Berrange                        bool websocket,
32993e305e4aSDaniel P. Berrange                        Error **errp)
33000dd72e15SDaniel P. Berrange {
33010dd72e15SDaniel P. Berrange     /*
33020dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
33030dd72e15SDaniel P. Berrange      *
33040dd72e15SDaniel P. Berrange      *   1. none
33050dd72e15SDaniel P. Berrange      *   2. vnc
33060dd72e15SDaniel P. Berrange      *   3. sasl
33070dd72e15SDaniel P. Berrange      *
33080dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
33090dd72e15SDaniel P. Berrange      *
33100dd72e15SDaniel P. Berrange      *   1. clear
33110dd72e15SDaniel P. Berrange      *   2. tls
33120dd72e15SDaniel P. Berrange      *
33130dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
33140dd72e15SDaniel P. Berrange      *
33150dd72e15SDaniel P. Berrange      *   1. anon
33160dd72e15SDaniel P. Berrange      *   2. x509
33170dd72e15SDaniel P. Berrange      *
33180dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
33190dd72e15SDaniel P. Berrange      *
33200dd72e15SDaniel P. Berrange      *   1. clear + none
33210dd72e15SDaniel P. Berrange      *   2. clear + vnc
33220dd72e15SDaniel P. Berrange      *   3. clear + sasl
33230dd72e15SDaniel P. Berrange      *   4. tls + anon + none
33240dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
33250dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
33260dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
33270dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
33280dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
33290dd72e15SDaniel P. Berrange      *
33300dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
33310dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
33320dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
33330dd72e15SDaniel P. Berrange      * sub-auth types.
3334f9148c8aSDaniel P. Berrange      *
3335f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3336f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3337f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3338f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3339f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3340f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3341f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3342f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3343f9148c8aSDaniel P. Berrange      *
3344f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3345f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3346f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
33470dd72e15SDaniel P. Berrange      */
33480dd72e15SDaniel P. Berrange     if (password) {
33493e305e4aSDaniel P. Berrange         if (vs->tlscreds) {
33500dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VENCRYPT;
3351f9148c8aSDaniel P. Berrange             if (websocket) {
3352f9148c8aSDaniel P. Berrange                 vs->ws_tls = true;
3353f9148c8aSDaniel P. Berrange             }
33543e305e4aSDaniel P. Berrange             if (object_dynamic_cast(OBJECT(vs->tlscreds),
33553e305e4aSDaniel P. Berrange                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
33560dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
33570dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
33583e305e4aSDaniel P. Berrange             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
33593e305e4aSDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
33600dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
33610dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
33623e305e4aSDaniel P. Berrange             } else {
33633e305e4aSDaniel P. Berrange                 error_setg(errp,
33643e305e4aSDaniel P. Berrange                            "Unsupported TLS cred type %s",
33653e305e4aSDaniel P. Berrange                            object_get_typename(OBJECT(vs->tlscreds)));
33663e305e4aSDaniel P. Berrange                 return -1;
33670dd72e15SDaniel P. Berrange             }
33680dd72e15SDaniel P. Berrange         } else {
33690dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
33700dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VNC;
33710dd72e15SDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
33720dd72e15SDaniel P. Berrange         }
3373f9148c8aSDaniel P. Berrange         if (websocket) {
3374f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_VNC;
3375f9148c8aSDaniel P. Berrange         } else {
3376f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_INVALID;
3377f9148c8aSDaniel P. Berrange         }
33780dd72e15SDaniel P. Berrange     } else if (sasl) {
33793e305e4aSDaniel P. Berrange         if (vs->tlscreds) {
33800dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VENCRYPT;
3381f9148c8aSDaniel P. Berrange             if (websocket) {
3382f9148c8aSDaniel P. Berrange                 vs->ws_tls = true;
3383f9148c8aSDaniel P. Berrange             }
33843e305e4aSDaniel P. Berrange             if (object_dynamic_cast(OBJECT(vs->tlscreds),
33853e305e4aSDaniel P. Berrange                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
33860dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
33870dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
33883e305e4aSDaniel P. Berrange             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
33893e305e4aSDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
33900dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
33910dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
33923e305e4aSDaniel P. Berrange             } else {
33933e305e4aSDaniel P. Berrange                 error_setg(errp,
33943e305e4aSDaniel P. Berrange                            "Unsupported TLS cred type %s",
33953e305e4aSDaniel P. Berrange                            object_get_typename(OBJECT(vs->tlscreds)));
33963e305e4aSDaniel P. Berrange                 return -1;
33970dd72e15SDaniel P. Berrange             }
33980dd72e15SDaniel P. Berrange         } else {
33990dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
34000dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_SASL;
34010dd72e15SDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
34020dd72e15SDaniel P. Berrange         }
3403f9148c8aSDaniel P. Berrange         if (websocket) {
3404f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_SASL;
3405f9148c8aSDaniel P. Berrange         } else {
3406f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_INVALID;
3407f9148c8aSDaniel P. Berrange         }
34080dd72e15SDaniel P. Berrange     } else {
34093e305e4aSDaniel P. Berrange         if (vs->tlscreds) {
34100dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VENCRYPT;
3411f9148c8aSDaniel P. Berrange             if (websocket) {
3412f9148c8aSDaniel P. Berrange                 vs->ws_tls = true;
3413f9148c8aSDaniel P. Berrange             }
34143e305e4aSDaniel P. Berrange             if (object_dynamic_cast(OBJECT(vs->tlscreds),
34153e305e4aSDaniel P. Berrange                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
34160dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
34170dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
34183e305e4aSDaniel P. Berrange             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
34193e305e4aSDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
34200dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
34210dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
34223e305e4aSDaniel P. Berrange             } else {
34233e305e4aSDaniel P. Berrange                 error_setg(errp,
34243e305e4aSDaniel P. Berrange                            "Unsupported TLS cred type %s",
34253e305e4aSDaniel P. Berrange                            object_get_typename(OBJECT(vs->tlscreds)));
34263e305e4aSDaniel P. Berrange                 return -1;
34270dd72e15SDaniel P. Berrange             }
34280dd72e15SDaniel P. Berrange         } else {
34290dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
34300dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_NONE;
34310dd72e15SDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
34320dd72e15SDaniel P. Berrange         }
3433f9148c8aSDaniel P. Berrange         if (websocket) {
3434f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_NONE;
3435f9148c8aSDaniel P. Berrange         } else {
3436f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_INVALID;
3437f9148c8aSDaniel P. Berrange         }
34380dd72e15SDaniel P. Berrange     }
34393e305e4aSDaniel P. Berrange     return 0;
34400dd72e15SDaniel P. Berrange }
34410dd72e15SDaniel P. Berrange 
34423e305e4aSDaniel P. Berrange 
34433e305e4aSDaniel P. Berrange /*
34443e305e4aSDaniel P. Berrange  * Handle back compat with old CLI syntax by creating some
34453e305e4aSDaniel P. Berrange  * suitable QCryptoTLSCreds objects
34463e305e4aSDaniel P. Berrange  */
34473e305e4aSDaniel P. Berrange static QCryptoTLSCreds *
34483e305e4aSDaniel P. Berrange vnc_display_create_creds(bool x509,
34493e305e4aSDaniel P. Berrange                          bool x509verify,
34503e305e4aSDaniel P. Berrange                          const char *dir,
34513e305e4aSDaniel P. Berrange                          const char *id,
34523e305e4aSDaniel P. Berrange                          Error **errp)
34533e305e4aSDaniel P. Berrange {
34543e305e4aSDaniel P. Berrange     gchar *credsid = g_strdup_printf("tlsvnc%s", id);
34553e305e4aSDaniel P. Berrange     Object *parent = object_get_objects_root();
34563e305e4aSDaniel P. Berrange     Object *creds;
34573e305e4aSDaniel P. Berrange     Error *err = NULL;
34583e305e4aSDaniel P. Berrange 
34593e305e4aSDaniel P. Berrange     if (x509) {
34603e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
34613e305e4aSDaniel P. Berrange                                       parent,
34623e305e4aSDaniel P. Berrange                                       credsid,
34633e305e4aSDaniel P. Berrange                                       &err,
34643e305e4aSDaniel P. Berrange                                       "endpoint", "server",
34653e305e4aSDaniel P. Berrange                                       "dir", dir,
34663e305e4aSDaniel P. Berrange                                       "verify-peer", x509verify ? "yes" : "no",
34673e305e4aSDaniel P. Berrange                                       NULL);
34683e305e4aSDaniel P. Berrange     } else {
34693e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
34703e305e4aSDaniel P. Berrange                                       parent,
34713e305e4aSDaniel P. Berrange                                       credsid,
34723e305e4aSDaniel P. Berrange                                       &err,
34733e305e4aSDaniel P. Berrange                                       "endpoint", "server",
34743e305e4aSDaniel P. Berrange                                       NULL);
34753e305e4aSDaniel P. Berrange     }
34763e305e4aSDaniel P. Berrange 
34773e305e4aSDaniel P. Berrange     g_free(credsid);
34783e305e4aSDaniel P. Berrange 
34793e305e4aSDaniel P. Berrange     if (err) {
34803e305e4aSDaniel P. Berrange         error_propagate(errp, err);
34813e305e4aSDaniel P. Berrange         return NULL;
34823e305e4aSDaniel P. Berrange     }
34833e305e4aSDaniel P. Berrange 
34843e305e4aSDaniel P. Berrange     return QCRYPTO_TLS_CREDS(creds);
34853e305e4aSDaniel P. Berrange }
34863e305e4aSDaniel P. Berrange 
34873e305e4aSDaniel P. Berrange 
34884db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
34893e230dd2SCorentin Chary {
349014f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
34914db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3492e0d03b8cSDaniel P. Berrange     SocketAddress *saddr = NULL, *wsaddr = NULL;
3493e2a11d9dSGonglei     const char *share, *device_id;
34941d0d59feSGerd Hoffmann     QemuConsole *con;
3495a2c72de0SGonglei     bool password = false;
3496a2c72de0SGonglei     bool reverse = false;
3497e2a11d9dSGonglei     const char *vnc;
3498e5560329SGerd Hoffmann     char *h;
34993e305e4aSDaniel P. Berrange     const char *credid;
3500a2c72de0SGonglei     bool sasl = false;
3501d169f04bSDaniel P. Berrange #ifdef CONFIG_VNC_SASL
35023e230dd2SCorentin Chary     int saslErr;
35033e230dd2SCorentin Chary #endif
35043e230dd2SCorentin Chary     int acl = 0;
35053e230dd2SCorentin Chary     int lock_key_sync = 1;
35063e230dd2SCorentin Chary 
3507d616ccc5SGerd Hoffmann     if (!vs) {
35082d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
35092d55f0e8SPaolo Bonzini         return;
35102d55f0e8SPaolo Bonzini     }
351114f7143eSGerd Hoffmann     vnc_display_close(vs);
35124db14629SGerd Hoffmann 
35134db14629SGerd Hoffmann     if (!opts) {
35142d55f0e8SPaolo Bonzini         return;
35154db14629SGerd Hoffmann     }
3516e2a11d9dSGonglei     vnc = qemu_opt_get(opts, "vnc");
3517e2a11d9dSGonglei     if (!vnc || strcmp(vnc, "none") == 0) {
35184db14629SGerd Hoffmann         return;
35194db14629SGerd Hoffmann     }
3520e2a11d9dSGonglei 
3521e5560329SGerd Hoffmann     h = strrchr(vnc, ':');
3522e5560329SGerd Hoffmann     if (h) {
3523274c3b52SJán Tomko         size_t hlen = h - vnc;
3524274c3b52SJán Tomko 
3525e0d03b8cSDaniel P. Berrange         const char *websocket = qemu_opt_get(opts, "websocket");
3526e0d03b8cSDaniel P. Berrange         int to = qemu_opt_get_number(opts, "to", 0);
3527e0d03b8cSDaniel P. Berrange         bool has_ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3528e0d03b8cSDaniel P. Berrange         bool has_ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3529e0d03b8cSDaniel P. Berrange 
3530e0d03b8cSDaniel P. Berrange         saddr = g_new0(SocketAddress, 1);
3531e0d03b8cSDaniel P. Berrange         if (websocket) {
3532e0d03b8cSDaniel P. Berrange             if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3533e0d03b8cSDaniel P. Berrange                 error_setg(errp,
3534e0d03b8cSDaniel P. Berrange                            "SHA1 hash support is required for websockets");
3535e5560329SGerd Hoffmann                 goto fail;
3536e2a11d9dSGonglei             }
3537e5560329SGerd Hoffmann 
3538e0d03b8cSDaniel P. Berrange             wsaddr = g_new0(SocketAddress, 1);
3539e0d03b8cSDaniel P. Berrange             vs->ws_enabled = true;
3540e5560329SGerd Hoffmann         }
3541e0d03b8cSDaniel P. Berrange 
3542e0d03b8cSDaniel P. Berrange         if (strncmp(vnc, "unix:", 5) == 0) {
35432d32addaSEric Blake             saddr->type = SOCKET_ADDRESS_KIND_UNIX;
35442d32addaSEric Blake             saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
35452d32addaSEric Blake             saddr->u.q_unix->path = g_strdup(vnc + 5);
3546e0d03b8cSDaniel P. Berrange 
3547e0d03b8cSDaniel P. Berrange             if (vs->ws_enabled) {
3548e0d03b8cSDaniel P. Berrange                 error_setg(errp, "UNIX sockets not supported with websock");
3549e0d03b8cSDaniel P. Berrange                 goto fail;
3550e5560329SGerd Hoffmann             }
3551e0d03b8cSDaniel P. Berrange         } else {
3552e0d03b8cSDaniel P. Berrange             unsigned long long baseport;
35532d32addaSEric Blake             saddr->type = SOCKET_ADDRESS_KIND_INET;
35542d32addaSEric Blake             saddr->u.inet = g_new0(InetSocketAddress, 1);
3555e0d03b8cSDaniel P. Berrange             if (vnc[0] == '[' && vnc[hlen - 1] == ']') {
35562d32addaSEric Blake                 saddr->u.inet->host = g_strndup(vnc + 1, hlen - 2);
3557e0d03b8cSDaniel P. Berrange             } else {
35582d32addaSEric Blake                 saddr->u.inet->host = g_strndup(vnc, hlen);
3559e0d03b8cSDaniel P. Berrange             }
3560e0d03b8cSDaniel P. Berrange             if (parse_uint_full(h + 1, &baseport, 10) < 0) {
3561e0d03b8cSDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", h + 1);
3562e0d03b8cSDaniel P. Berrange                 goto fail;
3563e0d03b8cSDaniel P. Berrange             }
3564e0d03b8cSDaniel P. Berrange             if (baseport > 65535 ||
3565e0d03b8cSDaniel P. Berrange                 baseport + 5900 > 65535) {
3566e0d03b8cSDaniel P. Berrange                 error_setg(errp, "port %s out of range", h + 1);
3567e0d03b8cSDaniel P. Berrange                 goto fail;
3568e0d03b8cSDaniel P. Berrange             }
35692d32addaSEric Blake             saddr->u.inet->port = g_strdup_printf(
3570e0d03b8cSDaniel P. Berrange                 "%d", (int)baseport + 5900);
3571e0d03b8cSDaniel P. Berrange 
3572e0d03b8cSDaniel P. Berrange             if (to) {
35732d32addaSEric Blake                 saddr->u.inet->has_to = true;
35742d32addaSEric Blake                 saddr->u.inet->to = to;
3575e0d03b8cSDaniel P. Berrange             }
35762d32addaSEric Blake             saddr->u.inet->ipv4 = saddr->u.inet->has_ipv4 = has_ipv4;
35772d32addaSEric Blake             saddr->u.inet->ipv6 = saddr->u.inet->has_ipv6 = has_ipv6;
3578e0d03b8cSDaniel P. Berrange 
3579e0d03b8cSDaniel P. Berrange             if (vs->ws_enabled) {
35802d32addaSEric Blake                 wsaddr->type = SOCKET_ADDRESS_KIND_INET;
35812d32addaSEric Blake                 wsaddr->u.inet = g_new0(InetSocketAddress, 1);
35822d32addaSEric Blake                 wsaddr->u.inet->host = g_strdup(saddr->u.inet->host);
35832d32addaSEric Blake                 wsaddr->u.inet->port = g_strdup(websocket);
3584e0d03b8cSDaniel P. Berrange 
3585e0d03b8cSDaniel P. Berrange                 if (to) {
35862d32addaSEric Blake                     wsaddr->u.inet->has_to = true;
35872d32addaSEric Blake                     wsaddr->u.inet->to = to;
3588e0d03b8cSDaniel P. Berrange                 }
35892d32addaSEric Blake                 wsaddr->u.inet->ipv4 = wsaddr->u.inet->has_ipv4 = has_ipv4;
35902d32addaSEric Blake                 wsaddr->u.inet->ipv6 = wsaddr->u.inet->has_ipv6 = has_ipv6;
3591e0d03b8cSDaniel P. Berrange             }
3592e0d03b8cSDaniel P. Berrange         }
3593e0d03b8cSDaniel P. Berrange     } else {
3594e0d03b8cSDaniel P. Berrange         error_setg(errp, "no vnc port specified");
3595e0d03b8cSDaniel P. Berrange         goto fail;
3596e5560329SGerd Hoffmann     }
35973e230dd2SCorentin Chary 
35984db14629SGerd Hoffmann     password = qemu_opt_get_bool(opts, "password", false);
3599800567a6SDaniel P. Berrange     if (password) {
3600800567a6SDaniel P. Berrange         if (fips_get_state()) {
36012d55f0e8SPaolo Bonzini             error_setg(errp,
36020f66998fSPaul Moore                        "VNC password auth disabled due to FIPS mode, "
36030f66998fSPaul Moore                        "consider using the VeNCrypt or SASL authentication "
36042d55f0e8SPaolo Bonzini                        "methods as an alternative");
36051ce52c78SPaolo Bonzini             goto fail;
36060f66998fSPaul Moore         }
3607800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
3608800567a6SDaniel P. Berrange                 QCRYPTO_CIPHER_ALG_DES_RFB)) {
3609800567a6SDaniel P. Berrange             error_setg(errp,
3610800567a6SDaniel P. Berrange                        "Cipher backend does not support DES RFB algorithm");
3611800567a6SDaniel P. Berrange             goto fail;
3612800567a6SDaniel P. Berrange         }
3613800567a6SDaniel P. Berrange     }
36144db14629SGerd Hoffmann 
36154db14629SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
36164db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
36174db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
3618d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
3619d169f04bSDaniel P. Berrange     if (sasl) {
3620d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3621d169f04bSDaniel P. Berrange         goto fail;
3622d169f04bSDaniel P. Berrange     }
3623d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
36243e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
36253e305e4aSDaniel P. Berrange     if (credid) {
36263e305e4aSDaniel P. Berrange         Object *creds;
36273e305e4aSDaniel P. Berrange         if (qemu_opt_get(opts, "tls") ||
36283e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509") ||
36293e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509verify")) {
36303e305e4aSDaniel P. Berrange             error_setg(errp,
36313e305e4aSDaniel P. Berrange                        "'credid' parameter is mutually exclusive with "
36323e305e4aSDaniel P. Berrange                        "'tls', 'x509' and 'x509verify' parameters");
36333e305e4aSDaniel P. Berrange             goto fail;
36343e305e4aSDaniel P. Berrange         }
36353e305e4aSDaniel P. Berrange 
36363e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
36373e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
36383e305e4aSDaniel P. Berrange         if (!creds) {
36393e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
36403e305e4aSDaniel P. Berrange                        credid);
36413e305e4aSDaniel P. Berrange             goto fail;
36423e305e4aSDaniel P. Berrange         }
36433e305e4aSDaniel P. Berrange         vs->tlscreds = (QCryptoTLSCreds *)
36443e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
36453e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
36463e305e4aSDaniel P. Berrange         if (!vs->tlscreds) {
36473e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
36483e305e4aSDaniel P. Berrange                        credid);
36493e305e4aSDaniel P. Berrange             goto fail;
36503e305e4aSDaniel P. Berrange         }
36513e305e4aSDaniel P. Berrange         object_ref(OBJECT(vs->tlscreds));
36523e305e4aSDaniel P. Berrange 
36533e305e4aSDaniel P. Berrange         if (vs->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
36543e305e4aSDaniel P. Berrange             error_setg(errp,
36553e305e4aSDaniel P. Berrange                        "Expecting TLS credentials with a server endpoint");
36563e305e4aSDaniel P. Berrange             goto fail;
36573e305e4aSDaniel P. Berrange         }
36583e305e4aSDaniel P. Berrange     } else {
36593e305e4aSDaniel P. Berrange         const char *path;
36603e305e4aSDaniel P. Berrange         bool tls = false, x509 = false, x509verify = false;
36614db14629SGerd Hoffmann         tls  = qemu_opt_get_bool(opts, "tls", false);
36623e305e4aSDaniel P. Berrange         if (tls) {
36634db14629SGerd Hoffmann             path = qemu_opt_get(opts, "x509");
36643e305e4aSDaniel P. Berrange 
36654db14629SGerd Hoffmann             if (path) {
3666a2c72de0SGonglei                 x509 = true;
36673e305e4aSDaniel P. Berrange             } else {
36683e305e4aSDaniel P. Berrange                 path = qemu_opt_get(opts, "x509verify");
36693e305e4aSDaniel P. Berrange                 if (path) {
36703e305e4aSDaniel P. Berrange                     x509 = true;
36713e305e4aSDaniel P. Berrange                     x509verify = true;
36723e305e4aSDaniel P. Berrange                 }
36733e305e4aSDaniel P. Berrange             }
36743e305e4aSDaniel P. Berrange             vs->tlscreds = vnc_display_create_creds(x509,
36753e305e4aSDaniel P. Berrange                                                     x509verify,
36763e305e4aSDaniel P. Berrange                                                     path,
36773e305e4aSDaniel P. Berrange                                                     vs->id,
36783e305e4aSDaniel P. Berrange                                                     errp);
36793e305e4aSDaniel P. Berrange             if (!vs->tlscreds) {
36801ce52c78SPaolo Bonzini                 goto fail;
36813e230dd2SCorentin Chary             }
36823e230dd2SCorentin Chary         }
3683d169f04bSDaniel P. Berrange     }
36844db14629SGerd Hoffmann     acl = qemu_opt_get_bool(opts, "acl", false);
36854db14629SGerd Hoffmann 
36864db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
36874db14629SGerd Hoffmann     if (share) {
36884db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
36898cf36489SGerd Hoffmann             vs->share_policy = VNC_SHARE_POLICY_IGNORE;
36904db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
36918cf36489SGerd Hoffmann             vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
36924db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
36938cf36489SGerd Hoffmann             vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
36948cf36489SGerd Hoffmann         } else {
36952d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
36961ce52c78SPaolo Bonzini             goto fail;
36978cf36489SGerd Hoffmann         }
36984db14629SGerd Hoffmann     } else {
36994db14629SGerd Hoffmann         vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
37003e230dd2SCorentin Chary     }
3701e5f34cddSGerd Hoffmann     vs->connections_limit = qemu_opt_get_number(opts, "connections", 32);
37023e230dd2SCorentin Chary 
37034db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
37044db14629SGerd Hoffmann     vs->lossy = qemu_opt_get_bool(opts, "lossy", false);
37054db14629SGerd Hoffmann #endif
37064db14629SGerd Hoffmann     vs->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3707e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
3708e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
3709e22492d3SPeter Lieven      * calculations otherwise */
3710e22492d3SPeter Lieven     if (!vs->lossy) {
3711e22492d3SPeter Lieven         vs->non_adaptive = true;
3712e22492d3SPeter Lieven     }
3713e22492d3SPeter Lieven 
37143e305e4aSDaniel P. Berrange     if (acl) {
3715c8496408SGerd Hoffmann         if (strcmp(vs->id, "default") == 0) {
37163e305e4aSDaniel P. Berrange             vs->tlsaclname = g_strdup("vnc.x509dname");
3717c8496408SGerd Hoffmann         } else {
37183e305e4aSDaniel P. Berrange             vs->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vs->id);
3719c8496408SGerd Hoffmann         }
37203e305e4aSDaniel P. Berrange         qemu_acl_init(vs->tlsaclname);
37213e230dd2SCorentin Chary      }
37223e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
37233e230dd2SCorentin Chary     if (acl && sasl) {
3724c8496408SGerd Hoffmann         char *aclname;
3725c8496408SGerd Hoffmann 
3726c8496408SGerd Hoffmann         if (strcmp(vs->id, "default") == 0) {
3727c8496408SGerd Hoffmann             aclname = g_strdup("vnc.username");
3728c8496408SGerd Hoffmann         } else {
3729c8496408SGerd Hoffmann             aclname = g_strdup_printf("vnc.%s.username", vs->id);
3730c8496408SGerd Hoffmann         }
3731c8496408SGerd Hoffmann         vs->sasl.acl = qemu_acl_init(aclname);
3732c8496408SGerd Hoffmann         g_free(aclname);
37333e230dd2SCorentin Chary     }
37343e230dd2SCorentin Chary #endif
37353e230dd2SCorentin Chary 
3736e0d03b8cSDaniel P. Berrange     if (vnc_display_setup_auth(vs, password, sasl, vs->ws_enabled, errp) < 0) {
37373e305e4aSDaniel P. Berrange         goto fail;
37383e305e4aSDaniel P. Berrange     }
37393e230dd2SCorentin Chary 
37403e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
37413e230dd2SCorentin Chary     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
37422d55f0e8SPaolo Bonzini         error_setg(errp, "Failed to initialize SASL auth: %s",
37433e230dd2SCorentin Chary                    sasl_errstring(saslErr, NULL, NULL));
37441ce52c78SPaolo Bonzini         goto fail;
37453e230dd2SCorentin Chary     }
37463e230dd2SCorentin Chary #endif
37473e230dd2SCorentin Chary     vs->lock_key_sync = lock_key_sync;
37483e230dd2SCorentin Chary 
37491d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
37501d0d59feSGerd Hoffmann     if (device_id) {
37511d0d59feSGerd Hoffmann         DeviceState *dev;
37521d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
37531d0d59feSGerd Hoffmann 
37541d0d59feSGerd Hoffmann         dev = qdev_find_recursive(sysbus_get_default(), device_id);
37551d0d59feSGerd Hoffmann         if (dev == NULL) {
3756f3cf80e8SMarkus Armbruster             error_setg(errp, "Device '%s' not found", device_id);
37571d0d59feSGerd Hoffmann             goto fail;
37581d0d59feSGerd Hoffmann         }
37591d0d59feSGerd Hoffmann 
37601d0d59feSGerd Hoffmann         con = qemu_console_lookup_by_device(dev, head);
37611d0d59feSGerd Hoffmann         if (con == NULL) {
37621d0d59feSGerd Hoffmann             error_setg(errp, "Device %s is not bound to a QemuConsole",
37631d0d59feSGerd Hoffmann                        device_id);
37641d0d59feSGerd Hoffmann             goto fail;
37651d0d59feSGerd Hoffmann         }
37661d0d59feSGerd Hoffmann     } else {
37671d0d59feSGerd Hoffmann         con = NULL;
37681d0d59feSGerd Hoffmann     }
37691d0d59feSGerd Hoffmann 
37701d0d59feSGerd Hoffmann     if (con != vs->dcl.con) {
37711d0d59feSGerd Hoffmann         unregister_displaychangelistener(&vs->dcl);
37721d0d59feSGerd Hoffmann         vs->dcl.con = con;
37731d0d59feSGerd Hoffmann         register_displaychangelistener(&vs->dcl);
37741d0d59feSGerd Hoffmann     }
37751d0d59feSGerd Hoffmann 
37763e230dd2SCorentin Chary     if (reverse) {
37773e230dd2SCorentin Chary         /* connect to viewer */
3778007fcd3eSPaolo Bonzini         int csock;
37793e230dd2SCorentin Chary         vs->lsock = -1;
37807536ee4bSTim Hardeck         vs->lwebsock = -1;
3781e0d03b8cSDaniel P. Berrange         if (vs->ws_enabled) {
3782e0d03b8cSDaniel P. Berrange             error_setg(errp, "Cannot use websockets in reverse mode");
3783e0d03b8cSDaniel P. Berrange             goto fail;
37843e230dd2SCorentin Chary         }
3785e0d03b8cSDaniel P. Berrange         csock = socket_connect(saddr, errp, NULL, NULL);
3786007fcd3eSPaolo Bonzini         if (csock < 0) {
3787007fcd3eSPaolo Bonzini             goto fail;
3788007fcd3eSPaolo Bonzini         }
37892d32addaSEric Blake         vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
37902c8cf549SMichael Tokarev         vnc_connect(vs, csock, false, false);
37913e230dd2SCorentin Chary     } else {
37923e230dd2SCorentin Chary         /* listen for connects */
3793e0d03b8cSDaniel P. Berrange         vs->lsock = socket_listen(saddr, errp);
37943d00ac1aSCole Robinson         if (vs->lsock < 0) {
37953d00ac1aSCole Robinson             goto fail;
37963d00ac1aSCole Robinson         }
37972d32addaSEric Blake         vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
3798bf7aa45eSGerd Hoffmann         if (vs->ws_enabled) {
3799e0d03b8cSDaniel P. Berrange             vs->lwebsock = socket_listen(wsaddr, errp);
38007536ee4bSTim Hardeck             if (vs->lwebsock < 0) {
3801b3c33f91SGonglei                 if (vs->lsock != -1) {
38027536ee4bSTim Hardeck                     close(vs->lsock);
38037536ee4bSTim Hardeck                     vs->lsock = -1;
38047536ee4bSTim Hardeck                 }
38057536ee4bSTim Hardeck                 goto fail;
38067536ee4bSTim Hardeck             }
38077536ee4bSTim Hardeck         }
3808bf7aa45eSGerd Hoffmann         vs->enabled = true;
380982e1cc4bSFam Zheng         qemu_set_fd_handler(vs->lsock, vnc_listen_regular_read, NULL, vs);
3810bf7aa45eSGerd Hoffmann         if (vs->ws_enabled) {
381182e1cc4bSFam Zheng             qemu_set_fd_handler(vs->lwebsock, vnc_listen_websocket_read,
381282e1cc4bSFam Zheng                                 NULL, vs);
38137536ee4bSTim Hardeck         }
38143e230dd2SCorentin Chary     }
3815e0d03b8cSDaniel P. Berrange 
3816e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(saddr);
3817e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(wsaddr);
38182d55f0e8SPaolo Bonzini     return;
38191ce52c78SPaolo Bonzini 
38201ce52c78SPaolo Bonzini fail:
3821e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(saddr);
3822e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(wsaddr);
3823bf7aa45eSGerd Hoffmann     vs->enabled = false;
3824bf7aa45eSGerd Hoffmann     vs->ws_enabled = false;
38253e230dd2SCorentin Chary }
382613661089SDaniel P. Berrange 
382714f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
382813661089SDaniel P. Berrange {
382914f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
383013661089SDaniel P. Berrange 
3831d616ccc5SGerd Hoffmann     if (!vs) {
3832d616ccc5SGerd Hoffmann         return;
3833d616ccc5SGerd Hoffmann     }
38342c8cf549SMichael Tokarev     vnc_connect(vs, csock, skipauth, false);
383513661089SDaniel P. Berrange }
38364db14629SGerd Hoffmann 
38379634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
38382779672fSGonglei {
38392779672fSGonglei     int i = 2;
38402779672fSGonglei     char *id;
38412779672fSGonglei 
38422779672fSGonglei     id = g_strdup("default");
38432779672fSGonglei     while (qemu_opts_find(olist, id)) {
38442779672fSGonglei         g_free(id);
38452779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
38462779672fSGonglei     }
38472779672fSGonglei     qemu_opts_set_id(opts, id);
38482779672fSGonglei }
38492779672fSGonglei 
385070b94331SMarkus Armbruster QemuOpts *vnc_parse(const char *str, Error **errp)
38514db14629SGerd Hoffmann {
38524db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
385370b94331SMarkus Armbruster     QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
385481607cbfSGonglei     const char *id;
38554db14629SGerd Hoffmann 
385681607cbfSGonglei     if (!opts) {
385781607cbfSGonglei         return NULL;
385881607cbfSGonglei     }
385981607cbfSGonglei 
386081607cbfSGonglei     id = qemu_opts_id(opts);
38614db14629SGerd Hoffmann     if (!id) {
38624db14629SGerd Hoffmann         /* auto-assign id if not present */
38632779672fSGonglei         vnc_auto_assign_id(olist, opts);
38649634f4e3SGerd Hoffmann     }
38659634f4e3SGerd Hoffmann     return opts;
38664db14629SGerd Hoffmann }
38674db14629SGerd Hoffmann 
386828d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
38699634f4e3SGerd Hoffmann {
38709634f4e3SGerd Hoffmann     Error *local_err = NULL;
38719634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
38729634f4e3SGerd Hoffmann 
38739634f4e3SGerd Hoffmann     assert(id);
38744db14629SGerd Hoffmann     vnc_display_init(id);
38754db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
38764db14629SGerd Hoffmann     if (local_err != NULL) {
3877bc119048SCole Robinson         error_report("Failed to start VNC server: %s",
38784db14629SGerd Hoffmann                      error_get_pretty(local_err));
38794db14629SGerd Hoffmann         error_free(local_err);
38804db14629SGerd Hoffmann         exit(1);
38814db14629SGerd Hoffmann     }
38824db14629SGerd Hoffmann     return 0;
38834db14629SGerd Hoffmann }
38844db14629SGerd Hoffmann 
38854db14629SGerd Hoffmann static void vnc_register_config(void)
38864db14629SGerd Hoffmann {
38874db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
38884db14629SGerd Hoffmann }
38894db14629SGerd Hoffmann machine_init(vnc_register_config);
3890