xref: /openbmc/qemu/ui/vnc.c (revision 30b80fd5269257f55203b7072c505b4ebaab5115)
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 
27e16f4c87SPeter Maydell #include "qemu/osdep.h"
283e230dd2SCorentin Chary #include "vnc.h"
29bd023f95SCorentin Chary #include "vnc-jobs.h"
3040066175SGerd Hoffmann #include "trace.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"
408d447d10SGerd Hoffmann #include "ui/input.h"
41fb6ba0d5SWenchao Xia #include "qapi-event.h"
428e9b0d24SDaniel P. Berrange #include "crypto/hash.h"
433e305e4aSDaniel P. Berrange #include "crypto/tlscredsanon.h"
443e305e4aSDaniel P. Berrange #include "crypto/tlscredsx509.h"
453e305e4aSDaniel P. Berrange #include "qom/object_interfaces.h"
46f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
4757a6d6d5SDaniel P. Berrange #include "io/dns-resolver.h"
483e230dd2SCorentin Chary 
490f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
503e230dd2SCorentin Chary #define VNC_REFRESH_INTERVAL_INC  50
510f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
52999342a0SCorentin Chary static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
53999342a0SCorentin Chary static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
543e230dd2SCorentin Chary 
553e230dd2SCorentin Chary #include "vnc_keysym.h"
56800567a6SDaniel P. Berrange #include "crypto/cipher.h"
573e230dd2SCorentin Chary 
58d616ccc5SGerd Hoffmann static QTAILQ_HEAD(, VncDisplay) vnc_displays =
59d616ccc5SGerd Hoffmann     QTAILQ_HEAD_INITIALIZER(vnc_displays);
603e230dd2SCorentin Chary 
613e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs);
627bc9318bSGerd Hoffmann static void vnc_release_modifiers(VncState *vs);
63e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs);
643e230dd2SCorentin Chary 
658cf36489SGerd Hoffmann static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
668cf36489SGerd Hoffmann {
678cf36489SGerd Hoffmann #ifdef _VNC_DEBUG
688cf36489SGerd Hoffmann     static const char *mn[] = {
698cf36489SGerd Hoffmann         [0]                           = "undefined",
708cf36489SGerd Hoffmann         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
718cf36489SGerd Hoffmann         [VNC_SHARE_MODE_SHARED]       = "shared",
728cf36489SGerd Hoffmann         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
738cf36489SGerd Hoffmann         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
748cf36489SGerd Hoffmann     };
7504d2529dSDaniel P. Berrange     fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
7604d2529dSDaniel P. Berrange             vs->ioc, mn[vs->share_mode], mn[mode]);
778cf36489SGerd Hoffmann #endif
788cf36489SGerd Hoffmann 
79e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
80e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
81e5f34cddSGerd Hoffmann         vs->vd->num_connecting--;
82e5f34cddSGerd Hoffmann         break;
83e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
84e5f34cddSGerd Hoffmann         vs->vd->num_shared--;
85e5f34cddSGerd Hoffmann         break;
86e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
878cf36489SGerd Hoffmann         vs->vd->num_exclusive--;
88e5f34cddSGerd Hoffmann         break;
89e5f34cddSGerd Hoffmann     default:
90e5f34cddSGerd Hoffmann         break;
918cf36489SGerd Hoffmann     }
92e5f34cddSGerd Hoffmann 
938cf36489SGerd Hoffmann     vs->share_mode = mode;
94e5f34cddSGerd Hoffmann 
95e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
96e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
97e5f34cddSGerd Hoffmann         vs->vd->num_connecting++;
98e5f34cddSGerd Hoffmann         break;
99e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
100e5f34cddSGerd Hoffmann         vs->vd->num_shared++;
101e5f34cddSGerd Hoffmann         break;
102e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
1038cf36489SGerd Hoffmann         vs->vd->num_exclusive++;
104e5f34cddSGerd Hoffmann         break;
105e5f34cddSGerd Hoffmann     default:
106e5f34cddSGerd Hoffmann         break;
1078cf36489SGerd Hoffmann     }
1088cf36489SGerd Hoffmann }
1098cf36489SGerd Hoffmann 
1103e230dd2SCorentin Chary 
111bd269ebcSMarkus Armbruster static void vnc_init_basic_info(SocketAddress *addr,
11298481bfcSEric Blake                                 VncBasicInfo *info,
11398481bfcSEric Blake                                 Error **errp)
1143e230dd2SCorentin Chary {
11504d2529dSDaniel P. Berrange     switch (addr->type) {
116bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_INET:
117bd269ebcSMarkus Armbruster         info->host = g_strdup(addr->u.inet.host);
118bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.inet.port);
119bd269ebcSMarkus Armbruster         if (addr->u.inet.ipv6) {
12004d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
12104d2529dSDaniel P. Berrange         } else {
12204d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
12304d2529dSDaniel P. Berrange         }
12404d2529dSDaniel P. Berrange         break;
1253e230dd2SCorentin Chary 
126bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_UNIX:
12704d2529dSDaniel P. Berrange         info->host = g_strdup("");
128bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.q_unix.path);
12904d2529dSDaniel P. Berrange         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
13004d2529dSDaniel P. Berrange         break;
13104d2529dSDaniel P. Berrange 
132bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_VSOCK:
133bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_FD:
134a6c76285SMarkus Armbruster         error_setg(errp, "Unsupported socket address type %s",
135977c736fSMarkus Armbruster                    SocketAddressType_str(addr->type));
13604d2529dSDaniel P. Berrange         break;
137a6c76285SMarkus Armbruster     default:
138a6c76285SMarkus Armbruster         abort();
13904d2529dSDaniel P. Berrange     }
14004d2529dSDaniel P. Berrange 
14198481bfcSEric Blake     return;
1423e230dd2SCorentin Chary }
1433e230dd2SCorentin Chary 
14404d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
14504d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
14698481bfcSEric Blake                                                  Error **errp)
1473e230dd2SCorentin Chary {
148bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1493e230dd2SCorentin Chary 
150624cdd46SDaniel P. Berrange     if (!ioc) {
151624cdd46SDaniel P. Berrange         error_setg(errp, "No listener socket available");
152624cdd46SDaniel P. Berrange         return;
153624cdd46SDaniel P. Berrange     }
154624cdd46SDaniel P. Berrange 
15504d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, errp);
15604d2529dSDaniel P. Berrange     if (!addr) {
15798481bfcSEric Blake         return;
1583e230dd2SCorentin Chary     }
1593e230dd2SCorentin Chary 
16004d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
161bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1623e230dd2SCorentin Chary }
1633e230dd2SCorentin Chary 
16404d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
16504d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
16698481bfcSEric Blake                                                  Error **errp)
1673e230dd2SCorentin Chary {
168bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1693e230dd2SCorentin Chary 
17004d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_remote_address(ioc, errp);
17104d2529dSDaniel P. Berrange     if (!addr) {
17298481bfcSEric Blake         return;
1733e230dd2SCorentin Chary     }
1743e230dd2SCorentin Chary 
17504d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
176bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1773e230dd2SCorentin Chary }
1783e230dd2SCorentin Chary 
1793e230dd2SCorentin Chary static const char *vnc_auth_name(VncDisplay *vd) {
1803e230dd2SCorentin Chary     switch (vd->auth) {
1813e230dd2SCorentin Chary     case VNC_AUTH_INVALID:
1823e230dd2SCorentin Chary         return "invalid";
1833e230dd2SCorentin Chary     case VNC_AUTH_NONE:
1843e230dd2SCorentin Chary         return "none";
1853e230dd2SCorentin Chary     case VNC_AUTH_VNC:
1863e230dd2SCorentin Chary         return "vnc";
1873e230dd2SCorentin Chary     case VNC_AUTH_RA2:
1883e230dd2SCorentin Chary         return "ra2";
1893e230dd2SCorentin Chary     case VNC_AUTH_RA2NE:
1903e230dd2SCorentin Chary         return "ra2ne";
1913e230dd2SCorentin Chary     case VNC_AUTH_TIGHT:
1923e230dd2SCorentin Chary         return "tight";
1933e230dd2SCorentin Chary     case VNC_AUTH_ULTRA:
1943e230dd2SCorentin Chary         return "ultra";
1953e230dd2SCorentin Chary     case VNC_AUTH_TLS:
1963e230dd2SCorentin Chary         return "tls";
1973e230dd2SCorentin Chary     case VNC_AUTH_VENCRYPT:
1983e230dd2SCorentin Chary         switch (vd->subauth) {
1993e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_PLAIN:
2003e230dd2SCorentin Chary             return "vencrypt+plain";
2013e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSNONE:
2023e230dd2SCorentin Chary             return "vencrypt+tls+none";
2033e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSVNC:
2043e230dd2SCorentin Chary             return "vencrypt+tls+vnc";
2053e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSPLAIN:
2063e230dd2SCorentin Chary             return "vencrypt+tls+plain";
2073e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509NONE:
2083e230dd2SCorentin Chary             return "vencrypt+x509+none";
2093e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509VNC:
2103e230dd2SCorentin Chary             return "vencrypt+x509+vnc";
2113e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509PLAIN:
2123e230dd2SCorentin Chary             return "vencrypt+x509+plain";
2133e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSSASL:
2143e230dd2SCorentin Chary             return "vencrypt+tls+sasl";
2153e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509SASL:
2163e230dd2SCorentin Chary             return "vencrypt+x509+sasl";
2173e230dd2SCorentin Chary         default:
2183e230dd2SCorentin Chary             return "vencrypt";
2193e230dd2SCorentin Chary         }
2203e230dd2SCorentin Chary     case VNC_AUTH_SASL:
2213e230dd2SCorentin Chary         return "sasl";
2223e230dd2SCorentin Chary     }
2233e230dd2SCorentin Chary     return "unknown";
2243e230dd2SCorentin Chary }
2253e230dd2SCorentin Chary 
226d616ccc5SGerd Hoffmann static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
2273e230dd2SCorentin Chary {
228fb6ba0d5SWenchao Xia     VncServerInfo *info;
22998481bfcSEric Blake     Error *err = NULL;
2303e230dd2SCorentin Chary 
2314ee74fa7SDaniel P. Berrange     if (!vd->nlsock) {
2324ee74fa7SDaniel P. Berrange         return NULL;
2334ee74fa7SDaniel P. Berrange     }
2344ee74fa7SDaniel P. Berrange 
2353e7f136dSDaniel P. Berrange     info = g_malloc0(sizeof(*info));
2364ee74fa7SDaniel P. Berrange     vnc_init_basic_info_from_server_addr(vd->lsock[0],
237ddf21908SEric Blake                                          qapi_VncServerInfo_base(info), &err);
238fb6ba0d5SWenchao Xia     info->has_auth = true;
239d616ccc5SGerd Hoffmann     info->auth = g_strdup(vnc_auth_name(vd));
24098481bfcSEric Blake     if (err) {
24198481bfcSEric Blake         qapi_free_VncServerInfo(info);
24298481bfcSEric Blake         info = NULL;
24398481bfcSEric Blake         error_free(err);
24498481bfcSEric Blake     }
245fb6ba0d5SWenchao Xia     return info;
2463e230dd2SCorentin Chary }
2473e230dd2SCorentin Chary 
2483e230dd2SCorentin Chary static void vnc_client_cache_auth(VncState *client)
2493e230dd2SCorentin Chary {
2503e230dd2SCorentin Chary     if (!client->info) {
2513e230dd2SCorentin Chary         return;
2523e230dd2SCorentin Chary     }
2533e230dd2SCorentin Chary 
2543e305e4aSDaniel P. Berrange     if (client->tls) {
2553e305e4aSDaniel P. Berrange         client->info->x509_dname =
2563e305e4aSDaniel P. Berrange             qcrypto_tls_session_get_peer_name(client->tls);
2573e305e4aSDaniel P. Berrange         client->info->has_x509_dname =
2583e305e4aSDaniel P. Berrange             client->info->x509_dname != NULL;
2593e230dd2SCorentin Chary     }
2603e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
2613e230dd2SCorentin Chary     if (client->sasl.conn &&
2623e230dd2SCorentin Chary         client->sasl.username) {
263fb6ba0d5SWenchao Xia         client->info->has_sasl_username = true;
264fb6ba0d5SWenchao Xia         client->info->sasl_username = g_strdup(client->sasl.username);
2653e230dd2SCorentin Chary     }
2663e230dd2SCorentin Chary #endif
2673e230dd2SCorentin Chary }
2683e230dd2SCorentin Chary 
2693e230dd2SCorentin Chary static void vnc_client_cache_addr(VncState *client)
2703e230dd2SCorentin Chary {
27198481bfcSEric Blake     Error *err = NULL;
2723e230dd2SCorentin Chary 
273fb6ba0d5SWenchao Xia     client->info = g_malloc0(sizeof(*client->info));
27404d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
275ddf21908SEric Blake                                          qapi_VncClientInfo_base(client->info),
27698481bfcSEric Blake                                          &err);
27798481bfcSEric Blake     if (err) {
27898481bfcSEric Blake         qapi_free_VncClientInfo(client->info);
27998481bfcSEric Blake         client->info = NULL;
28098481bfcSEric Blake         error_free(err);
281fb6ba0d5SWenchao Xia     }
2823e230dd2SCorentin Chary }
2833e230dd2SCorentin Chary 
284fb6ba0d5SWenchao Xia static void vnc_qmp_event(VncState *vs, QAPIEvent event)
2853e230dd2SCorentin Chary {
286fb6ba0d5SWenchao Xia     VncServerInfo *si;
2873e230dd2SCorentin Chary 
2883e230dd2SCorentin Chary     if (!vs->info) {
2893e230dd2SCorentin Chary         return;
2903e230dd2SCorentin Chary     }
2913e230dd2SCorentin Chary 
292d616ccc5SGerd Hoffmann     si = vnc_server_info_get(vs->vd);
293fb6ba0d5SWenchao Xia     if (!si) {
2943e230dd2SCorentin Chary         return;
2953e230dd2SCorentin Chary     }
2963e230dd2SCorentin Chary 
297fb6ba0d5SWenchao Xia     switch (event) {
298fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_CONNECTED:
299ddf21908SEric Blake         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info),
300ddf21908SEric Blake                                       &error_abort);
301fb6ba0d5SWenchao Xia         break;
302fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_INITIALIZED:
303fb6ba0d5SWenchao Xia         qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
304fb6ba0d5SWenchao Xia         break;
305fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_DISCONNECTED:
306fb6ba0d5SWenchao Xia         qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
307fb6ba0d5SWenchao Xia         break;
308fb6ba0d5SWenchao Xia     default:
309fb6ba0d5SWenchao Xia         break;
310fb6ba0d5SWenchao Xia     }
3113e230dd2SCorentin Chary 
312fb6ba0d5SWenchao Xia     qapi_free_VncServerInfo(si);
3133e230dd2SCorentin Chary }
3143e230dd2SCorentin Chary 
3152b54aa87SLuiz Capitulino static VncClientInfo *qmp_query_vnc_client(const VncState *client)
3163e230dd2SCorentin Chary {
3172b54aa87SLuiz Capitulino     VncClientInfo *info;
31804d2529dSDaniel P. Berrange     Error *err = NULL;
3192b54aa87SLuiz Capitulino 
3202b54aa87SLuiz Capitulino     info = g_malloc0(sizeof(*info));
32104d2529dSDaniel P. Berrange 
32204d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
32304d2529dSDaniel P. Berrange                                          qapi_VncClientInfo_base(info),
32404d2529dSDaniel P. Berrange                                          &err);
32504d2529dSDaniel P. Berrange     if (err) {
32604d2529dSDaniel P. Berrange         error_free(err);
32704d2529dSDaniel P. Berrange         qapi_free_VncClientInfo(info);
32804d2529dSDaniel P. Berrange         return NULL;
32904d2529dSDaniel P. Berrange     }
33004d2529dSDaniel P. Berrange 
331ddf21908SEric Blake     info->websocket = client->websocket;
3323e230dd2SCorentin Chary 
3333e305e4aSDaniel P. Berrange     if (client->tls) {
3343e305e4aSDaniel P. Berrange         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
3353e305e4aSDaniel P. Berrange         info->has_x509_dname = info->x509_dname != NULL;
3362b54aa87SLuiz Capitulino     }
3373e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
3382b54aa87SLuiz Capitulino     if (client->sasl.conn && client->sasl.username) {
3392b54aa87SLuiz Capitulino         info->has_sasl_username = true;
3402b54aa87SLuiz Capitulino         info->sasl_username = g_strdup(client->sasl.username);
3412b54aa87SLuiz Capitulino     }
3423e230dd2SCorentin Chary #endif
3432b54aa87SLuiz Capitulino 
3442b54aa87SLuiz Capitulino     return info;
3453e230dd2SCorentin Chary }
3463e230dd2SCorentin Chary 
347d616ccc5SGerd Hoffmann static VncDisplay *vnc_display_find(const char *id)
348d616ccc5SGerd Hoffmann {
349d616ccc5SGerd Hoffmann     VncDisplay *vd;
350d616ccc5SGerd Hoffmann 
351d616ccc5SGerd Hoffmann     if (id == NULL) {
352d616ccc5SGerd Hoffmann         return QTAILQ_FIRST(&vnc_displays);
353d616ccc5SGerd Hoffmann     }
354d616ccc5SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
355d616ccc5SGerd Hoffmann         if (strcmp(id, vd->id) == 0) {
356d616ccc5SGerd Hoffmann             return vd;
357d616ccc5SGerd Hoffmann         }
358d616ccc5SGerd Hoffmann     }
359d616ccc5SGerd Hoffmann     return NULL;
360d616ccc5SGerd Hoffmann }
361d616ccc5SGerd Hoffmann 
3622d29a436SGerd Hoffmann static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
3632d29a436SGerd Hoffmann {
3642d29a436SGerd Hoffmann     VncClientInfoList *cinfo, *prev = NULL;
3652d29a436SGerd Hoffmann     VncState *client;
3662d29a436SGerd Hoffmann 
3672d29a436SGerd Hoffmann     QTAILQ_FOREACH(client, &vd->clients, next) {
3682d29a436SGerd Hoffmann         cinfo = g_new0(VncClientInfoList, 1);
3692d29a436SGerd Hoffmann         cinfo->value = qmp_query_vnc_client(client);
3702d29a436SGerd Hoffmann         cinfo->next = prev;
3712d29a436SGerd Hoffmann         prev = cinfo;
3722d29a436SGerd Hoffmann     }
3732d29a436SGerd Hoffmann     return prev;
3742d29a436SGerd Hoffmann }
3752d29a436SGerd Hoffmann 
3762b54aa87SLuiz Capitulino VncInfo *qmp_query_vnc(Error **errp)
3773e230dd2SCorentin Chary {
3782b54aa87SLuiz Capitulino     VncInfo *info = g_malloc0(sizeof(*info));
379d616ccc5SGerd Hoffmann     VncDisplay *vd = vnc_display_find(NULL);
380bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3813e230dd2SCorentin Chary 
3824ee74fa7SDaniel P. Berrange     if (vd == NULL || !vd->nlsock) {
3832b54aa87SLuiz Capitulino         info->enabled = false;
3843e230dd2SCorentin Chary     } else {
3852b54aa87SLuiz Capitulino         info->enabled = true;
3862b54aa87SLuiz Capitulino 
3872b54aa87SLuiz Capitulino         /* for compatibility with the original command */
3882b54aa87SLuiz Capitulino         info->has_clients = true;
3892d29a436SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
3903e230dd2SCorentin Chary 
39104d2529dSDaniel P. Berrange         if (vd->lsock == NULL) {
392417b0b88SPaolo Bonzini             return info;
393417b0b88SPaolo Bonzini         }
394417b0b88SPaolo Bonzini 
3954ee74fa7SDaniel P. Berrange         addr = qio_channel_socket_get_local_address(vd->lsock[0], errp);
39604d2529dSDaniel P. Berrange         if (!addr) {
3972b54aa87SLuiz Capitulino             goto out_error;
3982b54aa87SLuiz Capitulino         }
3993e230dd2SCorentin Chary 
40004d2529dSDaniel P. Berrange         switch (addr->type) {
401bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_INET:
402bd269ebcSMarkus Armbruster             info->host = g_strdup(addr->u.inet.host);
403bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.inet.port);
404bd269ebcSMarkus Armbruster             if (addr->u.inet.ipv6) {
40504d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
40604d2529dSDaniel P. Berrange             } else {
40704d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
40804d2529dSDaniel P. Berrange             }
40904d2529dSDaniel P. Berrange             break;
41004d2529dSDaniel P. Berrange 
411bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_UNIX:
41204d2529dSDaniel P. Berrange             info->host = g_strdup("");
413bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.q_unix.path);
41404d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
41504d2529dSDaniel P. Berrange             break;
41604d2529dSDaniel P. Berrange 
417bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_VSOCK:
418bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_FD:
419a6c76285SMarkus Armbruster             error_setg(errp, "Unsupported socket address type %s",
420977c736fSMarkus Armbruster                        SocketAddressType_str(addr->type));
4212b54aa87SLuiz Capitulino             goto out_error;
422a6c76285SMarkus Armbruster         default:
423a6c76285SMarkus Armbruster             abort();
4243e230dd2SCorentin Chary         }
4252b54aa87SLuiz Capitulino 
4262b54aa87SLuiz Capitulino         info->has_host = true;
4272b54aa87SLuiz Capitulino         info->has_service = true;
4282b54aa87SLuiz Capitulino         info->has_family = true;
4292b54aa87SLuiz Capitulino 
4302b54aa87SLuiz Capitulino         info->has_auth = true;
431d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4323e230dd2SCorentin Chary     }
4332b54aa87SLuiz Capitulino 
434bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4352b54aa87SLuiz Capitulino     return info;
4362b54aa87SLuiz Capitulino 
4372b54aa87SLuiz Capitulino out_error:
438bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4392b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4402b54aa87SLuiz Capitulino     return NULL;
4413e230dd2SCorentin Chary }
4423e230dd2SCorentin Chary 
4432a7e6857SDaniel P. Berrange 
4442a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4452a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4462a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4472a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt);
4482a7e6857SDaniel P. Berrange 
4492a7e6857SDaniel P. Berrange static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
4504478aa76SGerd Hoffmann                                                   bool websocket,
4512a7e6857SDaniel P. Berrange                                                   int auth,
4522a7e6857SDaniel P. Berrange                                                   int subauth,
4532a7e6857SDaniel P. Berrange                                                   VncServerInfo2List *prev)
454df887684SGerd Hoffmann {
4552a7e6857SDaniel P. Berrange     VncServerInfo2List *list;
4562a7e6857SDaniel P. Berrange     VncServerInfo2 *info;
45704d2529dSDaniel P. Berrange     Error *err = NULL;
458bd269ebcSMarkus Armbruster     SocketAddress *addr;
459df887684SGerd Hoffmann 
46004d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, &err);
46104d2529dSDaniel P. Berrange     if (!addr) {
46204d2529dSDaniel P. Berrange         error_free(err);
463df887684SGerd Hoffmann         return prev;
464df887684SGerd Hoffmann     }
465df887684SGerd Hoffmann 
4662a7e6857SDaniel P. Berrange     info = g_new0(VncServerInfo2, 1);
4672a7e6857SDaniel P. Berrange     vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
468bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
46904d2529dSDaniel P. Berrange     if (err) {
4702a7e6857SDaniel P. Berrange         qapi_free_VncServerInfo2(info);
47104d2529dSDaniel P. Berrange         error_free(err);
47204d2529dSDaniel P. Berrange         return prev;
47304d2529dSDaniel P. Berrange     }
4744478aa76SGerd Hoffmann     info->websocket = websocket;
475df887684SGerd Hoffmann 
4762a7e6857SDaniel P. Berrange     qmp_query_auth(auth, subauth, &info->auth,
4772a7e6857SDaniel P. Berrange                    &info->vencrypt, &info->has_vencrypt);
4782a7e6857SDaniel P. Berrange 
4792a7e6857SDaniel P. Berrange     list = g_new0(VncServerInfo2List, 1);
480df887684SGerd Hoffmann     list->value = info;
481df887684SGerd Hoffmann     list->next = prev;
482df887684SGerd Hoffmann     return list;
483df887684SGerd Hoffmann }
484df887684SGerd Hoffmann 
4852a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4862a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4872a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4882a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt)
489df887684SGerd Hoffmann {
4902a7e6857SDaniel P. Berrange     switch (auth) {
491df887684SGerd Hoffmann     case VNC_AUTH_VNC:
4922a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VNC;
493df887684SGerd Hoffmann         break;
494df887684SGerd Hoffmann     case VNC_AUTH_RA2:
4952a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2;
496df887684SGerd Hoffmann         break;
497df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
4982a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
499df887684SGerd Hoffmann         break;
500df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
5012a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
502df887684SGerd Hoffmann         break;
503df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
5042a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
505df887684SGerd Hoffmann         break;
506df887684SGerd Hoffmann     case VNC_AUTH_TLS:
5072a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TLS;
508df887684SGerd Hoffmann         break;
509df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
5102a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
5112a7e6857SDaniel P. Berrange         *qmp_has_vencrypt = true;
5122a7e6857SDaniel P. Berrange         switch (subauth) {
513df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
5142a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
515df887684SGerd Hoffmann             break;
516df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
5172a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
518df887684SGerd Hoffmann             break;
519df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
5202a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
521df887684SGerd Hoffmann             break;
522df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
5232a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
524df887684SGerd Hoffmann             break;
525df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
5262a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
527df887684SGerd Hoffmann             break;
528df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
5292a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
530df887684SGerd Hoffmann             break;
531df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
5322a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
533df887684SGerd Hoffmann             break;
534df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
5352a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
536df887684SGerd Hoffmann             break;
537df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
5382a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
539df887684SGerd Hoffmann             break;
540df887684SGerd Hoffmann         default:
5412a7e6857SDaniel P. Berrange             *qmp_has_vencrypt = false;
542df887684SGerd Hoffmann             break;
543df887684SGerd Hoffmann         }
544df887684SGerd Hoffmann         break;
545df887684SGerd Hoffmann     case VNC_AUTH_SASL:
5462a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_SASL;
547df887684SGerd Hoffmann         break;
548df887684SGerd Hoffmann     case VNC_AUTH_NONE:
549df887684SGerd Hoffmann     default:
5502a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_NONE;
551df887684SGerd Hoffmann         break;
552df887684SGerd Hoffmann     }
553df887684SGerd Hoffmann }
554df887684SGerd Hoffmann 
555df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
556df887684SGerd Hoffmann {
557df887684SGerd Hoffmann     VncInfo2List *item, *prev = NULL;
558df887684SGerd Hoffmann     VncInfo2 *info;
559df887684SGerd Hoffmann     VncDisplay *vd;
560df887684SGerd Hoffmann     DeviceState *dev;
5614ee74fa7SDaniel P. Berrange     size_t i;
562df887684SGerd Hoffmann 
563df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
564df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
565df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
566df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
5672a7e6857SDaniel P. Berrange         qmp_query_auth(vd->auth, vd->subauth, &info->auth,
5682a7e6857SDaniel P. Berrange                        &info->vencrypt, &info->has_vencrypt);
569df887684SGerd Hoffmann         if (vd->dcl.con) {
570df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
571df887684SGerd Hoffmann                                                   "device", NULL));
572df887684SGerd Hoffmann             info->has_display = true;
573df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
574df887684SGerd Hoffmann         }
5754ee74fa7SDaniel P. Berrange         for (i = 0; i < vd->nlsock; i++) {
57604d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
5774ee74fa7SDaniel P. Berrange                 vd->lsock[i], false, vd->auth, vd->subauth, info->server);
578df887684SGerd Hoffmann         }
5794ee74fa7SDaniel P. Berrange         for (i = 0; i < vd->nlwebsock; i++) {
58004d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
5814ee74fa7SDaniel P. Berrange                 vd->lwebsock[i], true, vd->ws_auth,
5824ee74fa7SDaniel P. Berrange                 vd->ws_subauth, info->server);
583df887684SGerd Hoffmann         }
584df887684SGerd Hoffmann 
585df887684SGerd Hoffmann         item = g_new0(VncInfo2List, 1);
586df887684SGerd Hoffmann         item->value = info;
587df887684SGerd Hoffmann         item->next = prev;
588df887684SGerd Hoffmann         prev = item;
589df887684SGerd Hoffmann     }
590df887684SGerd Hoffmann     return prev;
591df887684SGerd Hoffmann }
592df887684SGerd Hoffmann 
5933e230dd2SCorentin Chary /* TODO
5943e230dd2SCorentin Chary    1) Get the queue working for IO.
5953e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
5963e230dd2SCorentin Chary       and not totally invalidated
5973e230dd2SCorentin Chary    3) resolutions > 1024
5983e230dd2SCorentin Chary */
5993e230dd2SCorentin Chary 
6006af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty);
6013e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
6023e230dd2SCorentin Chary 
6033e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
6043e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
6053e230dd2SCorentin Chary                                        int x_position, int y_position,
6063e230dd2SCorentin Chary                                        int w, int h);
6070f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
6083e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
6093e230dd2SCorentin Chary 
610d05959c2SGerd Hoffmann static int vnc_width(VncDisplay *vd)
611d05959c2SGerd Hoffmann {
612d05959c2SGerd Hoffmann     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
613d05959c2SGerd Hoffmann                                        VNC_DIRTY_PIXELS_PER_BIT));
614d05959c2SGerd Hoffmann }
615d05959c2SGerd Hoffmann 
616d05959c2SGerd Hoffmann static int vnc_height(VncDisplay *vd)
617d05959c2SGerd Hoffmann {
618d05959c2SGerd Hoffmann     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
619d05959c2SGerd Hoffmann }
620d05959c2SGerd Hoffmann 
621bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
622bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
623f7b3d68cSGerd Hoffmann                                VncDisplay *vd,
624f7b3d68cSGerd Hoffmann                                int x, int y, int w, int h)
625f7b3d68cSGerd Hoffmann {
626f7b3d68cSGerd Hoffmann     int width = vnc_width(vd);
627f7b3d68cSGerd Hoffmann     int height = vnc_height(vd);
628f7b3d68cSGerd Hoffmann 
62991937225SPeter Lieven     /* this is needed this to ensure we updated all affected
63091937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
631b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
632b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6333e230dd2SCorentin Chary 
6349f64916dSGerd Hoffmann     x = MIN(x, width);
6359f64916dSGerd Hoffmann     y = MIN(y, height);
6369f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
63791937225SPeter Lieven     h = MIN(y + h, height);
6383e230dd2SCorentin Chary 
639b4c85ddcSPeter Lieven     for (; y < h; y++) {
640bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
64191937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
642b4c85ddcSPeter Lieven     }
6433e230dd2SCorentin Chary }
6443e230dd2SCorentin Chary 
645bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
646bea60dd7SPeter Lieven                            int x, int y, int w, int h)
647bea60dd7SPeter Lieven {
648bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
649bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
650bea60dd7SPeter Lieven 
651f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
652bea60dd7SPeter Lieven }
653bea60dd7SPeter Lieven 
6543e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6553e230dd2SCorentin Chary                             int32_t encoding)
6563e230dd2SCorentin Chary {
6573e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6583e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6593e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6603e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6613e230dd2SCorentin Chary 
6623e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6633e230dd2SCorentin Chary }
6643e230dd2SCorentin Chary 
66532ed2680STim Hardeck 
6663e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
6673e230dd2SCorentin Chary {
66804d2529dSDaniel P. Berrange     if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
6693e230dd2SCorentin Chary         return;
6703e230dd2SCorentin Chary     }
671bea60dd7SPeter Lieven     if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
672bea60dd7SPeter Lieven         vs->client_height == pixman_image_get_height(vs->vd->server)) {
6733e230dd2SCorentin Chary         return;
6743e230dd2SCorentin Chary     }
675bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
676bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
677bd023f95SCorentin Chary     vnc_lock_output(vs);
6783e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
6793e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
6803e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
6813e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
6823e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
683bd023f95SCorentin Chary     vnc_unlock_output(vs);
6843e230dd2SCorentin Chary     vnc_flush(vs);
6853e230dd2SCorentin Chary }
6863e230dd2SCorentin Chary 
687bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
688bd023f95SCorentin Chary {
689bd023f95SCorentin Chary     VncState *vs;
690bd023f95SCorentin Chary 
691bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
692bd023f95SCorentin Chary         vnc_lock_output(vs);
693bd023f95SCorentin Chary         vs->abort = true;
694bd023f95SCorentin Chary         vnc_unlock_output(vs);
695bd023f95SCorentin Chary     }
696bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
697bd023f95SCorentin Chary         vnc_jobs_join(vs);
698bd023f95SCorentin Chary     }
699bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
700bd023f95SCorentin Chary         vnc_lock_output(vs);
701bd023f95SCorentin Chary         vs->abort = false;
702bd023f95SCorentin Chary         vnc_unlock_output(vs);
703bd023f95SCorentin Chary     }
704bd023f95SCorentin Chary }
705bd023f95SCorentin Chary 
7069f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
7079f64916dSGerd Hoffmann {
7089f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
7099f64916dSGerd Hoffmann }
7109f64916dSGerd Hoffmann 
7119f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
7129f64916dSGerd Hoffmann {
7139f64916dSGerd Hoffmann     uint8_t *ptr;
7149f64916dSGerd Hoffmann 
7159f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
7169f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
7179f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
7189f64916dSGerd Hoffmann     return ptr;
7199f64916dSGerd Hoffmann }
7209f64916dSGerd Hoffmann 
721453f842bSGerd Hoffmann static void vnc_update_server_surface(VncDisplay *vd)
722453f842bSGerd Hoffmann {
723b69a553bSDaniel P. Berrange     int width, height;
724b69a553bSDaniel P. Berrange 
725453f842bSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
726453f842bSGerd Hoffmann     vd->server = NULL;
727453f842bSGerd Hoffmann 
728c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vd->clients)) {
729c7628bffSGerd Hoffmann         return;
730c7628bffSGerd Hoffmann     }
731c7628bffSGerd Hoffmann 
732b69a553bSDaniel P. Berrange     width = vnc_width(vd);
733b69a553bSDaniel P. Berrange     height = vnc_height(vd);
734453f842bSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
735b69a553bSDaniel P. Berrange                                           width, height,
736453f842bSGerd Hoffmann                                           NULL, 0);
737b69a553bSDaniel P. Berrange 
738b69a553bSDaniel P. Berrange     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
739b69a553bSDaniel P. Berrange     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
740b69a553bSDaniel P. Berrange                        width, height);
741453f842bSGerd Hoffmann }
742453f842bSGerd Hoffmann 
743c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
744c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
7453e230dd2SCorentin Chary {
74621ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
7473e230dd2SCorentin Chary     VncState *vs;
7483e230dd2SCorentin Chary 
749bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
750453f842bSGerd Hoffmann     vd->ds = surface;
751bd023f95SCorentin Chary 
7523e230dd2SCorentin Chary     /* server surface */
753453f842bSGerd Hoffmann     vnc_update_server_surface(vd);
7543e230dd2SCorentin Chary 
7553e230dd2SCorentin Chary     /* guest surface */
7569f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
757d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
758d39fa6d8SGerd Hoffmann     vd->guest.format = surface->format;
7593e230dd2SCorentin Chary 
7603e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
7613e230dd2SCorentin Chary         vnc_colordepth(vs);
7623e230dd2SCorentin Chary         vnc_desktop_resize(vs);
7633e230dd2SCorentin Chary         if (vs->vd->cursor) {
7643e230dd2SCorentin Chary             vnc_cursor_define(vs);
7653e230dd2SCorentin Chary         }
766bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
767f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
768b69a553bSDaniel P. Berrange                            vnc_width(vd),
769b69a553bSDaniel P. Berrange                            vnc_height(vd));
770e2b72cb6SDaniel P. Berrange         vnc_update_throttle_offset(vs);
7713e230dd2SCorentin Chary     }
7723e230dd2SCorentin Chary }
7733e230dd2SCorentin Chary 
7743e230dd2SCorentin Chary /* fastest code */
7759f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
7763e230dd2SCorentin Chary                                   void *pixels, int size)
7773e230dd2SCorentin Chary {
7783e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
7793e230dd2SCorentin Chary }
7803e230dd2SCorentin Chary 
7813e230dd2SCorentin Chary /* slowest but generic code. */
7823e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
7833e230dd2SCorentin Chary {
7843e230dd2SCorentin Chary     uint8_t r, g, b;
7853e230dd2SCorentin Chary 
7869f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
7879f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
7889f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
7899f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
7909f64916dSGerd Hoffmann #else
7919f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
7929f64916dSGerd Hoffmann #endif
7939f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
7949f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
7959f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
7969f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
7973e230dd2SCorentin Chary     case 1:
7983e230dd2SCorentin Chary         buf[0] = v;
7993e230dd2SCorentin Chary         break;
8003e230dd2SCorentin Chary     case 2:
8019f64916dSGerd Hoffmann         if (vs->client_be) {
8023e230dd2SCorentin Chary             buf[0] = v >> 8;
8033e230dd2SCorentin Chary             buf[1] = v;
8043e230dd2SCorentin Chary         } else {
8053e230dd2SCorentin Chary             buf[1] = v >> 8;
8063e230dd2SCorentin Chary             buf[0] = v;
8073e230dd2SCorentin Chary         }
8083e230dd2SCorentin Chary         break;
8093e230dd2SCorentin Chary     default:
8103e230dd2SCorentin Chary     case 4:
8119f64916dSGerd Hoffmann         if (vs->client_be) {
8123e230dd2SCorentin Chary             buf[0] = v >> 24;
8133e230dd2SCorentin Chary             buf[1] = v >> 16;
8143e230dd2SCorentin Chary             buf[2] = v >> 8;
8153e230dd2SCorentin Chary             buf[3] = v;
8163e230dd2SCorentin Chary         } else {
8173e230dd2SCorentin Chary             buf[3] = v >> 24;
8183e230dd2SCorentin Chary             buf[2] = v >> 16;
8193e230dd2SCorentin Chary             buf[1] = v >> 8;
8203e230dd2SCorentin Chary             buf[0] = v;
8213e230dd2SCorentin Chary         }
8223e230dd2SCorentin Chary         break;
8233e230dd2SCorentin Chary     }
8243e230dd2SCorentin Chary }
8253e230dd2SCorentin Chary 
8269f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
8273e230dd2SCorentin Chary                                      void *pixels1, int size)
8283e230dd2SCorentin Chary {
8293e230dd2SCorentin Chary     uint8_t buf[4];
8303e230dd2SCorentin Chary 
8319f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
8323e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
8333e230dd2SCorentin Chary         int n, i;
8343e230dd2SCorentin Chary         n = size >> 2;
8353e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
8363e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
8379f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
8383e230dd2SCorentin Chary         }
8393e230dd2SCorentin Chary     }
8403e230dd2SCorentin Chary }
8413e230dd2SCorentin Chary 
8423e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8433e230dd2SCorentin Chary {
8443e230dd2SCorentin Chary     int i;
8453e230dd2SCorentin Chary     uint8_t *row;
8463e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
8473e230dd2SCorentin Chary 
8489f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
8493e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
8509f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
8519f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
8523e230dd2SCorentin Chary     }
8533e230dd2SCorentin Chary     return 1;
8543e230dd2SCorentin Chary }
8553e230dd2SCorentin Chary 
856bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8573e230dd2SCorentin Chary {
8583e230dd2SCorentin Chary     int n = 0;
859de3f7de7SPeter Lieven     bool encode_raw = false;
860de3f7de7SPeter Lieven     size_t saved_offs = vs->output.offset;
8613e230dd2SCorentin Chary 
8623e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
8633e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
8643e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
8653e230dd2SCorentin Chary             break;
8663e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
8673e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
8683e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
8693e230dd2SCorentin Chary             break;
8703e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
8713e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
8723e230dd2SCorentin Chary             break;
873efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
874efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
875efe556adSCorentin Chary             break;
876148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
877148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
878148954faSCorentin Chary             break;
879148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
880148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
881148954faSCorentin Chary             break;
8823e230dd2SCorentin Chary         default:
883de3f7de7SPeter Lieven             encode_raw = true;
8843e230dd2SCorentin Chary             break;
8853e230dd2SCorentin Chary     }
886de3f7de7SPeter Lieven 
887de3f7de7SPeter Lieven     /* If the client has the same pixel format as our internal buffer and
888de3f7de7SPeter Lieven      * a RAW encoding would need less space fall back to RAW encoding to
889de3f7de7SPeter Lieven      * save bandwidth and processing power in the client. */
890de3f7de7SPeter Lieven     if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
891de3f7de7SPeter Lieven         12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
892de3f7de7SPeter Lieven         vs->output.offset = saved_offs;
893de3f7de7SPeter Lieven         encode_raw = true;
894de3f7de7SPeter Lieven     }
895de3f7de7SPeter Lieven 
896de3f7de7SPeter Lieven     if (encode_raw) {
897de3f7de7SPeter Lieven         vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
898de3f7de7SPeter Lieven         n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
899de3f7de7SPeter Lieven     }
900de3f7de7SPeter Lieven 
9013e230dd2SCorentin Chary     return n;
9023e230dd2SCorentin Chary }
9033e230dd2SCorentin Chary 
9047c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9057c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9063e230dd2SCorentin Chary {
9073e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9083e230dd2SCorentin Chary }
9093e230dd2SCorentin Chary 
9103e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
9113e230dd2SCorentin Chary {
9123e230dd2SCorentin Chary     QEMUCursor *c = vs->vd->cursor;
9133e230dd2SCorentin Chary     int isize;
9143e230dd2SCorentin Chary 
9153e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
916d01f9595SCorentin Chary         vnc_lock_output(vs);
9173e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
9183e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
9193e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
9203e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
9213e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
9229f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
9239f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
9243e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
925d01f9595SCorentin Chary         vnc_unlock_output(vs);
9263e230dd2SCorentin Chary         return 0;
9273e230dd2SCorentin Chary     }
9283e230dd2SCorentin Chary     return -1;
9293e230dd2SCorentin Chary }
9303e230dd2SCorentin Chary 
9317c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
9327c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
9333e230dd2SCorentin Chary {
934d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
9353e230dd2SCorentin Chary     VncState *vs;
9363e230dd2SCorentin Chary 
9373e230dd2SCorentin Chary     cursor_put(vd->cursor);
9387267c094SAnthony Liguori     g_free(vd->cursor_mask);
9393e230dd2SCorentin Chary 
9403e230dd2SCorentin Chary     vd->cursor = c;
9413e230dd2SCorentin Chary     cursor_get(vd->cursor);
9423e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
9437267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
9443e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
9453e230dd2SCorentin Chary 
9463e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
9473e230dd2SCorentin Chary         vnc_cursor_define(vs);
9483e230dd2SCorentin Chary     }
9493e230dd2SCorentin Chary }
9503e230dd2SCorentin Chary 
9514769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
9526c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
9533e230dd2SCorentin Chary {
9543e230dd2SCorentin Chary     int h;
9553e230dd2SCorentin Chary 
9566c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
957bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
9583e230dd2SCorentin Chary             break;
959bc2429b9SCorentin Chary         }
960863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
9613e230dd2SCorentin Chary     }
9623e230dd2SCorentin Chary 
9633e230dd2SCorentin Chary     return h;
9643e230dd2SCorentin Chary }
9653e230dd2SCorentin Chary 
966e2b72cb6SDaniel P. Berrange /*
967e2b72cb6SDaniel P. Berrange  * Figure out how much pending data we should allow in the output
968e2b72cb6SDaniel P. Berrange  * buffer before we throttle incremental display updates, and/or
969e2b72cb6SDaniel P. Berrange  * drop audio samples.
970e2b72cb6SDaniel P. Berrange  *
971e2b72cb6SDaniel P. Berrange  * We allow for equiv of 1 full display's worth of FB updates,
972e2b72cb6SDaniel P. Berrange  * and 1 second of audio samples. If audio backlog was larger
973e2b72cb6SDaniel P. Berrange  * than that the client would already suffering awful audio
974e2b72cb6SDaniel P. Berrange  * glitches, so dropping samples is no worse really).
975e2b72cb6SDaniel P. Berrange  */
976e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs)
977e2b72cb6SDaniel P. Berrange {
978e2b72cb6SDaniel P. Berrange     size_t offset =
979e2b72cb6SDaniel P. Berrange         vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
980e2b72cb6SDaniel P. Berrange 
981e2b72cb6SDaniel P. Berrange     if (vs->audio_cap) {
982e2b72cb6SDaniel P. Berrange         int freq = vs->as.freq;
983e2b72cb6SDaniel P. Berrange         /* We don't limit freq when reading settings from client, so
984e2b72cb6SDaniel P. Berrange          * it could be upto MAX_INT in size. 48khz is a sensible
985e2b72cb6SDaniel P. Berrange          * upper bound for trustworthy clients */
986e2b72cb6SDaniel P. Berrange         int bps;
987e2b72cb6SDaniel P. Berrange         if (freq > 48000) {
988e2b72cb6SDaniel P. Berrange             freq = 48000;
989e2b72cb6SDaniel P. Berrange         }
990e2b72cb6SDaniel P. Berrange         switch (vs->as.fmt) {
991e2b72cb6SDaniel P. Berrange         default:
992e2b72cb6SDaniel P. Berrange         case  AUD_FMT_U8:
993e2b72cb6SDaniel P. Berrange         case  AUD_FMT_S8:
994e2b72cb6SDaniel P. Berrange             bps = 1;
995e2b72cb6SDaniel P. Berrange             break;
996e2b72cb6SDaniel P. Berrange         case  AUD_FMT_U16:
997e2b72cb6SDaniel P. Berrange         case  AUD_FMT_S16:
998e2b72cb6SDaniel P. Berrange             bps = 2;
999e2b72cb6SDaniel P. Berrange             break;
1000e2b72cb6SDaniel P. Berrange         case  AUD_FMT_U32:
1001e2b72cb6SDaniel P. Berrange         case  AUD_FMT_S32:
1002e2b72cb6SDaniel P. Berrange             bps = 4;
1003e2b72cb6SDaniel P. Berrange             break;
1004e2b72cb6SDaniel P. Berrange         }
1005e2b72cb6SDaniel P. Berrange         offset += freq * bps * vs->as.nchannels;
1006e2b72cb6SDaniel P. Berrange     }
1007e2b72cb6SDaniel P. Berrange 
1008e2b72cb6SDaniel P. Berrange     /* Put a floor of 1MB on offset, so that if we have a large pending
1009e2b72cb6SDaniel P. Berrange      * buffer and the display is resized to a small size & back again
1010e2b72cb6SDaniel P. Berrange      * we don't suddenly apply a tiny send limit
1011e2b72cb6SDaniel P. Berrange      */
1012e2b72cb6SDaniel P. Berrange     offset = MAX(offset, 1024 * 1024);
1013e2b72cb6SDaniel P. Berrange 
10146aa22a29SDaniel P. Berrange     if (vs->throttle_output_offset != offset) {
10156aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_threshold(
10166aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
10176aa22a29SDaniel P. Berrange             vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
10186aa22a29SDaniel P. Berrange     }
10196aa22a29SDaniel P. Berrange 
1020e2b72cb6SDaniel P. Berrange     vs->throttle_output_offset = offset;
1021e2b72cb6SDaniel P. Berrange }
1022e2b72cb6SDaniel P. Berrange 
10230bad8342SDaniel P. Berrange static bool vnc_should_update(VncState *vs)
10240bad8342SDaniel P. Berrange {
10250bad8342SDaniel P. Berrange     switch (vs->update) {
10260bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_NONE:
10270bad8342SDaniel P. Berrange         break;
10280bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_INCREMENTAL:
1029e2b72cb6SDaniel P. Berrange         /* Only allow incremental updates if the pending send queue
1030ada8d2e4SDaniel P. Berrange          * is less than the permitted threshold, and the job worker
1031ada8d2e4SDaniel P. Berrange          * is completely idle.
10320bad8342SDaniel P. Berrange          */
1033ada8d2e4SDaniel P. Berrange         if (vs->output.offset < vs->throttle_output_offset &&
1034ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
10350bad8342SDaniel P. Berrange             return true;
10360bad8342SDaniel P. Berrange         }
10376aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_incremental(
10386aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->output.offset);
10390bad8342SDaniel P. Berrange         break;
10400bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_FORCE:
1041ada8d2e4SDaniel P. Berrange         /* Only allow forced updates if the pending send queue
1042ada8d2e4SDaniel P. Berrange          * does not contain a previous forced update, and the
1043ada8d2e4SDaniel P. Berrange          * job worker is completely idle.
1044ada8d2e4SDaniel P. Berrange          *
1045ada8d2e4SDaniel P. Berrange          * Note this means we'll queue a forced update, even if
1046ada8d2e4SDaniel P. Berrange          * the output buffer size is otherwise over the throttle
1047ada8d2e4SDaniel P. Berrange          * output limit.
1048ada8d2e4SDaniel P. Berrange          */
1049ada8d2e4SDaniel P. Berrange         if (vs->force_update_offset == 0 &&
1050ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
10510bad8342SDaniel P. Berrange             return true;
10520bad8342SDaniel P. Berrange         }
10536aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_forced(
10546aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->force_update_offset);
1055ada8d2e4SDaniel P. Berrange         break;
1056ada8d2e4SDaniel P. Berrange     }
10570bad8342SDaniel P. Berrange     return false;
10580bad8342SDaniel P. Berrange }
10590bad8342SDaniel P. Berrange 
10606af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty)
10613e230dd2SCorentin Chary {
10623e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
1063bd023f95SCorentin Chary     VncJob *job;
10643e230dd2SCorentin Chary     int y;
10652f487a3dSPeter Lieven     int height, width;
1066bd023f95SCorentin Chary     int n = 0;
1067bd023f95SCorentin Chary 
1068b939eb89SDaniel P. Berrange     if (vs->disconnecting) {
1069b939eb89SDaniel P. Berrange         vnc_disconnect_finish(vs);
1070b939eb89SDaniel P. Berrange         return 0;
1071b939eb89SDaniel P. Berrange     }
1072b939eb89SDaniel P. Berrange 
1073b939eb89SDaniel P. Berrange     vs->has_dirty += has_dirty;
10740bad8342SDaniel P. Berrange     if (!vnc_should_update(vs)) {
10753e230dd2SCorentin Chary         return 0;
1076b939eb89SDaniel P. Berrange     }
10773e230dd2SCorentin Chary 
1078fef1bbadSDaniel P. Berrange     if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
10793e230dd2SCorentin Chary         return 0;
1080b939eb89SDaniel P. Berrange     }
10813e230dd2SCorentin Chary 
10823e230dd2SCorentin Chary     /*
10833e230dd2SCorentin Chary      * Send screen updates to the vnc client using the server
10843e230dd2SCorentin Chary      * surface and server dirty map.  guest surface updates
10853e230dd2SCorentin Chary      * happening in parallel don't disturb us, the next pass will
10863e230dd2SCorentin Chary      * send them to the client.
10873e230dd2SCorentin Chary      */
1088bd023f95SCorentin Chary     job = vnc_job_new(vs);
10893e230dd2SCorentin Chary 
1090bea60dd7SPeter Lieven     height = pixman_image_get_height(vd->server);
1091bea60dd7SPeter Lieven     width = pixman_image_get_width(vd->server);
10923e230dd2SCorentin Chary 
109312b316d4SPeter Lieven     y = 0;
109412b316d4SPeter Lieven     for (;;) {
109512b316d4SPeter Lieven         int x, h;
109612b316d4SPeter Lieven         unsigned long x2;
109712b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
109812b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(vs),
109912b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(vs));
110012b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(vs)) {
110112b316d4SPeter Lieven             /* no more dirty bits */
110212b316d4SPeter Lieven             break;
11033e230dd2SCorentin Chary         }
110412b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(vs);
110512b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(vs);
110612b316d4SPeter Lieven         x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
110712b316d4SPeter Lieven                                 VNC_DIRTY_BPL(vs), x);
110812b316d4SPeter Lieven         bitmap_clear(vs->dirty[y], x, x2 - x);
110912b316d4SPeter Lieven         h = find_and_clear_dirty_height(vs, y, x, x2, height);
11102f487a3dSPeter Lieven         x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
11112f487a3dSPeter Lieven         if (x2 > x) {
111212b316d4SPeter Lieven             n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
111312b316d4SPeter Lieven                                   (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
11143e230dd2SCorentin Chary         }
11150e7d6f60SPeter Lieven         if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
11160e7d6f60SPeter Lieven             y += h;
11170e7d6f60SPeter Lieven             if (y == height) {
11180e7d6f60SPeter Lieven                 break;
11190e7d6f60SPeter Lieven             }
11200e7d6f60SPeter Lieven         }
11212f487a3dSPeter Lieven     }
1122bd023f95SCorentin Chary 
1123ada8d2e4SDaniel P. Berrange     vs->job_update = vs->update;
1124728a7ac9SDaniel P. Berrange     vs->update = VNC_STATE_UPDATE_NONE;
1125ada8d2e4SDaniel P. Berrange     vnc_job_push(job);
112663658280SGerd Hoffmann     vs->has_dirty = 0;
1127bd023f95SCorentin Chary     return n;
11283e230dd2SCorentin Chary }
11293e230dd2SCorentin Chary 
11303e230dd2SCorentin Chary /* audio */
11313e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
11323e230dd2SCorentin Chary {
11333e230dd2SCorentin Chary     VncState *vs = opaque;
11343e230dd2SCorentin Chary 
11353e230dd2SCorentin Chary     switch (cmd) {
11363e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1137bd023f95SCorentin Chary         vnc_lock_output(vs);
11383e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11393e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11403e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1141bd023f95SCorentin Chary         vnc_unlock_output(vs);
11423e230dd2SCorentin Chary         vnc_flush(vs);
11433e230dd2SCorentin Chary         break;
11443e230dd2SCorentin Chary 
11453e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1146bd023f95SCorentin Chary         vnc_lock_output(vs);
11473e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11483e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11493e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1150bd023f95SCorentin Chary         vnc_unlock_output(vs);
11513e230dd2SCorentin Chary         vnc_flush(vs);
11523e230dd2SCorentin Chary         break;
11533e230dd2SCorentin Chary     }
11543e230dd2SCorentin Chary }
11553e230dd2SCorentin Chary 
11563e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
11573e230dd2SCorentin Chary {
11583e230dd2SCorentin Chary }
11593e230dd2SCorentin Chary 
11603e230dd2SCorentin Chary static void audio_capture(void *opaque, void *buf, int size)
11613e230dd2SCorentin Chary {
11623e230dd2SCorentin Chary     VncState *vs = opaque;
11633e230dd2SCorentin Chary 
1164bd023f95SCorentin Chary     vnc_lock_output(vs);
1165e2b72cb6SDaniel P. Berrange     if (vs->output.offset < vs->throttle_output_offset) {
11663e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11673e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11683e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
11693e230dd2SCorentin Chary         vnc_write_u32(vs, size);
11703e230dd2SCorentin Chary         vnc_write(vs, buf, size);
11716aa22a29SDaniel P. Berrange     } else {
11726aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1173e2b72cb6SDaniel P. Berrange     }
1174bd023f95SCorentin Chary     vnc_unlock_output(vs);
11753e230dd2SCorentin Chary     vnc_flush(vs);
11763e230dd2SCorentin Chary }
11773e230dd2SCorentin Chary 
11783e230dd2SCorentin Chary static void audio_add(VncState *vs)
11793e230dd2SCorentin Chary {
11803e230dd2SCorentin Chary     struct audio_capture_ops ops;
11813e230dd2SCorentin Chary 
11823e230dd2SCorentin Chary     if (vs->audio_cap) {
1183027a79c3SCole Robinson         error_report("audio already running");
11843e230dd2SCorentin Chary         return;
11853e230dd2SCorentin Chary     }
11863e230dd2SCorentin Chary 
11873e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
11883e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
11893e230dd2SCorentin Chary     ops.capture = audio_capture;
11903e230dd2SCorentin Chary 
11913e230dd2SCorentin Chary     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
11923e230dd2SCorentin Chary     if (!vs->audio_cap) {
1193027a79c3SCole Robinson         error_report("Failed to add audio capture");
11943e230dd2SCorentin Chary     }
11953e230dd2SCorentin Chary }
11963e230dd2SCorentin Chary 
11973e230dd2SCorentin Chary static void audio_del(VncState *vs)
11983e230dd2SCorentin Chary {
11993e230dd2SCorentin Chary     if (vs->audio_cap) {
12003e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
12013e230dd2SCorentin Chary         vs->audio_cap = NULL;
12023e230dd2SCorentin Chary     }
12033e230dd2SCorentin Chary }
12043e230dd2SCorentin Chary 
12053e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
12063e230dd2SCorentin Chary {
120704d2529dSDaniel P. Berrange     if (vs->disconnecting) {
12083e230dd2SCorentin Chary         return;
120904d2529dSDaniel P. Berrange     }
1210ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_start(vs, vs->ioc);
12118cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
121204d2529dSDaniel P. Berrange     if (vs->ioc_tag) {
121304d2529dSDaniel P. Berrange         g_source_remove(vs->ioc_tag);
1214a75d6f07SBrandon Carpenter         vs->ioc_tag = 0;
121504d2529dSDaniel P. Berrange     }
121604d2529dSDaniel P. Berrange     qio_channel_close(vs->ioc, NULL);
121704d2529dSDaniel P. Berrange     vs->disconnecting = TRUE;
12183e230dd2SCorentin Chary }
12193e230dd2SCorentin Chary 
12207536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
12213e230dd2SCorentin Chary {
12227d964c9dSCorentin Chary     int i;
12237d964c9dSCorentin Chary 
1224ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_finish(vs, vs->ioc);
1225ad6374c4SDaniel P. Berrange 
1226bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1227bd023f95SCorentin Chary 
1228bd023f95SCorentin Chary     vnc_lock_output(vs);
1229fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
12303e230dd2SCorentin Chary 
12313e230dd2SCorentin Chary     buffer_free(&vs->input);
12323e230dd2SCorentin Chary     buffer_free(&vs->output);
12333e230dd2SCorentin Chary 
1234fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
12353e230dd2SCorentin Chary 
12363e230dd2SCorentin Chary     vnc_zlib_clear(vs);
12373e230dd2SCorentin Chary     vnc_tight_clear(vs);
1238148954faSCorentin Chary     vnc_zrle_clear(vs);
12393e230dd2SCorentin Chary 
12403e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
12413e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
12423e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
12433e230dd2SCorentin Chary     audio_del(vs);
12447bc9318bSGerd Hoffmann     vnc_release_modifiers(vs);
12453e230dd2SCorentin Chary 
124690cd03a3SDaniel P. Berrange     if (vs->mouse_mode_notifier.notify != NULL) {
12476fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
124890cd03a3SDaniel P. Berrange     }
124990cd03a3SDaniel P. Berrange     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1250c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1251c7628bffSGerd Hoffmann         /* last client gone */
1252c7628bffSGerd Hoffmann         vnc_update_server_surface(vs->vd);
1253c7628bffSGerd Hoffmann     }
12543e230dd2SCorentin Chary 
1255bd023f95SCorentin Chary     vnc_unlock_output(vs);
1256bd023f95SCorentin Chary 
1257bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
12586fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1259175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
12606fd8e79aSTim Hardeck     }
1261175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1262175b2a6eSCorentin Chary 
12637d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
12647267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
12657d964c9dSCorentin Chary     }
12667267c094SAnthony Liguori     g_free(vs->lossy_rect);
126704d2529dSDaniel P. Berrange 
126804d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->ioc));
126904d2529dSDaniel P. Berrange     vs->ioc = NULL;
127004d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->sioc));
127104d2529dSDaniel P. Berrange     vs->sioc = NULL;
12727267c094SAnthony Liguori     g_free(vs);
12733e230dd2SCorentin Chary }
12743e230dd2SCorentin Chary 
1275*30b80fd5SDaniel P. Berrange size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
12763e230dd2SCorentin Chary {
127704d2529dSDaniel P. Berrange     if (ret <= 0) {
127804d2529dSDaniel P. Berrange         if (ret == 0) {
1279ad6374c4SDaniel P. Berrange             trace_vnc_client_eof(vs, vs->ioc);
1280537848eeSMichael Tokarev             vnc_disconnect_start(vs);
128104d2529dSDaniel P. Berrange         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1282ad6374c4SDaniel P. Berrange             trace_vnc_client_io_error(vs, vs->ioc,
1283ad6374c4SDaniel P. Berrange                                       errp ? error_get_pretty(*errp) :
1284ad6374c4SDaniel P. Berrange                                       "Unknown");
1285537848eeSMichael Tokarev             vnc_disconnect_start(vs);
12863e230dd2SCorentin Chary         }
12873e230dd2SCorentin Chary 
128804d2529dSDaniel P. Berrange         if (errp) {
128904d2529dSDaniel P. Berrange             error_free(*errp);
129004d2529dSDaniel P. Berrange             *errp = NULL;
129104d2529dSDaniel P. Berrange         }
12923e230dd2SCorentin Chary         return 0;
12933e230dd2SCorentin Chary     }
12943e230dd2SCorentin Chary     return ret;
12953e230dd2SCorentin Chary }
12963e230dd2SCorentin Chary 
12973e230dd2SCorentin Chary 
12983e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
12993e230dd2SCorentin Chary {
13003e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
13013e230dd2SCorentin Chary     vnc_disconnect_start(vs);
13023e230dd2SCorentin Chary }
13033e230dd2SCorentin Chary 
13043e305e4aSDaniel P. Berrange 
13053e230dd2SCorentin Chary /*
13063e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
13073e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
13083e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
13093e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
13103e230dd2SCorentin Chary  *
13113e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
13123e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
13133e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
13143e230dd2SCorentin Chary  * is active
13153e230dd2SCorentin Chary  *
13163e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13173e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
1318*30b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
13193e230dd2SCorentin Chary  */
1320*30b80fd5SDaniel P. Berrange size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
13213e230dd2SCorentin Chary {
132204d2529dSDaniel P. Berrange     Error *err = NULL;
1323fdd1ab6aSDaniel P. Berrange     ssize_t ret;
132404d2529dSDaniel P. Berrange     ret = qio_channel_write(
132504d2529dSDaniel P. Berrange         vs->ioc, (const char *)data, datalen, &err);
13263e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
132704d2529dSDaniel P. Berrange     return vnc_client_io_error(vs, ret, &err);
13283e230dd2SCorentin Chary }
13293e230dd2SCorentin Chary 
13303e230dd2SCorentin Chary 
13313e230dd2SCorentin Chary /*
13323e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
13333e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
13343e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
13353e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
13363e230dd2SCorentin Chary  *
13373e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13383e230dd2SCorentin Chary  * the buffered output data if the socket would block.  Returns
1339*30b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
13403e230dd2SCorentin Chary  */
1341*30b80fd5SDaniel P. Berrange static size_t vnc_client_write_plain(VncState *vs)
13423e230dd2SCorentin Chary {
13436aa22a29SDaniel P. Berrange     size_t offset;
1344*30b80fd5SDaniel P. Berrange     size_t ret;
13453e230dd2SCorentin Chary 
13463e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13473e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
13483e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
13493e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
13503e230dd2SCorentin Chary 
13513e230dd2SCorentin Chary     if (vs->sasl.conn &&
13523e230dd2SCorentin Chary         vs->sasl.runSSF &&
13533e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
13543e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
13553e230dd2SCorentin Chary         if (ret)
13563e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
13573e230dd2SCorentin Chary     } else
13583e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13593e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
13603e230dd2SCorentin Chary     if (!ret)
13613e230dd2SCorentin Chary         return 0;
13623e230dd2SCorentin Chary 
1363ada8d2e4SDaniel P. Berrange     if (ret >= vs->force_update_offset) {
13646aa22a29SDaniel P. Berrange         if (vs->force_update_offset != 0) {
13656aa22a29SDaniel P. Berrange             trace_vnc_client_unthrottle_forced(vs, vs->ioc);
13666aa22a29SDaniel P. Berrange         }
1367ada8d2e4SDaniel P. Berrange         vs->force_update_offset = 0;
1368ada8d2e4SDaniel P. Berrange     } else {
1369ada8d2e4SDaniel P. Berrange         vs->force_update_offset -= ret;
1370ada8d2e4SDaniel P. Berrange     }
13716aa22a29SDaniel P. Berrange     offset = vs->output.offset;
137232ed2680STim Hardeck     buffer_advance(&vs->output, ret);
13736aa22a29SDaniel P. Berrange     if (offset >= vs->throttle_output_offset &&
13746aa22a29SDaniel P. Berrange         vs->output.offset < vs->throttle_output_offset) {
13756aa22a29SDaniel P. Berrange         trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
13766aa22a29SDaniel P. Berrange     }
13773e230dd2SCorentin Chary 
13783e230dd2SCorentin Chary     if (vs->output.offset == 0) {
137904d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
138004d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
138104d2529dSDaniel P. Berrange         }
138204d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
138304d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
13843e230dd2SCorentin Chary     }
13853e230dd2SCorentin Chary 
13863e230dd2SCorentin Chary     return ret;
13873e230dd2SCorentin Chary }
13883e230dd2SCorentin Chary 
13893e230dd2SCorentin Chary 
13903e230dd2SCorentin Chary /*
13913e230dd2SCorentin Chary  * First function called whenever there is data to be written to
13923e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
13933e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
13943e230dd2SCorentin Chary  */
139504d2529dSDaniel P. Berrange static void vnc_client_write_locked(VncState *vs)
13963e230dd2SCorentin Chary {
13973e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13983e230dd2SCorentin Chary     if (vs->sasl.conn &&
13993e230dd2SCorentin Chary         vs->sasl.runSSF &&
14003e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
14013e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
14023e230dd2SCorentin Chary     } else
14033e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14047536ee4bSTim Hardeck     {
14053e230dd2SCorentin Chary         vnc_client_write_plain(vs);
14063e230dd2SCorentin Chary     }
14077536ee4bSTim Hardeck }
14083e230dd2SCorentin Chary 
140904d2529dSDaniel P. Berrange static void vnc_client_write(VncState *vs)
1410bd023f95SCorentin Chary {
1411bd023f95SCorentin Chary 
1412bd023f95SCorentin Chary     vnc_lock_output(vs);
1413d5f04223SDaniel P. Berrange     if (vs->output.offset) {
141404d2529dSDaniel P. Berrange         vnc_client_write_locked(vs);
141504d2529dSDaniel P. Berrange     } else if (vs->ioc != NULL) {
141604d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
141704d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
141804d2529dSDaniel P. Berrange         }
141904d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
142004d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1421bd023f95SCorentin Chary     }
1422bd023f95SCorentin Chary     vnc_unlock_output(vs);
1423bd023f95SCorentin Chary }
1424bd023f95SCorentin Chary 
14253e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
14263e230dd2SCorentin Chary {
14273e230dd2SCorentin Chary     vs->read_handler = func;
14283e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
14293e230dd2SCorentin Chary }
14303e230dd2SCorentin Chary 
14313e230dd2SCorentin Chary 
14323e230dd2SCorentin Chary /*
14333e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
14343e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
14353e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
14363e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
14373e230dd2SCorentin Chary  *
14383e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
14393e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
14403e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
14413e230dd2SCorentin Chary  * is active
14423e230dd2SCorentin Chary  *
14433e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
14443e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
1445*30b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
14463e230dd2SCorentin Chary  */
1447*30b80fd5SDaniel P. Berrange size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
14483e230dd2SCorentin Chary {
1449fdd1ab6aSDaniel P. Berrange     ssize_t ret;
145004d2529dSDaniel P. Berrange     Error *err = NULL;
145104d2529dSDaniel P. Berrange     ret = qio_channel_read(
145204d2529dSDaniel P. Berrange         vs->ioc, (char *)data, datalen, &err);
14533e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
145404d2529dSDaniel P. Berrange     return vnc_client_io_error(vs, ret, &err);
14553e230dd2SCorentin Chary }
14563e230dd2SCorentin Chary 
14573e230dd2SCorentin Chary 
14583e230dd2SCorentin Chary /*
14593e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
14603e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
14613e230dd2SCorentin Chary  * data as possible without blocking.
14623e230dd2SCorentin Chary  *
1463*30b80fd5SDaniel P. Berrange  * Returns the number of bytes read, which may be less than
1464*30b80fd5SDaniel P. Berrange  * the requested 'datalen' if the socket would block. Returns
1465*30b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
14663e230dd2SCorentin Chary  */
1467*30b80fd5SDaniel P. Berrange static size_t vnc_client_read_plain(VncState *vs)
14683e230dd2SCorentin Chary {
1469*30b80fd5SDaniel P. Berrange     size_t ret;
14703e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
14713e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
14723e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
14733e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
14743e230dd2SCorentin Chary     if (!ret)
14753e230dd2SCorentin Chary         return 0;
14763e230dd2SCorentin Chary     vs->input.offset += ret;
14773e230dd2SCorentin Chary     return ret;
14783e230dd2SCorentin Chary }
14793e230dd2SCorentin Chary 
1480175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1481175b2a6eSCorentin Chary {
1482175b2a6eSCorentin Chary     VncState *vs = opaque;
1483175b2a6eSCorentin Chary 
1484175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1485175b2a6eSCorentin Chary }
14863e230dd2SCorentin Chary 
14873e230dd2SCorentin Chary /*
14883e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
14893e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
14903e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
1491ea697449SDaniel P. Berrange  * Returns 0 on success, -1 if client disconnected
14923e230dd2SCorentin Chary  */
1493ea697449SDaniel P. Berrange static int vnc_client_read(VncState *vs)
14943e230dd2SCorentin Chary {
1495*30b80fd5SDaniel P. Berrange     size_t ret;
14963e230dd2SCorentin Chary 
14973e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14983e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
14993e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
15003e230dd2SCorentin Chary     else
15013e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
15023e230dd2SCorentin Chary         ret = vnc_client_read_plain(vs);
15033e230dd2SCorentin Chary     if (!ret) {
150404d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15053e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1506ea697449SDaniel P. Berrange             return -1;
150704d2529dSDaniel P. Berrange         }
1508ea697449SDaniel P. Berrange         return 0;
15093e230dd2SCorentin Chary     }
15103e230dd2SCorentin Chary 
15113e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
15123e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
15133e230dd2SCorentin Chary         int ret;
15143e230dd2SCorentin Chary 
15153e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
151604d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15173e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1518ea697449SDaniel P. Berrange             return -1;
15193e230dd2SCorentin Chary         }
15203e230dd2SCorentin Chary 
15213e230dd2SCorentin Chary         if (!ret) {
152232ed2680STim Hardeck             buffer_advance(&vs->input, len);
15233e230dd2SCorentin Chary         } else {
15243e230dd2SCorentin Chary             vs->read_handler_expect = ret;
15253e230dd2SCorentin Chary         }
15263e230dd2SCorentin Chary     }
1527ea697449SDaniel P. Berrange     return 0;
15283e230dd2SCorentin Chary }
15293e230dd2SCorentin Chary 
153004d2529dSDaniel P. Berrange gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
153104d2529dSDaniel P. Berrange                        GIOCondition condition, void *opaque)
153204d2529dSDaniel P. Berrange {
153304d2529dSDaniel P. Berrange     VncState *vs = opaque;
153404d2529dSDaniel P. Berrange     if (condition & G_IO_IN) {
1535ea697449SDaniel P. Berrange         if (vnc_client_read(vs) < 0) {
1536ea697449SDaniel P. Berrange             return TRUE;
1537ea697449SDaniel P. Berrange         }
153804d2529dSDaniel P. Berrange     }
153904d2529dSDaniel P. Berrange     if (condition & G_IO_OUT) {
154004d2529dSDaniel P. Berrange         vnc_client_write(vs);
154104d2529dSDaniel P. Berrange     }
154204d2529dSDaniel P. Berrange     return TRUE;
154304d2529dSDaniel P. Berrange }
154404d2529dSDaniel P. Berrange 
154504d2529dSDaniel P. Berrange 
1546f887cf16SDaniel P. Berrange /*
1547f887cf16SDaniel P. Berrange  * Scale factor to apply to vs->throttle_output_offset when checking for
1548f887cf16SDaniel P. Berrange  * hard limit. Worst case normal usage could be x2, if we have a complete
1549f887cf16SDaniel P. Berrange  * incremental update and complete forced update in the output buffer.
1550f887cf16SDaniel P. Berrange  * So x3 should be good enough, but we pick x5 to be conservative and thus
1551f887cf16SDaniel P. Berrange  * (hopefully) never trigger incorrectly.
1552f887cf16SDaniel P. Berrange  */
1553f887cf16SDaniel P. Berrange #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1554f887cf16SDaniel P. Berrange 
15553e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
15563e230dd2SCorentin Chary {
1557f887cf16SDaniel P. Berrange     if (vs->disconnecting) {
1558f887cf16SDaniel P. Berrange         return;
1559f887cf16SDaniel P. Berrange     }
1560f887cf16SDaniel P. Berrange     /* Protection against malicious client/guest to prevent our output
1561f887cf16SDaniel P. Berrange      * buffer growing without bound if client stops reading data. This
1562f887cf16SDaniel P. Berrange      * should rarely trigger, because we have earlier throttling code
1563f887cf16SDaniel P. Berrange      * which stops issuing framebuffer updates and drops audio data
1564f887cf16SDaniel P. Berrange      * if the throttle_output_offset value is exceeded. So we only reach
1565f887cf16SDaniel P. Berrange      * this higher level if a huge number of pseudo-encodings get
1566f887cf16SDaniel P. Berrange      * triggered while data can't be sent on the socket.
1567f887cf16SDaniel P. Berrange      *
1568f887cf16SDaniel P. Berrange      * NB throttle_output_offset can be zero during early protocol
1569f887cf16SDaniel P. Berrange      * handshake, or from the job thread's VncState clone
1570f887cf16SDaniel P. Berrange      */
1571f887cf16SDaniel P. Berrange     if (vs->throttle_output_offset != 0 &&
1572f887cf16SDaniel P. Berrange         vs->output.offset > (vs->throttle_output_offset *
1573f887cf16SDaniel P. Berrange                              VNC_THROTTLE_OUTPUT_LIMIT_SCALE)) {
15746aa22a29SDaniel P. Berrange         trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
15756aa22a29SDaniel P. Berrange                                       vs->throttle_output_offset);
1576f887cf16SDaniel P. Berrange         vnc_disconnect_start(vs);
1577f887cf16SDaniel P. Berrange         return;
1578f887cf16SDaniel P. Berrange     }
15793e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
15803e230dd2SCorentin Chary 
158104d2529dSDaniel P. Berrange     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
158204d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
158304d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
158404d2529dSDaniel P. Berrange         }
158504d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
158604d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
15873e230dd2SCorentin Chary     }
15883e230dd2SCorentin Chary 
15893e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
15903e230dd2SCorentin Chary }
15913e230dd2SCorentin Chary 
15923e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
15933e230dd2SCorentin Chary {
15943e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
15953e230dd2SCorentin Chary }
15963e230dd2SCorentin Chary 
15973e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
15983e230dd2SCorentin Chary {
15993e230dd2SCorentin Chary     uint8_t buf[4];
16003e230dd2SCorentin Chary 
16013e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
16023e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
16033e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
16043e230dd2SCorentin Chary     buf[3] = value & 0xFF;
16053e230dd2SCorentin Chary 
16063e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
16073e230dd2SCorentin Chary }
16083e230dd2SCorentin Chary 
16093e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
16103e230dd2SCorentin Chary {
16113e230dd2SCorentin Chary     uint8_t buf[2];
16123e230dd2SCorentin Chary 
16133e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
16143e230dd2SCorentin Chary     buf[1] = value & 0xFF;
16153e230dd2SCorentin Chary 
16163e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
16173e230dd2SCorentin Chary }
16183e230dd2SCorentin Chary 
16193e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
16203e230dd2SCorentin Chary {
16213e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
16223e230dd2SCorentin Chary }
16233e230dd2SCorentin Chary 
16243e230dd2SCorentin Chary void vnc_flush(VncState *vs)
16253e230dd2SCorentin Chary {
1626bd023f95SCorentin Chary     vnc_lock_output(vs);
1627d5f04223SDaniel P. Berrange     if (vs->ioc != NULL && vs->output.offset) {
1628bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1629bd023f95SCorentin Chary     }
1630bd023f95SCorentin Chary     vnc_unlock_output(vs);
16313e230dd2SCorentin Chary }
16323e230dd2SCorentin Chary 
163371a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
16343e230dd2SCorentin Chary {
16353e230dd2SCorentin Chary     return data[offset];
16363e230dd2SCorentin Chary }
16373e230dd2SCorentin Chary 
163871a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
16393e230dd2SCorentin Chary {
16403e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
16413e230dd2SCorentin Chary }
16423e230dd2SCorentin Chary 
164371a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
16443e230dd2SCorentin Chary {
16453e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
16463e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
16473e230dd2SCorentin Chary }
16483e230dd2SCorentin Chary 
16493e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
16503e230dd2SCorentin Chary {
16513e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
16523e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
16533e230dd2SCorentin Chary }
16543e230dd2SCorentin Chary 
16553e230dd2SCorentin Chary static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
16563e230dd2SCorentin Chary {
16573e230dd2SCorentin Chary }
16583e230dd2SCorentin Chary 
16599e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
16603e230dd2SCorentin Chary {
16613e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
166214768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
16633e230dd2SCorentin Chary 
16643e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1665bd023f95SCorentin Chary         vnc_lock_output(vs);
16663e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
16673e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
16683e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
16693e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1670bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1671bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
16723e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1673bd023f95SCorentin Chary         vnc_unlock_output(vs);
16743e230dd2SCorentin Chary         vnc_flush(vs);
16753e230dd2SCorentin Chary     }
16763e230dd2SCorentin Chary     vs->absolute = absolute;
16773e230dd2SCorentin Chary }
16783e230dd2SCorentin Chary 
16793e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
16803e230dd2SCorentin Chary {
16817fb1cf16SEric Blake     static uint32_t bmap[INPUT_BUTTON__MAX] = {
168214768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
168314768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
168414768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
1685f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1686f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
168714768ebaSGerd Hoffmann     };
168814768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1689bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1690bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
16913e230dd2SCorentin Chary 
169214768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
169314768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
169414768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
169514768ebaSGerd Hoffmann     }
16963e230dd2SCorentin Chary 
16973e230dd2SCorentin Chary     if (vs->absolute) {
16989cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
16999cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
17003e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
170114768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
170214768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
17033e230dd2SCorentin Chary     } else {
170414768ebaSGerd Hoffmann         if (vs->last_x != -1) {
170514768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
170614768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
170714768ebaSGerd Hoffmann         }
17083e230dd2SCorentin Chary         vs->last_x = x;
17093e230dd2SCorentin Chary         vs->last_y = y;
17103e230dd2SCorentin Chary     }
171114768ebaSGerd Hoffmann     qemu_input_event_sync();
17123e230dd2SCorentin Chary }
17133e230dd2SCorentin Chary 
17143e230dd2SCorentin Chary static void reset_keys(VncState *vs)
17153e230dd2SCorentin Chary {
17163e230dd2SCorentin Chary     int i;
17173e230dd2SCorentin Chary     for(i = 0; i < 256; i++) {
17183e230dd2SCorentin Chary         if (vs->modifiers_state[i]) {
17198d447d10SGerd Hoffmann             qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1720c5ce8333SGerd Hoffmann             qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
17213e230dd2SCorentin Chary             vs->modifiers_state[i] = 0;
17223e230dd2SCorentin Chary         }
17233e230dd2SCorentin Chary     }
17243e230dd2SCorentin Chary }
17253e230dd2SCorentin Chary 
17263e230dd2SCorentin Chary static void press_key(VncState *vs, int keysym)
17273e230dd2SCorentin Chary {
17283e230dd2SCorentin Chary     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
17298d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1730c5ce8333SGerd Hoffmann     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
17318d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1732c5ce8333SGerd Hoffmann     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
17333e230dd2SCorentin Chary }
17343e230dd2SCorentin Chary 
1735ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1736ab99e5c1SLei Li {
1737ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1738ab99e5c1SLei Li         return;
1739ab99e5c1SLei Li     }
1740ab99e5c1SLei Li 
1741ab99e5c1SLei Li     vnc_lock_output(vs);
1742ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1743ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1744ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1745ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1746a54f0d2bSPierre Ossman     vnc_write_u8(vs, vs->vd->ledstate);
1747ab99e5c1SLei Li     vnc_unlock_output(vs);
1748ab99e5c1SLei Li     vnc_flush(vs);
1749ab99e5c1SLei Li }
1750ab99e5c1SLei Li 
17513e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
17523e230dd2SCorentin Chary {
1753a54f0d2bSPierre Ossman     VncDisplay *vd = opaque;
1754a54f0d2bSPierre Ossman     VncState *client;
17553e230dd2SCorentin Chary 
175640066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
175740066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
175840066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
175940066175SGerd Hoffmann 
1760a54f0d2bSPierre Ossman     if (ledstate == vd->ledstate) {
1761a54f0d2bSPierre Ossman         return;
176296f3d174SLei Li     }
1763ab99e5c1SLei Li 
1764a54f0d2bSPierre Ossman     vd->ledstate = ledstate;
1765a54f0d2bSPierre Ossman 
1766a54f0d2bSPierre Ossman     QTAILQ_FOREACH(client, &vd->clients, next) {
1767a54f0d2bSPierre Ossman         vnc_led_state_change(client);
1768ab99e5c1SLei Li     }
17693e230dd2SCorentin Chary }
17703e230dd2SCorentin Chary 
17713e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
17723e230dd2SCorentin Chary {
17733e230dd2SCorentin Chary     /* QEMU console switch */
17743e230dd2SCorentin Chary     switch(keycode) {
17753e230dd2SCorentin Chary     case 0x2a:                          /* Left Shift */
17763e230dd2SCorentin Chary     case 0x36:                          /* Right Shift */
17773e230dd2SCorentin Chary     case 0x1d:                          /* Left CTRL */
17783e230dd2SCorentin Chary     case 0x9d:                          /* Right CTRL */
17793e230dd2SCorentin Chary     case 0x38:                          /* Left ALT */
17803e230dd2SCorentin Chary     case 0xb8:                          /* Right ALT */
17813e230dd2SCorentin Chary         if (down)
17823e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 1;
17833e230dd2SCorentin Chary         else
17843e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 0;
17853e230dd2SCorentin Chary         break;
17863e230dd2SCorentin Chary     case 0x02 ... 0x0a: /* '1' to '9' keys */
17871d0d59feSGerd Hoffmann         if (vs->vd->dcl.con == NULL &&
17881d0d59feSGerd Hoffmann             down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
17893e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
17903e230dd2SCorentin Chary             reset_keys(vs);
17913e230dd2SCorentin Chary             console_select(keycode - 0x02);
17923e230dd2SCorentin Chary             return;
17933e230dd2SCorentin Chary         }
17943e230dd2SCorentin Chary         break;
17953e230dd2SCorentin Chary     case 0x3a:                        /* CapsLock */
17963e230dd2SCorentin Chary     case 0x45:                        /* NumLock */
17973e230dd2SCorentin Chary         if (down)
17983e230dd2SCorentin Chary             vs->modifiers_state[keycode] ^= 1;
17993e230dd2SCorentin Chary         break;
18003e230dd2SCorentin Chary     }
18013e230dd2SCorentin Chary 
1802e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1803e7b2aaccSLei Li        state extension.
1804e7b2aaccSLei Li     */
18059892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1806e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18073e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
18083e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
18093e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18103e230dd2SCorentin Chary            toggles numlock away from the VNC window.
18113e230dd2SCorentin Chary         */
18123e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
18133e230dd2SCorentin Chary             if (!vs->modifiers_state[0x45]) {
181440066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
18153e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 1;
18163e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
18173e230dd2SCorentin Chary             }
18183e230dd2SCorentin Chary         } else {
18193e230dd2SCorentin Chary             if (vs->modifiers_state[0x45]) {
182040066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
18213e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 0;
18223e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
18233e230dd2SCorentin Chary             }
18243e230dd2SCorentin Chary         }
18253e230dd2SCorentin Chary     }
18263e230dd2SCorentin Chary 
18279892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1828e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18293e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
18303e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
18313e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18323e230dd2SCorentin Chary            toggles capslock away from the VNC window.
18333e230dd2SCorentin Chary         */
18343e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
18353e230dd2SCorentin Chary         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
18363e230dd2SCorentin Chary         int capslock = !!(vs->modifiers_state[0x3a]);
18373e230dd2SCorentin Chary         if (capslock) {
18383e230dd2SCorentin Chary             if (uppercase == shift) {
183940066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
18403e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 0;
18413e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18423e230dd2SCorentin Chary             }
18433e230dd2SCorentin Chary         } else {
18443e230dd2SCorentin Chary             if (uppercase != shift) {
184540066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
18463e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 1;
18473e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18483e230dd2SCorentin Chary             }
18493e230dd2SCorentin Chary         }
18503e230dd2SCorentin Chary     }
18513e230dd2SCorentin Chary 
185281c0d5a6SGerd Hoffmann     if (qemu_console_is_graphic(NULL)) {
18538d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1854c5ce8333SGerd Hoffmann         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
18553e230dd2SCorentin Chary     } else {
1856e26437c2SGerd Hoffmann         bool numlock = vs->modifiers_state[0x45];
1857e26437c2SGerd Hoffmann         bool control = (vs->modifiers_state[0x1d] ||
1858e26437c2SGerd Hoffmann                         vs->modifiers_state[0x9d]);
18593e230dd2SCorentin Chary         /* QEMU console emulation */
18603e230dd2SCorentin Chary         if (down) {
18613e230dd2SCorentin Chary             switch (keycode) {
18623e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
18633e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
18643e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
18653e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
18663e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
18673e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
18683e230dd2SCorentin Chary                 break;
18693e230dd2SCorentin Chary             case 0xc8:
18703e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_UP);
18713e230dd2SCorentin Chary                 break;
18723e230dd2SCorentin Chary             case 0xd0:
18733e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DOWN);
18743e230dd2SCorentin Chary                 break;
18753e230dd2SCorentin Chary             case 0xcb:
18763e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_LEFT);
18773e230dd2SCorentin Chary                 break;
18783e230dd2SCorentin Chary             case 0xcd:
18793e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_RIGHT);
18803e230dd2SCorentin Chary                 break;
18813e230dd2SCorentin Chary             case 0xd3:
18823e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DELETE);
18833e230dd2SCorentin Chary                 break;
18843e230dd2SCorentin Chary             case 0xc7:
18853e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_HOME);
18863e230dd2SCorentin Chary                 break;
18873e230dd2SCorentin Chary             case 0xcf:
18883e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_END);
18893e230dd2SCorentin Chary                 break;
18903e230dd2SCorentin Chary             case 0xc9:
18913e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEUP);
18923e230dd2SCorentin Chary                 break;
18933e230dd2SCorentin Chary             case 0xd1:
18943e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
18953e230dd2SCorentin Chary                 break;
18963e230dd2SCorentin Chary 
18973e230dd2SCorentin Chary             case 0x47:
18983e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
18993e230dd2SCorentin Chary                 break;
19003e230dd2SCorentin Chary             case 0x48:
19013e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
19023e230dd2SCorentin Chary                 break;
19033e230dd2SCorentin Chary             case 0x49:
19043e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
19053e230dd2SCorentin Chary                 break;
19063e230dd2SCorentin Chary             case 0x4b:
19073e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
19083e230dd2SCorentin Chary                 break;
19093e230dd2SCorentin Chary             case 0x4c:
19103e230dd2SCorentin Chary                 kbd_put_keysym('5');
19113e230dd2SCorentin Chary                 break;
19123e230dd2SCorentin Chary             case 0x4d:
19133e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
19143e230dd2SCorentin Chary                 break;
19153e230dd2SCorentin Chary             case 0x4f:
19163e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
19173e230dd2SCorentin Chary                 break;
19183e230dd2SCorentin Chary             case 0x50:
19193e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
19203e230dd2SCorentin Chary                 break;
19213e230dd2SCorentin Chary             case 0x51:
19223e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
19233e230dd2SCorentin Chary                 break;
19243e230dd2SCorentin Chary             case 0x52:
19253e230dd2SCorentin Chary                 kbd_put_keysym('0');
19263e230dd2SCorentin Chary                 break;
19273e230dd2SCorentin Chary             case 0x53:
19283e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
19293e230dd2SCorentin Chary                 break;
19303e230dd2SCorentin Chary 
19313e230dd2SCorentin Chary             case 0xb5:
19323e230dd2SCorentin Chary                 kbd_put_keysym('/');
19333e230dd2SCorentin Chary                 break;
19343e230dd2SCorentin Chary             case 0x37:
19353e230dd2SCorentin Chary                 kbd_put_keysym('*');
19363e230dd2SCorentin Chary                 break;
19373e230dd2SCorentin Chary             case 0x4a:
19383e230dd2SCorentin Chary                 kbd_put_keysym('-');
19393e230dd2SCorentin Chary                 break;
19403e230dd2SCorentin Chary             case 0x4e:
19413e230dd2SCorentin Chary                 kbd_put_keysym('+');
19423e230dd2SCorentin Chary                 break;
19433e230dd2SCorentin Chary             case 0x9c:
19443e230dd2SCorentin Chary                 kbd_put_keysym('\n');
19453e230dd2SCorentin Chary                 break;
19463e230dd2SCorentin Chary 
19473e230dd2SCorentin Chary             default:
1948e26437c2SGerd Hoffmann                 if (control) {
1949e26437c2SGerd Hoffmann                     kbd_put_keysym(sym & 0x1f);
1950e26437c2SGerd Hoffmann                 } else {
19513e230dd2SCorentin Chary                     kbd_put_keysym(sym);
1952e26437c2SGerd Hoffmann                 }
19533e230dd2SCorentin Chary                 break;
19543e230dd2SCorentin Chary             }
19553e230dd2SCorentin Chary         }
19563e230dd2SCorentin Chary     }
19573e230dd2SCorentin Chary }
19583e230dd2SCorentin Chary 
19597bc9318bSGerd Hoffmann static void vnc_release_modifiers(VncState *vs)
19607bc9318bSGerd Hoffmann {
19617bc9318bSGerd Hoffmann     static const int keycodes[] = {
19627bc9318bSGerd Hoffmann         /* shift, control, alt keys, both left & right */
19637bc9318bSGerd Hoffmann         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
19647bc9318bSGerd Hoffmann     };
19657bc9318bSGerd Hoffmann     int i, keycode;
19667bc9318bSGerd Hoffmann 
196781c0d5a6SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
19687bc9318bSGerd Hoffmann         return;
19697bc9318bSGerd Hoffmann     }
19707bc9318bSGerd Hoffmann     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
19717bc9318bSGerd Hoffmann         keycode = keycodes[i];
19727bc9318bSGerd Hoffmann         if (!vs->modifiers_state[keycode]) {
19737bc9318bSGerd Hoffmann             continue;
19747bc9318bSGerd Hoffmann         }
19758d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1976c5ce8333SGerd Hoffmann         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
19777bc9318bSGerd Hoffmann     }
19787bc9318bSGerd Hoffmann }
19797bc9318bSGerd Hoffmann 
198040066175SGerd Hoffmann static const char *code2name(int keycode)
198140066175SGerd Hoffmann {
1982977c736fSMarkus Armbruster     return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
198340066175SGerd Hoffmann }
198440066175SGerd Hoffmann 
19853e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
19863e230dd2SCorentin Chary {
19873e230dd2SCorentin Chary     int keycode;
19883e230dd2SCorentin Chary     int lsym = sym;
19893e230dd2SCorentin Chary 
199081c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
19913e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
19923e230dd2SCorentin Chary     }
19933e230dd2SCorentin Chary 
19943e230dd2SCorentin Chary     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
199540066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
19963e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
19973e230dd2SCorentin Chary }
19983e230dd2SCorentin Chary 
19993e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
20003e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
20013e230dd2SCorentin Chary {
20023e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
200340066175SGerd Hoffmann     if (keyboard_layout) {
20043e230dd2SCorentin Chary         key_event(vs, down, sym);
200540066175SGerd Hoffmann     } else {
200640066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
20073e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
20083e230dd2SCorentin Chary     }
200940066175SGerd Hoffmann }
20103e230dd2SCorentin Chary 
20113e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
2012bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
20133e230dd2SCorentin Chary {
2014bea60dd7SPeter Lieven     if (incremental) {
2015fef1bbadSDaniel P. Berrange         if (vs->update != VNC_STATE_UPDATE_FORCE) {
2016fef1bbadSDaniel P. Berrange             vs->update = VNC_STATE_UPDATE_INCREMENTAL;
20173e230dd2SCorentin Chary         }
2018fef1bbadSDaniel P. Berrange     } else {
2019fef1bbadSDaniel P. Berrange         vs->update = VNC_STATE_UPDATE_FORCE;
2020f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
20213e230dd2SCorentin Chary     }
2022fef1bbadSDaniel P. Berrange }
20233e230dd2SCorentin Chary 
20243e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
20253e230dd2SCorentin Chary {
2026bd023f95SCorentin Chary     vnc_lock_output(vs);
20273e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20283e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20293e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2030d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2031bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2032bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20333e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
2034bd023f95SCorentin Chary     vnc_unlock_output(vs);
20353e230dd2SCorentin Chary     vnc_flush(vs);
20363e230dd2SCorentin Chary }
20373e230dd2SCorentin Chary 
20383e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
20393e230dd2SCorentin Chary {
2040bd023f95SCorentin Chary     vnc_lock_output(vs);
20413e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20423e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20433e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2044d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2045bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2046bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20473e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2048bd023f95SCorentin Chary     vnc_unlock_output(vs);
20493e230dd2SCorentin Chary     vnc_flush(vs);
20503e230dd2SCorentin Chary }
20513e230dd2SCorentin Chary 
20523e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
20533e230dd2SCorentin Chary {
20543e230dd2SCorentin Chary     int i;
20553e230dd2SCorentin Chary     unsigned int enc = 0;
20563e230dd2SCorentin Chary 
20573e230dd2SCorentin Chary     vs->features = 0;
20583e230dd2SCorentin Chary     vs->vnc_encoding = 0;
2059d1af0e05SCorentin Chary     vs->tight.compression = 9;
2060d1af0e05SCorentin Chary     vs->tight.quality = -1; /* Lossless by default */
20613e230dd2SCorentin Chary     vs->absolute = -1;
20623e230dd2SCorentin Chary 
20633e230dd2SCorentin Chary     /*
20643e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2065e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
20663e230dd2SCorentin Chary      * will be set at the end of the loop.
20673e230dd2SCorentin Chary      */
20683e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
20693e230dd2SCorentin Chary         enc = encodings[i];
20703e230dd2SCorentin Chary         switch (enc) {
20713e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
20723e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20733e230dd2SCorentin Chary             break;
20743e230dd2SCorentin Chary         case VNC_ENCODING_COPYRECT:
20753e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_COPYRECT_MASK;
20763e230dd2SCorentin Chary             break;
20773e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
20783e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
20793e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20803e230dd2SCorentin Chary             break;
20813e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
20823e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
20833e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20843e230dd2SCorentin Chary             break;
2085fe3e7f2dSJoel Martin #ifdef CONFIG_VNC_PNG
2086efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2087efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2088efe556adSCorentin Chary             vs->vnc_encoding = enc;
2089efe556adSCorentin Chary             break;
2090fe3e7f2dSJoel Martin #endif
20913e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
20923e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_ZLIB_MASK;
20933e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20943e230dd2SCorentin Chary             break;
2095148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2096148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2097148954faSCorentin Chary             vs->vnc_encoding = enc;
2098148954faSCorentin Chary             break;
2099148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2100148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2101148954faSCorentin Chary             vs->vnc_encoding = enc;
2102148954faSCorentin Chary             break;
21033e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
21043e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
21053e230dd2SCorentin Chary             break;
21063e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
21073e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
21083e230dd2SCorentin Chary             break;
21093e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
21103e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
211191ec41dcSFrediano Ziglio             if (vs->vd->cursor) {
211291ec41dcSFrediano Ziglio                 vnc_cursor_define(vs);
211391ec41dcSFrediano Ziglio             }
21143e230dd2SCorentin Chary             break;
21153e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
21163e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
21173e230dd2SCorentin Chary             break;
21183e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
21193e230dd2SCorentin Chary             send_ext_audio_ack(vs);
21203e230dd2SCorentin Chary             break;
21213e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
21223e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
21233e230dd2SCorentin Chary             break;
2124ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2125ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2126ab99e5c1SLei Li             break;
21273e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2128d1af0e05SCorentin Chary             vs->tight.compression = (enc & 0x0F);
21293e230dd2SCorentin Chary             break;
21303e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2131b31f519eSCorentin Chary             if (vs->vd->lossy) {
2132d1af0e05SCorentin Chary                 vs->tight.quality = (enc & 0x0F);
2133b31f519eSCorentin Chary             }
21343e230dd2SCorentin Chary             break;
21353e230dd2SCorentin Chary         default:
21363e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
21373e230dd2SCorentin Chary             break;
21383e230dd2SCorentin Chary         }
21393e230dd2SCorentin Chary     }
21403e230dd2SCorentin Chary     vnc_desktop_resize(vs);
21419e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2142ab99e5c1SLei Li     vnc_led_state_change(vs);
21433e230dd2SCorentin Chary }
21443e230dd2SCorentin Chary 
21453e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
21463e230dd2SCorentin Chary {
21479f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
21489f64916dSGerd Hoffmann 
21499f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
21503e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
21513e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
21523e230dd2SCorentin Chary     } else {
21533e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
21543e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
21553e230dd2SCorentin Chary     }
21563e230dd2SCorentin Chary }
21573e230dd2SCorentin Chary 
21580c426e45SAlexander Graf static void send_color_map(VncState *vs)
21590c426e45SAlexander Graf {
21600c426e45SAlexander Graf     int i;
21610c426e45SAlexander Graf 
21620c426e45SAlexander Graf     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
21630c426e45SAlexander Graf     vnc_write_u8(vs,  0);    /* padding     */
21640c426e45SAlexander Graf     vnc_write_u16(vs, 0);    /* first color */
21650c426e45SAlexander Graf     vnc_write_u16(vs, 256);  /* # of colors */
21660c426e45SAlexander Graf 
21670c426e45SAlexander Graf     for (i = 0; i < 256; i++) {
21680c426e45SAlexander Graf         PixelFormat *pf = &vs->client_pf;
21690c426e45SAlexander Graf 
21700c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
21710c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
21720c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
21730c426e45SAlexander Graf     }
21740c426e45SAlexander Graf }
21750c426e45SAlexander Graf 
2176ec9fb41aSGerd Hoffmann static void set_pixel_format(VncState *vs, int bits_per_pixel,
21773e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
21783e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
21793e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
21803e230dd2SCorentin Chary {
21813e230dd2SCorentin Chary     if (!true_color_flag) {
21820c426e45SAlexander Graf         /* Expose a reasonable default 256 color map */
21830c426e45SAlexander Graf         bits_per_pixel = 8;
21840c426e45SAlexander Graf         red_max = 7;
21850c426e45SAlexander Graf         green_max = 7;
21860c426e45SAlexander Graf         blue_max = 3;
21870c426e45SAlexander Graf         red_shift = 0;
21880c426e45SAlexander Graf         green_shift = 3;
21890c426e45SAlexander Graf         blue_shift = 6;
21903e230dd2SCorentin Chary     }
21913e230dd2SCorentin Chary 
2192e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2193e6908bfeSPetr Matousek     case 8:
2194e6908bfeSPetr Matousek     case 16:
2195e6908bfeSPetr Matousek     case 32:
2196e6908bfeSPetr Matousek         break;
2197e6908bfeSPetr Matousek     default:
2198e6908bfeSPetr Matousek         vnc_client_error(vs);
2199e6908bfeSPetr Matousek         return;
2200e6908bfeSPetr Matousek     }
2201e6908bfeSPetr Matousek 
22024c65fed8SPrasad J Pandit     vs->client_pf.rmax = red_max ? red_max : 0xFF;
22037c9209e7SCédric Le Goater     vs->client_pf.rbits = ctpopl(red_max);
22049f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
22059f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
22064c65fed8SPrasad J Pandit     vs->client_pf.gmax = green_max ? green_max : 0xFF;
22077c9209e7SCédric Le Goater     vs->client_pf.gbits = ctpopl(green_max);
22089f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
22099f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
22104c65fed8SPrasad J Pandit     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
22117c9209e7SCédric Le Goater     vs->client_pf.bbits = ctpopl(blue_max);
22129f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
22139f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
22149f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
22159f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
22169f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
22179f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
22183e230dd2SCorentin Chary 
22190c426e45SAlexander Graf     if (!true_color_flag) {
22200c426e45SAlexander Graf         send_color_map(vs);
22210c426e45SAlexander Graf     }
22220c426e45SAlexander Graf 
22233e230dd2SCorentin Chary     set_pixel_conversion(vs);
22243e230dd2SCorentin Chary 
22251d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
22261d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
22273e230dd2SCorentin Chary }
22283e230dd2SCorentin Chary 
22293e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
22303e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
22313e230dd2SCorentin Chary 
22329f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
22339f64916dSGerd Hoffmann 
22349f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
22359f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
22363e230dd2SCorentin Chary 
22373e230dd2SCorentin Chary #ifdef HOST_WORDS_BIGENDIAN
22383e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
22393e230dd2SCorentin Chary #else
22403e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
22413e230dd2SCorentin Chary #endif
22423e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
22439f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
22449f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
22459f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
22469f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
22479f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
22489f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
22499f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
22503e230dd2SCorentin Chary 
22513e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
22523e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
22533e230dd2SCorentin Chary }
22543e230dd2SCorentin Chary 
22553e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
22563e230dd2SCorentin Chary {
22573e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
22583e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2259bd023f95SCorentin Chary         vnc_lock_output(vs);
22603e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
22613e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
22623e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2263d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
2264bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
2265bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
2266d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
22673e230dd2SCorentin Chary         pixel_format_message(vs);
2268bd023f95SCorentin Chary         vnc_unlock_output(vs);
22693e230dd2SCorentin Chary         vnc_flush(vs);
22703e230dd2SCorentin Chary     } else {
22713e230dd2SCorentin Chary         set_pixel_conversion(vs);
22723e230dd2SCorentin Chary     }
22733e230dd2SCorentin Chary }
22743e230dd2SCorentin Chary 
22753e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
22763e230dd2SCorentin Chary {
22773e230dd2SCorentin Chary     int i;
22783e230dd2SCorentin Chary     uint16_t limit;
22793e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
22803e230dd2SCorentin Chary 
22813e230dd2SCorentin Chary     if (data[0] > 3) {
22820f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
22833e230dd2SCorentin Chary     }
22843e230dd2SCorentin Chary 
22853e230dd2SCorentin Chary     switch (data[0]) {
22863e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
22873e230dd2SCorentin Chary         if (len == 1)
22883e230dd2SCorentin Chary             return 20;
22893e230dd2SCorentin Chary 
2290ec9fb41aSGerd Hoffmann         set_pixel_format(vs, read_u8(data, 4),
22913e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
22923e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
22933e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
22943e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
22953e230dd2SCorentin Chary         break;
22963e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
22973e230dd2SCorentin Chary         if (len == 1)
22983e230dd2SCorentin Chary             return 4;
22993e230dd2SCorentin Chary 
23003e230dd2SCorentin Chary         if (len == 4) {
23013e230dd2SCorentin Chary             limit = read_u16(data, 2);
23023e230dd2SCorentin Chary             if (limit > 0)
23033e230dd2SCorentin Chary                 return 4 + (limit * 4);
23043e230dd2SCorentin Chary         } else
23053e230dd2SCorentin Chary             limit = read_u16(data, 2);
23063e230dd2SCorentin Chary 
23073e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
23083e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
23093e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
23103e230dd2SCorentin Chary         }
23113e230dd2SCorentin Chary 
23123e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
23133e230dd2SCorentin Chary         break;
23143e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
23153e230dd2SCorentin Chary         if (len == 1)
23163e230dd2SCorentin Chary             return 10;
23173e230dd2SCorentin Chary 
23183e230dd2SCorentin Chary         framebuffer_update_request(vs,
23193e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
23203e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
23213e230dd2SCorentin Chary         break;
23223e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
23233e230dd2SCorentin Chary         if (len == 1)
23243e230dd2SCorentin Chary             return 8;
23253e230dd2SCorentin Chary 
23263e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
23273e230dd2SCorentin Chary         break;
23283e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
23293e230dd2SCorentin Chary         if (len == 1)
23303e230dd2SCorentin Chary             return 6;
23313e230dd2SCorentin Chary 
23323e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
23333e230dd2SCorentin Chary         break;
23343e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2335f9a70e79SPeter Lieven         if (len == 1) {
23363e230dd2SCorentin Chary             return 8;
2337f9a70e79SPeter Lieven         }
23383e230dd2SCorentin Chary         if (len == 8) {
23393e230dd2SCorentin Chary             uint32_t dlen = read_u32(data, 4);
2340f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2341f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2342f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2343f9a70e79SPeter Lieven                 vnc_client_error(vs);
2344f9a70e79SPeter Lieven                 break;
2345f9a70e79SPeter Lieven             }
2346f9a70e79SPeter Lieven             if (dlen > 0) {
23473e230dd2SCorentin Chary                 return 8 + dlen;
23483e230dd2SCorentin Chary             }
2349f9a70e79SPeter Lieven         }
23503e230dd2SCorentin Chary 
23513e230dd2SCorentin Chary         client_cut_text(vs, read_u32(data, 4), data + 8);
23523e230dd2SCorentin Chary         break;
23533e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
23543e230dd2SCorentin Chary         if (len == 1)
23553e230dd2SCorentin Chary             return 2;
23563e230dd2SCorentin Chary 
23573e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
23583e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
23593e230dd2SCorentin Chary             if (len == 2)
23603e230dd2SCorentin Chary                 return 12;
23613e230dd2SCorentin Chary 
23623e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
23633e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
23643e230dd2SCorentin Chary             break;
23653e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
23663e230dd2SCorentin Chary             if (len == 2)
23673e230dd2SCorentin Chary                 return 4;
23683e230dd2SCorentin Chary 
23693e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
23703e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
23713e230dd2SCorentin Chary                 audio_add(vs);
23723e230dd2SCorentin Chary                 break;
23733e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
23743e230dd2SCorentin Chary                 audio_del(vs);
23753e230dd2SCorentin Chary                 break;
23763e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
23773e230dd2SCorentin Chary                 if (len == 4)
23783e230dd2SCorentin Chary                     return 10;
23793e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
23803e230dd2SCorentin Chary                 case 0: vs->as.fmt = AUD_FMT_U8; break;
23813e230dd2SCorentin Chary                 case 1: vs->as.fmt = AUD_FMT_S8; break;
23823e230dd2SCorentin Chary                 case 2: vs->as.fmt = AUD_FMT_U16; break;
23833e230dd2SCorentin Chary                 case 3: vs->as.fmt = AUD_FMT_S16; break;
23843e230dd2SCorentin Chary                 case 4: vs->as.fmt = AUD_FMT_U32; break;
23853e230dd2SCorentin Chary                 case 5: vs->as.fmt = AUD_FMT_S32; break;
23863e230dd2SCorentin Chary                 default:
2387153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
23883e230dd2SCorentin Chary                     vnc_client_error(vs);
23893e230dd2SCorentin Chary                     break;
23903e230dd2SCorentin Chary                 }
23913e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
23923e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2393090fdc83SMarc-André Lureau                     VNC_DEBUG("Invalid audio channel count %d\n",
23943e230dd2SCorentin Chary                               read_u8(data, 5));
23953e230dd2SCorentin Chary                     vnc_client_error(vs);
23963e230dd2SCorentin Chary                     break;
23973e230dd2SCorentin Chary                 }
23983e230dd2SCorentin Chary                 vs->as.freq = read_u32(data, 6);
23993e230dd2SCorentin Chary                 break;
24003e230dd2SCorentin Chary             default:
2401153130cdSDaniel P. Berrange                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
24023e230dd2SCorentin Chary                 vnc_client_error(vs);
24033e230dd2SCorentin Chary                 break;
24043e230dd2SCorentin Chary             }
24053e230dd2SCorentin Chary             break;
24063e230dd2SCorentin Chary 
24073e230dd2SCorentin Chary         default:
2408153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
24093e230dd2SCorentin Chary             vnc_client_error(vs);
24103e230dd2SCorentin Chary             break;
24113e230dd2SCorentin Chary         }
24123e230dd2SCorentin Chary         break;
24133e230dd2SCorentin Chary     default:
2414153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
24153e230dd2SCorentin Chary         vnc_client_error(vs);
24163e230dd2SCorentin Chary         break;
24173e230dd2SCorentin Chary     }
24183e230dd2SCorentin Chary 
2419e2b72cb6SDaniel P. Berrange     vnc_update_throttle_offset(vs);
24203e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
24213e230dd2SCorentin Chary     return 0;
24223e230dd2SCorentin Chary }
24233e230dd2SCorentin Chary 
24243e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
24253e230dd2SCorentin Chary {
24263e230dd2SCorentin Chary     char buf[1024];
24278cf36489SGerd Hoffmann     VncShareMode mode;
24283e230dd2SCorentin Chary     int size;
24293e230dd2SCorentin Chary 
24308cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
24318cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
24328cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
24338cf36489SGerd Hoffmann         /*
24348cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
24358cf36489SGerd Hoffmann          *
24368cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
24378cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
24388cf36489SGerd Hoffmann          * reasons.
24398cf36489SGerd Hoffmann          */
24408cf36489SGerd Hoffmann         break;
24418cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
24428cf36489SGerd Hoffmann         /*
24438cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
24448cf36489SGerd Hoffmann          *
24458cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
24468cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
24478cf36489SGerd Hoffmann          * as no exclusive connection exists.
24488cf36489SGerd Hoffmann          *
24498cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
24508cf36489SGerd Hoffmann          */
24518cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24528cf36489SGerd Hoffmann             VncState *client;
24538cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
24548cf36489SGerd Hoffmann                 if (vs == client) {
24558cf36489SGerd Hoffmann                     continue;
24568cf36489SGerd Hoffmann                 }
24578cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
24588cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
24598cf36489SGerd Hoffmann                     continue;
24608cf36489SGerd Hoffmann                 }
24618cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
24628cf36489SGerd Hoffmann             }
24638cf36489SGerd Hoffmann         }
24648cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
24658cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
24668cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
24678cf36489SGerd Hoffmann                 return 0;
24688cf36489SGerd Hoffmann             }
24698cf36489SGerd Hoffmann         }
24708cf36489SGerd Hoffmann         break;
24718cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
24728cf36489SGerd Hoffmann         /*
24738cf36489SGerd Hoffmann          * Policy: Shared connects only.
24748cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
24758cf36489SGerd Hoffmann          *
24768cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
24778cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
24788cf36489SGerd Hoffmann          * client disconnect everybody else.
24798cf36489SGerd Hoffmann          */
24808cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24818cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
24828cf36489SGerd Hoffmann             return 0;
24838cf36489SGerd Hoffmann         }
24848cf36489SGerd Hoffmann         break;
24858cf36489SGerd Hoffmann     }
24868cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
24878cf36489SGerd Hoffmann 
2488e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2489e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2490e5f34cddSGerd Hoffmann         return 0;
2491e5f34cddSGerd Hoffmann     }
2492e5f34cddSGerd Hoffmann 
2493bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2494bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
24953e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
24963e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
24973e230dd2SCorentin Chary 
24983e230dd2SCorentin Chary     pixel_format_message(vs);
24993e230dd2SCorentin Chary 
250097efe4f9SThomas Huth     if (qemu_name) {
25013e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
250297efe4f9SThomas Huth         if (size > sizeof(buf)) {
250397efe4f9SThomas Huth             size = sizeof(buf);
250497efe4f9SThomas Huth         }
250597efe4f9SThomas Huth     } else {
25063e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
250797efe4f9SThomas Huth     }
25083e230dd2SCorentin Chary 
25093e230dd2SCorentin Chary     vnc_write_u32(vs, size);
25103e230dd2SCorentin Chary     vnc_write(vs, buf, size);
25113e230dd2SCorentin Chary     vnc_flush(vs);
25123e230dd2SCorentin Chary 
25133e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2514fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
25153e230dd2SCorentin Chary 
25163e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
25173e230dd2SCorentin Chary 
25183e230dd2SCorentin Chary     return 0;
25193e230dd2SCorentin Chary }
25203e230dd2SCorentin Chary 
25213e230dd2SCorentin Chary void start_client_init(VncState *vs)
25223e230dd2SCorentin Chary {
25233e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
25243e230dd2SCorentin Chary }
25253e230dd2SCorentin Chary 
25263e230dd2SCorentin Chary static void make_challenge(VncState *vs)
25273e230dd2SCorentin Chary {
25283e230dd2SCorentin Chary     int i;
25293e230dd2SCorentin Chary 
25303e230dd2SCorentin Chary     srand(time(NULL)+getpid()+getpid()*987654+rand());
25313e230dd2SCorentin Chary 
25323e230dd2SCorentin Chary     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
25333e230dd2SCorentin Chary         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
25343e230dd2SCorentin Chary }
25353e230dd2SCorentin Chary 
25363e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
25373e230dd2SCorentin Chary {
25383e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2539800567a6SDaniel P. Berrange     size_t i, pwlen;
25403e230dd2SCorentin Chary     unsigned char key[8];
25413c9405a0SGerd Hoffmann     time_t now = time(NULL);
254260928458SGonglei     QCryptoCipher *cipher = NULL;
2543800567a6SDaniel P. Berrange     Error *err = NULL;
25443e230dd2SCorentin Chary 
25451cd20f8bSAnthony Liguori     if (!vs->vd->password) {
25467364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
25476bffdf0fSGerd Hoffmann         goto reject;
25483e230dd2SCorentin Chary     }
25493c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
25507364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
25513c9405a0SGerd Hoffmann         goto reject;
25523c9405a0SGerd Hoffmann     }
25533e230dd2SCorentin Chary 
25543e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
25553e230dd2SCorentin Chary 
25563e230dd2SCorentin Chary     /* Calculate the expected challenge response */
25573e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
25583e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
25593e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2560800567a6SDaniel P. Berrange 
2561800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
2562800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_DES_RFB,
2563800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2564800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2565800567a6SDaniel P. Berrange         &err);
2566800567a6SDaniel P. Berrange     if (!cipher) {
25677364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2568800567a6SDaniel P. Berrange                             error_get_pretty(err));
2569800567a6SDaniel P. Berrange         error_free(err);
2570800567a6SDaniel P. Berrange         goto reject;
2571800567a6SDaniel P. Berrange     }
2572800567a6SDaniel P. Berrange 
2573a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2574800567a6SDaniel P. Berrange                                vs->challenge,
2575800567a6SDaniel P. Berrange                                response,
2576800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2577800567a6SDaniel P. Berrange                                &err) < 0) {
25787364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2579800567a6SDaniel P. Berrange                             error_get_pretty(err));
2580800567a6SDaniel P. Berrange         error_free(err);
2581800567a6SDaniel P. Berrange         goto reject;
2582800567a6SDaniel P. Berrange     }
25833e230dd2SCorentin Chary 
25843e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
25853e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
25867364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
25876bffdf0fSGerd Hoffmann         goto reject;
25886bffdf0fSGerd Hoffmann     } else {
25897364dbdaSDaniel P. Berrange         trace_vnc_auth_pass(vs, vs->auth);
25906bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
25916bffdf0fSGerd Hoffmann         vnc_flush(vs);
25926bffdf0fSGerd Hoffmann 
25936bffdf0fSGerd Hoffmann         start_client_init(vs);
25946bffdf0fSGerd Hoffmann     }
259560928458SGonglei 
259660928458SGonglei     qcrypto_cipher_free(cipher);
25976bffdf0fSGerd Hoffmann     return 0;
25986bffdf0fSGerd Hoffmann 
25996bffdf0fSGerd Hoffmann reject:
26003e230dd2SCorentin Chary     vnc_write_u32(vs, 1); /* Reject auth */
26013e230dd2SCorentin Chary     if (vs->minor >= 8) {
26023e230dd2SCorentin Chary         static const char err[] = "Authentication failed";
26033e230dd2SCorentin Chary         vnc_write_u32(vs, sizeof(err));
26043e230dd2SCorentin Chary         vnc_write(vs, err, sizeof(err));
26053e230dd2SCorentin Chary     }
26063e230dd2SCorentin Chary     vnc_flush(vs);
26073e230dd2SCorentin Chary     vnc_client_error(vs);
260860928458SGonglei     qcrypto_cipher_free(cipher);
26093e230dd2SCorentin Chary     return 0;
26103e230dd2SCorentin Chary }
26113e230dd2SCorentin Chary 
26123e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
26133e230dd2SCorentin Chary {
26143e230dd2SCorentin Chary     make_challenge(vs);
26153e230dd2SCorentin Chary     /* Send client a 'random' challenge */
26163e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
26173e230dd2SCorentin Chary     vnc_flush(vs);
26183e230dd2SCorentin Chary 
26193e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
26203e230dd2SCorentin Chary }
26213e230dd2SCorentin Chary 
26223e230dd2SCorentin Chary 
26233e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
26243e230dd2SCorentin Chary {
26253e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
26263e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
26277e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
26287364dbdaSDaniel P. Berrange        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
26293e230dd2SCorentin Chary        vnc_write_u32(vs, 1);
26303e230dd2SCorentin Chary        if (vs->minor >= 8) {
26313e230dd2SCorentin Chary            static const char err[] = "Authentication failed";
26323e230dd2SCorentin Chary            vnc_write_u32(vs, sizeof(err));
26333e230dd2SCorentin Chary            vnc_write(vs, err, sizeof(err));
26343e230dd2SCorentin Chary        }
26353e230dd2SCorentin Chary        vnc_client_error(vs);
26363e230dd2SCorentin Chary     } else { /* Accept requested auth */
26377364dbdaSDaniel P. Berrange        trace_vnc_auth_start(vs, vs->auth);
26387e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
26393e230dd2SCorentin Chary        case VNC_AUTH_NONE:
26403e230dd2SCorentin Chary            if (vs->minor >= 8) {
26413e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
26423e230dd2SCorentin Chary                vnc_flush(vs);
26433e230dd2SCorentin Chary            }
26447364dbdaSDaniel P. Berrange            trace_vnc_auth_pass(vs, vs->auth);
26453e230dd2SCorentin Chary            start_client_init(vs);
26463e230dd2SCorentin Chary            break;
26473e230dd2SCorentin Chary 
26483e230dd2SCorentin Chary        case VNC_AUTH_VNC:
26493e230dd2SCorentin Chary            start_auth_vnc(vs);
26503e230dd2SCorentin Chary            break;
26513e230dd2SCorentin Chary 
26523e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
26533e230dd2SCorentin Chary            start_auth_vencrypt(vs);
26543e230dd2SCorentin Chary            break;
26553e230dd2SCorentin Chary 
26563e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
26573e230dd2SCorentin Chary        case VNC_AUTH_SASL:
26583e230dd2SCorentin Chary            start_auth_sasl(vs);
26593e230dd2SCorentin Chary            break;
26603e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
26613e230dd2SCorentin Chary 
26623e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
26637364dbdaSDaniel P. Berrange            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
26643e230dd2SCorentin Chary            vnc_write_u8(vs, 1);
26653e230dd2SCorentin Chary            if (vs->minor >= 8) {
26663e230dd2SCorentin Chary                static const char err[] = "Authentication failed";
26673e230dd2SCorentin Chary                vnc_write_u32(vs, sizeof(err));
26683e230dd2SCorentin Chary                vnc_write(vs, err, sizeof(err));
26693e230dd2SCorentin Chary            }
26703e230dd2SCorentin Chary            vnc_client_error(vs);
26713e230dd2SCorentin Chary        }
26723e230dd2SCorentin Chary     }
26733e230dd2SCorentin Chary     return 0;
26743e230dd2SCorentin Chary }
26753e230dd2SCorentin Chary 
26763e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
26773e230dd2SCorentin Chary {
26783e230dd2SCorentin Chary     char local[13];
26793e230dd2SCorentin Chary 
26803e230dd2SCorentin Chary     memcpy(local, version, 12);
26813e230dd2SCorentin Chary     local[12] = 0;
26823e230dd2SCorentin Chary 
26833e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
26843e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
26853e230dd2SCorentin Chary         vnc_client_error(vs);
26863e230dd2SCorentin Chary         return 0;
26873e230dd2SCorentin Chary     }
26883e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
26893e230dd2SCorentin Chary     if (vs->major != 3 ||
26903e230dd2SCorentin Chary         (vs->minor != 3 &&
26913e230dd2SCorentin Chary          vs->minor != 4 &&
26923e230dd2SCorentin Chary          vs->minor != 5 &&
26933e230dd2SCorentin Chary          vs->minor != 7 &&
26943e230dd2SCorentin Chary          vs->minor != 8)) {
26953e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
26963e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
26973e230dd2SCorentin Chary         vnc_flush(vs);
26983e230dd2SCorentin Chary         vnc_client_error(vs);
26993e230dd2SCorentin Chary         return 0;
27003e230dd2SCorentin Chary     }
27013e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
27023e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
27033e230dd2SCorentin Chary      */
27043e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
27053e230dd2SCorentin Chary         vs->minor = 3;
27063e230dd2SCorentin Chary 
27073e230dd2SCorentin Chary     if (vs->minor == 3) {
27087364dbdaSDaniel P. Berrange         trace_vnc_auth_start(vs, vs->auth);
27097e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
27107e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
27113e230dd2SCorentin Chary             vnc_flush(vs);
27127364dbdaSDaniel P. Berrange             trace_vnc_auth_pass(vs, vs->auth);
27133e230dd2SCorentin Chary             start_client_init(vs);
27147e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
27153e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
27167e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
27173e230dd2SCorentin Chary             vnc_flush(vs);
27183e230dd2SCorentin Chary             start_auth_vnc(vs);
27193e230dd2SCorentin Chary        } else {
27207364dbdaSDaniel P. Berrange             trace_vnc_auth_fail(vs, vs->auth,
27217364dbdaSDaniel P. Berrange                                 "Unsupported auth method for v3.3", "");
27223e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
27233e230dd2SCorentin Chary             vnc_flush(vs);
27243e230dd2SCorentin Chary             vnc_client_error(vs);
27253e230dd2SCorentin Chary        }
27263e230dd2SCorentin Chary     } else {
27273e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
27287e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
27293e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
27303e230dd2SCorentin Chary         vnc_flush(vs);
27313e230dd2SCorentin Chary     }
27323e230dd2SCorentin Chary 
27333e230dd2SCorentin Chary     return 0;
27343e230dd2SCorentin Chary }
27353e230dd2SCorentin Chary 
2736999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2737999342a0SCorentin Chary {
2738999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2739999342a0SCorentin Chary 
2740999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2741999342a0SCorentin Chary }
2742999342a0SCorentin Chary 
27437d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
27447d964c9dSCorentin Chary {
27457d964c9dSCorentin Chary     int i, j;
27467d964c9dSCorentin Chary 
27477d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
27487d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
27497d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
27507d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
27517d964c9dSCorentin Chary 
2752207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2753207f328aSCorentin Chary         for (i = x; i <= w; i++) {
27547d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
27557d964c9dSCorentin Chary         }
27567d964c9dSCorentin Chary     }
27577d964c9dSCorentin Chary }
27587d964c9dSCorentin Chary 
27597d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
27607d964c9dSCorentin Chary {
27617d964c9dSCorentin Chary     VncState *vs;
27627d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
27637d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
27647d964c9dSCorentin Chary     int has_dirty = 0;
27657d964c9dSCorentin Chary 
27665a3804dbSMarc-André Lureau     y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
27675a3804dbSMarc-André Lureau     x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
27687d964c9dSCorentin Chary 
27697d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2770bc2429b9SCorentin Chary         int j;
27717d964c9dSCorentin Chary 
27727d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
27737d964c9dSCorentin Chary         if (vs->output.offset) {
27747d964c9dSCorentin Chary             continue;
27757d964c9dSCorentin Chary         }
27767d964c9dSCorentin Chary 
27777d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
27787d964c9dSCorentin Chary             continue;
27797d964c9dSCorentin Chary         }
2780207f328aSCorentin Chary 
27817d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
27827d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2783b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2784b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2785b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
27867d964c9dSCorentin Chary         }
27877d964c9dSCorentin Chary         has_dirty++;
27887d964c9dSCorentin Chary     }
2789207f328aSCorentin Chary 
27907d964c9dSCorentin Chary     return has_dirty;
27917d964c9dSCorentin Chary }
27927d964c9dSCorentin Chary 
27937d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2794999342a0SCorentin Chary {
2795eebe0b79SGerd Hoffmann     int width = MIN(pixman_image_get_width(vd->guest.fb),
2796eebe0b79SGerd Hoffmann                     pixman_image_get_width(vd->server));
2797eebe0b79SGerd Hoffmann     int height = MIN(pixman_image_get_height(vd->guest.fb),
2798eebe0b79SGerd Hoffmann                      pixman_image_get_height(vd->server));
2799999342a0SCorentin Chary     int x, y;
2800999342a0SCorentin Chary     struct timeval res;
28017d964c9dSCorentin Chary     int has_dirty = 0;
2802999342a0SCorentin Chary 
28039f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
28049f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2805999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2806999342a0SCorentin Chary 
2807999342a0SCorentin Chary             rect->updated = false;
2808999342a0SCorentin Chary         }
2809999342a0SCorentin Chary     }
2810999342a0SCorentin Chary 
2811ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2812999342a0SCorentin Chary 
2813999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
28147d964c9dSCorentin Chary         return has_dirty;
2815999342a0SCorentin Chary     }
2816999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
2817999342a0SCorentin Chary 
28189f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
28199f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2820999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2821999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
2822999342a0SCorentin Chary             struct timeval min, max;
2823999342a0SCorentin Chary 
2824999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
2825999342a0SCorentin Chary                 continue ;
2826999342a0SCorentin Chary             }
2827999342a0SCorentin Chary 
2828999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2829ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
2830999342a0SCorentin Chary 
2831999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2832999342a0SCorentin Chary                 rect->freq = 0;
28337d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2834999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
2835999342a0SCorentin Chary                 continue ;
2836999342a0SCorentin Chary             }
2837999342a0SCorentin Chary 
2838999342a0SCorentin Chary             min = rect->times[rect->idx];
2839999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2840ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
2841999342a0SCorentin Chary 
2842999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2843999342a0SCorentin Chary             rect->freq /= count;
2844999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
2845999342a0SCorentin Chary         }
2846999342a0SCorentin Chary     }
28477d964c9dSCorentin Chary     return has_dirty;
2848999342a0SCorentin Chary }
2849999342a0SCorentin Chary 
2850999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2851999342a0SCorentin Chary {
2852999342a0SCorentin Chary     int i, j;
2853999342a0SCorentin Chary     double total = 0;
2854999342a0SCorentin Chary     int num = 0;
2855999342a0SCorentin Chary 
28565a3804dbSMarc-André Lureau     x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
28575a3804dbSMarc-André Lureau     y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2858999342a0SCorentin Chary 
2859999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2860999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2861999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
2862999342a0SCorentin Chary             num++;
2863999342a0SCorentin Chary         }
2864999342a0SCorentin Chary     }
2865999342a0SCorentin Chary 
2866999342a0SCorentin Chary     if (num) {
2867999342a0SCorentin Chary         return total / num;
2868999342a0SCorentin Chary     } else {
2869999342a0SCorentin Chary         return 0;
2870999342a0SCorentin Chary     }
2871999342a0SCorentin Chary }
2872999342a0SCorentin Chary 
2873999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2874999342a0SCorentin Chary {
2875999342a0SCorentin Chary     VncRectStat *rect;
2876999342a0SCorentin Chary 
2877999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
2878999342a0SCorentin Chary     if (rect->updated) {
2879999342a0SCorentin Chary         return ;
2880999342a0SCorentin Chary     }
2881999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
2882999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2883999342a0SCorentin Chary     rect->updated = true;
2884999342a0SCorentin Chary }
2885999342a0SCorentin Chary 
28863e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
28873e230dd2SCorentin Chary {
2888bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
2889bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
2890bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
2891bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
2892eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
289312b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
28943e230dd2SCorentin Chary     VncState *vs;
28953e230dd2SCorentin Chary     int has_dirty = 0;
28969f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
28973e230dd2SCorentin Chary 
289880e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
2899999342a0SCorentin Chary 
290080e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
2901999342a0SCorentin Chary         gettimeofday(&tv, NULL);
29027d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
290380e0c8c3SCorentin Chary     }
2904999342a0SCorentin Chary 
29053e230dd2SCorentin Chary     /*
29063e230dd2SCorentin Chary      * Walk through the guest dirty map.
29073e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
29083e230dd2SCorentin Chary      * Update server dirty map.
29093e230dd2SCorentin Chary      */
2910bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2911eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
2912eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
2913bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2914bea60dd7SPeter Lieven                     server_stride);
29159f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
29169f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
29179f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
291812b316d4SPeter Lieven     } else {
2919eb8934b0SGerd Hoffmann         int guest_bpp =
2920eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
292112b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
292212b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
2923659c90eeSMarc-André Lureau         guest_ll = pixman_image_get_width(vd->guest.fb) * (DIV_ROUND_UP(guest_bpp, 8));
29249f64916dSGerd Hoffmann     }
2925eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
292612b316d4SPeter Lieven 
292712b316d4SPeter Lieven     for (;;) {
29283e230dd2SCorentin Chary         int x;
292912b316d4SPeter Lieven         uint8_t *guest_ptr, *server_ptr;
293012b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
293112b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(&vd->guest),
293212b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(&vd->guest));
293312b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
293412b316d4SPeter Lieven             /* no more dirty bits */
293512b316d4SPeter Lieven             break;
293612b316d4SPeter Lieven         }
293712b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
293812b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
293912b316d4SPeter Lieven 
294012b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
29413e230dd2SCorentin Chary 
29429f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2943bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
29449f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
29459f64916dSGerd Hoffmann         } else {
294612b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
29479f64916dSGerd Hoffmann         }
294812b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
29493e230dd2SCorentin Chary 
295012b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
295112b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2952bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
295312b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
29543e230dd2SCorentin Chary                 continue;
2955b4c85ddcSPeter Lieven             }
2956eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
2957eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
2958bea60dd7SPeter Lieven             }
2959eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
2960bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
29613e230dd2SCorentin Chary                 continue;
2962b4c85ddcSPeter Lieven             }
2963bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
296412b316d4SPeter Lieven             if (!vd->non_adaptive) {
296512b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
296612b316d4SPeter Lieven                                  y, &tv);
296712b316d4SPeter Lieven             }
29683e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
296912b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
29703e230dd2SCorentin Chary             }
29713e230dd2SCorentin Chary             has_dirty++;
29723e230dd2SCorentin Chary         }
297312b316d4SPeter Lieven 
297412b316d4SPeter Lieven         y++;
29753e230dd2SCorentin Chary     }
29769f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
29773e230dd2SCorentin Chary     return has_dirty;
29783e230dd2SCorentin Chary }
29793e230dd2SCorentin Chary 
29800f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
29813e230dd2SCorentin Chary {
29820f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
29833e230dd2SCorentin Chary     VncState *vs, *vn;
29843e230dd2SCorentin Chary     int has_dirty, rects = 0;
29853e230dd2SCorentin Chary 
29869d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
29879d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
29889d6b2070SChenLiang         return;
29899d6b2070SChenLiang     }
29909d6b2070SChenLiang 
29911d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
29923e230dd2SCorentin Chary 
2993bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
29940f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2995bd023f95SCorentin Chary         return;
2996bd023f95SCorentin Chary     }
2997bd023f95SCorentin Chary 
29983e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
2999bd023f95SCorentin Chary     vnc_unlock_display(vd);
30003e230dd2SCorentin Chary 
30013e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
30026af998dbSDaniel P. Berrange         rects += vnc_update_client(vs, has_dirty);
30033e230dd2SCorentin Chary         /* vs might be free()ed here */
30043e230dd2SCorentin Chary     }
3005bd023f95SCorentin Chary 
30063e230dd2SCorentin Chary     if (has_dirty && rects) {
30070f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
30080f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
30090f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
30100f7b2864SGerd Hoffmann         }
30113e230dd2SCorentin Chary     } else {
30120f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
30130f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
30140f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
30153e230dd2SCorentin Chary         }
30163e230dd2SCorentin Chary     }
30173e230dd2SCorentin Chary }
30183e230dd2SCorentin Chary 
301904d2529dSDaniel P. Berrange static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
30202c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
30213e230dd2SCorentin Chary {
3022fedf0d35SMarkus Armbruster     VncState *vs = g_new0(VncState, 1);
302390cd03a3SDaniel P. Berrange     bool first_client = QTAILQ_EMPTY(&vd->clients);
30247d964c9dSCorentin Chary     int i;
30257d964c9dSCorentin Chary 
3026ad6374c4SDaniel P. Berrange     trace_vnc_client_connect(vs, sioc);
302704d2529dSDaniel P. Berrange     vs->sioc = sioc;
302804d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->sioc));
302904d2529dSDaniel P. Berrange     vs->ioc = QIO_CHANNEL(sioc);
303004d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->ioc));
3031d616ccc5SGerd Hoffmann     vs->vd = vd;
30327e7e2ebcSDaniel P. Berrange 
303304d2529dSDaniel P. Berrange     buffer_init(&vs->input,          "vnc-input/%p", sioc);
303404d2529dSDaniel P. Berrange     buffer_init(&vs->output,         "vnc-output/%p", sioc);
303504d2529dSDaniel P. Berrange     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3036543b9580SGerd Hoffmann 
303704d2529dSDaniel P. Berrange     buffer_init(&vs->tight.tight,    "vnc-tight/%p", sioc);
303804d2529dSDaniel P. Berrange     buffer_init(&vs->tight.zlib,     "vnc-tight-zlib/%p", sioc);
303904d2529dSDaniel P. Berrange     buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
3040543b9580SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
304104d2529dSDaniel P. Berrange     buffer_init(&vs->tight.jpeg,     "vnc-tight-jpeg/%p", sioc);
3042543b9580SGerd Hoffmann #endif
3043543b9580SGerd Hoffmann #ifdef CONFIG_VNC_PNG
304404d2529dSDaniel P. Berrange     buffer_init(&vs->tight.png,      "vnc-tight-png/%p", sioc);
3045543b9580SGerd Hoffmann #endif
304604d2529dSDaniel P. Berrange     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
304704d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.zrle,      "vnc-zrle/%p", sioc);
304804d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.fb,        "vnc-zrle-fb/%p", sioc);
304904d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.zlib,      "vnc-zrle-zlib/%p", sioc);
3050543b9580SGerd Hoffmann 
30517e7e2ebcSDaniel P. Berrange     if (skipauth) {
30527e7e2ebcSDaniel P. Berrange 	vs->auth = VNC_AUTH_NONE;
30537e7e2ebcSDaniel P. Berrange 	vs->subauth = VNC_AUTH_INVALID;
30547e7e2ebcSDaniel P. Berrange     } else {
3055f9148c8aSDaniel P. Berrange         if (websocket) {
3056f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
3057f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
3058f9148c8aSDaniel P. Berrange         } else {
30597e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
30607e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
30617e7e2ebcSDaniel P. Berrange         }
3062f9148c8aSDaniel P. Berrange     }
306304d2529dSDaniel P. Berrange     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
306404d2529dSDaniel P. Berrange               sioc, websocket, vs->auth, vs->subauth);
30657e7e2ebcSDaniel P. Berrange 
30667267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
30677d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3068fedf0d35SMarkus Armbruster         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
30697d964c9dSCorentin Chary     }
30703e230dd2SCorentin Chary 
307104d2529dSDaniel P. Berrange     VNC_DEBUG("New client on socket %p\n", vs->sioc);
30720f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
307304d2529dSDaniel P. Berrange     qio_channel_set_blocking(vs->ioc, false, NULL);
3074a75d6f07SBrandon Carpenter     if (vs->ioc_tag) {
3075a75d6f07SBrandon Carpenter         g_source_remove(vs->ioc_tag);
3076a75d6f07SBrandon Carpenter     }
30777536ee4bSTim Hardeck     if (websocket) {
30787536ee4bSTim Hardeck         vs->websocket = 1;
307938e5756aSDaniel P. Berrange         if (vd->tlscreds) {
308004d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
308104d2529dSDaniel P. Berrange                 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
30823e305e4aSDaniel P. Berrange         } else {
308304d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
308404d2529dSDaniel P. Berrange                 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
30850057a0d5STim Hardeck         }
308604d2529dSDaniel P. Berrange     } else {
308704d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
308804d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
30897536ee4bSTim Hardeck     }
30903e230dd2SCorentin Chary 
30913e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3092fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
30938cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
30943e230dd2SCorentin Chary 
30953e230dd2SCorentin Chary     vs->last_x = -1;
30963e230dd2SCorentin Chary     vs->last_y = -1;
30973e230dd2SCorentin Chary 
30983e230dd2SCorentin Chary     vs->as.freq = 44100;
30993e230dd2SCorentin Chary     vs->as.nchannels = 2;
31003e230dd2SCorentin Chary     vs->as.fmt = AUD_FMT_S16;
31013e230dd2SCorentin Chary     vs->as.endianness = 0;
31023e230dd2SCorentin Chary 
3103bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3104175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3105bd023f95SCorentin Chary 
3106e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3107c7628bffSGerd Hoffmann     if (first_client) {
3108c7628bffSGerd Hoffmann         vnc_update_server_surface(vd);
3109c7628bffSGerd Hoffmann     }
31103e230dd2SCorentin Chary 
31111d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
31123e230dd2SCorentin Chary 
311390cd03a3SDaniel P. Berrange     if (!vs->websocket) {
3114dbee9897SDaniel P. Berrange         vnc_start_protocol(vs);
311590cd03a3SDaniel P. Berrange     }
311690cd03a3SDaniel P. Berrange 
311790cd03a3SDaniel P. Berrange     if (vd->num_connecting > vd->connections_limit) {
311890cd03a3SDaniel P. Berrange         QTAILQ_FOREACH(vs, &vd->clients, next) {
311990cd03a3SDaniel P. Berrange             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
312090cd03a3SDaniel P. Berrange                 vnc_disconnect_start(vs);
312190cd03a3SDaniel P. Berrange                 return;
312290cd03a3SDaniel P. Berrange             }
312390cd03a3SDaniel P. Berrange         }
312490cd03a3SDaniel P. Berrange     }
312590cd03a3SDaniel P. Berrange }
312690cd03a3SDaniel P. Berrange 
3127dbee9897SDaniel P. Berrange void vnc_start_protocol(VncState *vs)
312890cd03a3SDaniel P. Berrange {
31293e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
31303e230dd2SCorentin Chary     vnc_flush(vs);
31313e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
31323e230dd2SCorentin Chary 
31333e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
31343e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
31353e230dd2SCorentin Chary }
31363e230dd2SCorentin Chary 
313704d2529dSDaniel P. Berrange static gboolean vnc_listen_io(QIOChannel *ioc,
313804d2529dSDaniel P. Berrange                               GIOCondition condition,
313904d2529dSDaniel P. Berrange                               void *opaque)
31403e230dd2SCorentin Chary {
3141bf01c179SDaniel P. Berrange     VncDisplay *vd = opaque;
314204d2529dSDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
314304d2529dSDaniel P. Berrange     Error *err = NULL;
31444ee74fa7SDaniel P. Berrange     bool isWebsock = false;
31454ee74fa7SDaniel P. Berrange     size_t i;
31464ee74fa7SDaniel P. Berrange 
31474ee74fa7SDaniel P. Berrange     for (i = 0; i < vd->nlwebsock; i++) {
31484ee74fa7SDaniel P. Berrange         if (ioc == QIO_CHANNEL(vd->lwebsock[i])) {
31494ee74fa7SDaniel P. Berrange             isWebsock = true;
31504ee74fa7SDaniel P. Berrange             break;
31514ee74fa7SDaniel P. Berrange         }
31524ee74fa7SDaniel P. Berrange     }
31533e230dd2SCorentin Chary 
315404d2529dSDaniel P. Berrange     sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), &err);
315504d2529dSDaniel P. Berrange     if (sioc != NULL) {
315610bcfe58SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc),
31574ee74fa7SDaniel P. Berrange                              isWebsock ? "vnc-ws-server" : "vnc-server");
315804d2529dSDaniel P. Berrange         qio_channel_set_delay(QIO_CHANNEL(sioc), false);
31594ee74fa7SDaniel P. Berrange         vnc_connect(vd, sioc, false, isWebsock);
316004d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
31618e9b0d24SDaniel P. Berrange     } else {
316204d2529dSDaniel P. Berrange         /* client probably closed connection before we got there */
316304d2529dSDaniel P. Berrange         error_free(err);
31647536ee4bSTim Hardeck     }
31653e230dd2SCorentin Chary 
316604d2529dSDaniel P. Berrange     return TRUE;
31677536ee4bSTim Hardeck }
31687536ee4bSTim Hardeck 
31697c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
31707c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
31710f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
31727c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3173c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
317434da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
31757c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
31767c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
31777c20b4a3SGerd Hoffmann };
31787c20b4a3SGerd Hoffmann 
317914f7143eSGerd Hoffmann void vnc_display_init(const char *id)
31803e230dd2SCorentin Chary {
3181bf01c179SDaniel P. Berrange     VncDisplay *vd;
31824db14629SGerd Hoffmann 
31834db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
31844db14629SGerd Hoffmann         return;
31854db14629SGerd Hoffmann     }
3186bf01c179SDaniel P. Berrange     vd = g_malloc0(sizeof(*vd));
31873e230dd2SCorentin Chary 
3188bf01c179SDaniel P. Berrange     vd->id = strdup(id);
3189bf01c179SDaniel P. Berrange     QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
31903e230dd2SCorentin Chary 
3191bf01c179SDaniel P. Berrange     QTAILQ_INIT(&vd->clients);
3192bf01c179SDaniel P. Berrange     vd->expires = TIME_MAX;
31933e230dd2SCorentin Chary 
319440066175SGerd Hoffmann     if (keyboard_layout) {
319540066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
3196bf01c179SDaniel P. Berrange         vd->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
319740066175SGerd Hoffmann     } else {
3198bf01c179SDaniel P. Berrange         vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
319940066175SGerd Hoffmann     }
32003e230dd2SCorentin Chary 
3201bf01c179SDaniel P. Berrange     if (!vd->kbd_layout) {
32023e230dd2SCorentin Chary         exit(1);
3203bf01c179SDaniel P. Berrange     }
32043e230dd2SCorentin Chary 
3205bf01c179SDaniel P. Berrange     vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3206bf01c179SDaniel P. Berrange     vd->connections_limit = 32;
320712e29b16SDaniel P. Berrange 
3208bf01c179SDaniel P. Berrange     qemu_mutex_init(&vd->mutex);
3209bd023f95SCorentin Chary     vnc_start_worker_thread();
3210bd023f95SCorentin Chary 
3211bf01c179SDaniel P. Berrange     vd->dcl.ops = &dcl_ops;
3212bf01c179SDaniel P. Berrange     register_displaychangelistener(&vd->dcl);
32133e230dd2SCorentin Chary }
32143e230dd2SCorentin Chary 
32153e230dd2SCorentin Chary 
3216bf01c179SDaniel P. Berrange static void vnc_display_close(VncDisplay *vd)
32173e230dd2SCorentin Chary {
32184ee74fa7SDaniel P. Berrange     size_t i;
3219bf01c179SDaniel P. Berrange     if (!vd) {
32203e230dd2SCorentin Chary         return;
322104d2529dSDaniel P. Berrange     }
3222bf01c179SDaniel P. Berrange     vd->is_unix = false;
32234ee74fa7SDaniel P. Berrange     for (i = 0; i < vd->nlsock; i++) {
32244ee74fa7SDaniel P. Berrange         if (vd->lsock_tag[i]) {
32254ee74fa7SDaniel P. Berrange             g_source_remove(vd->lsock_tag[i]);
32263e230dd2SCorentin Chary         }
32274ee74fa7SDaniel P. Berrange         object_unref(OBJECT(vd->lsock[i]));
32284ee74fa7SDaniel P. Berrange     }
32294ee74fa7SDaniel P. Berrange     g_free(vd->lsock);
32304ee74fa7SDaniel P. Berrange     g_free(vd->lsock_tag);
3231bf01c179SDaniel P. Berrange     vd->lsock = NULL;
32322dc120beSGerd Hoffmann     vd->lsock_tag = NULL;
32334ee74fa7SDaniel P. Berrange     vd->nlsock = 0;
32344ee74fa7SDaniel P. Berrange 
32354ee74fa7SDaniel P. Berrange     for (i = 0; i < vd->nlwebsock; i++) {
32364ee74fa7SDaniel P. Berrange         if (vd->lwebsock_tag[i]) {
32374ee74fa7SDaniel P. Berrange             g_source_remove(vd->lwebsock_tag[i]);
323804d2529dSDaniel P. Berrange         }
32394ee74fa7SDaniel P. Berrange         object_unref(OBJECT(vd->lwebsock[i]));
32407536ee4bSTim Hardeck     }
32414ee74fa7SDaniel P. Berrange     g_free(vd->lwebsock);
32424ee74fa7SDaniel P. Berrange     g_free(vd->lwebsock_tag);
3243bf01c179SDaniel P. Berrange     vd->lwebsock = NULL;
32442dc120beSGerd Hoffmann     vd->lwebsock_tag = NULL;
32454ee74fa7SDaniel P. Berrange     vd->nlwebsock = 0;
32464ee74fa7SDaniel P. Berrange 
3247bf01c179SDaniel P. Berrange     vd->auth = VNC_AUTH_INVALID;
3248bf01c179SDaniel P. Berrange     vd->subauth = VNC_AUTH_INVALID;
3249bf01c179SDaniel P. Berrange     if (vd->tlscreds) {
3250bf01c179SDaniel P. Berrange         object_unparent(OBJECT(vd->tlscreds));
3251bf01c179SDaniel P. Berrange         vd->tlscreds = NULL;
3252bf01c179SDaniel P. Berrange     }
3253bf01c179SDaniel P. Berrange     g_free(vd->tlsaclname);
3254bf01c179SDaniel P. Berrange     vd->tlsaclname = NULL;
3255a54f0d2bSPierre Ossman     if (vd->lock_key_sync) {
3256a54f0d2bSPierre Ossman         qemu_remove_led_event_handler(vd->led);
32572dc120beSGerd Hoffmann         vd->led = NULL;
3258a54f0d2bSPierre Ossman     }
32593e230dd2SCorentin Chary }
32603e230dd2SCorentin Chary 
326114f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
32621cd20f8bSAnthony Liguori {
3263bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
32641cd20f8bSAnthony Liguori 
3265bf01c179SDaniel P. Berrange     if (!vd) {
3266a6aa9d3eSLuiz Capitulino         return -EINVAL;
32671cd20f8bSAnthony Liguori     }
3268bf01c179SDaniel P. Berrange     if (vd->auth == VNC_AUTH_NONE) {
3269cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
32707ea7d36eSMarkus Armbruster                                 "password auth using '-vnc ${dpy},password'.\n");
3271cf864569SGerd Hoffmann         return -EINVAL;
32721cd20f8bSAnthony Liguori     }
32731cd20f8bSAnthony Liguori 
3274bf01c179SDaniel P. Berrange     g_free(vd->password);
3275bf01c179SDaniel P. Berrange     vd->password = g_strdup(password);
3276a6aa9d3eSLuiz Capitulino 
3277a6aa9d3eSLuiz Capitulino     return 0;
32783e230dd2SCorentin Chary }
32793e230dd2SCorentin Chary 
328014f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
32813c9405a0SGerd Hoffmann {
3282bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
32833c9405a0SGerd Hoffmann 
3284bf01c179SDaniel P. Berrange     if (!vd) {
32851643f2b2SGerd Hoffmann         return -EINVAL;
32861643f2b2SGerd Hoffmann     }
32871643f2b2SGerd Hoffmann 
3288bf01c179SDaniel P. Berrange     vd->expires = expires;
32893c9405a0SGerd Hoffmann     return 0;
32903c9405a0SGerd Hoffmann }
32913c9405a0SGerd Hoffmann 
3292bf01c179SDaniel P. Berrange static void vnc_display_print_local_addr(VncDisplay *vd)
32933e230dd2SCorentin Chary {
3294bd269ebcSMarkus Armbruster     SocketAddress *addr;
329504d2529dSDaniel P. Berrange     Error *err = NULL;
32963e230dd2SCorentin Chary 
32974ee74fa7SDaniel P. Berrange     if (!vd->nlsock) {
32984ee74fa7SDaniel P. Berrange         return;
32994ee74fa7SDaniel P. Berrange     }
33004ee74fa7SDaniel P. Berrange 
33014ee74fa7SDaniel P. Berrange     addr = qio_channel_socket_get_local_address(vd->lsock[0], &err);
330204d2529dSDaniel P. Berrange     if (!addr) {
330333df7bf3SPaolo Bonzini         return;
330404d2529dSDaniel P. Berrange     }
330504d2529dSDaniel P. Berrange 
3306bd269ebcSMarkus Armbruster     if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3307bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
330833df7bf3SPaolo Bonzini         return;
330904d2529dSDaniel P. Berrange     }
331033df7bf3SPaolo Bonzini     error_printf_unless_qmp("VNC server running on %s:%s\n",
3311bd269ebcSMarkus Armbruster                             addr->u.inet.host,
3312bd269ebcSMarkus Armbruster                             addr->u.inet.port);
3313bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
33143e230dd2SCorentin Chary }
33153e230dd2SCorentin Chary 
33164db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
33174db14629SGerd Hoffmann     .name = "vnc",
33184db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
33194db14629SGerd Hoffmann     .implied_opt_name = "vnc",
33204db14629SGerd Hoffmann     .desc = {
33214db14629SGerd Hoffmann         {
33224db14629SGerd Hoffmann             .name = "vnc",
33234db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33244db14629SGerd Hoffmann         },{
33254db14629SGerd Hoffmann             .name = "websocket",
33264db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33274db14629SGerd Hoffmann         },{
33283e305e4aSDaniel P. Berrange             .name = "tls-creds",
33293e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
33303e305e4aSDaniel P. Berrange         },{
33313e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33324db14629SGerd Hoffmann             .name = "x509",
33334db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33344db14629SGerd Hoffmann         },{
33354db14629SGerd Hoffmann             .name = "share",
33364db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33374db14629SGerd Hoffmann         },{
33381d0d59feSGerd Hoffmann             .name = "display",
33391d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
33401d0d59feSGerd Hoffmann         },{
33411d0d59feSGerd Hoffmann             .name = "head",
33421d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
33431d0d59feSGerd Hoffmann         },{
3344e5f34cddSGerd Hoffmann             .name = "connections",
3345e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3346e5f34cddSGerd Hoffmann         },{
334788428b7aSGonglei             .name = "to",
334888428b7aSGonglei             .type = QEMU_OPT_NUMBER,
334988428b7aSGonglei         },{
335088428b7aSGonglei             .name = "ipv4",
335188428b7aSGonglei             .type = QEMU_OPT_BOOL,
335288428b7aSGonglei         },{
335388428b7aSGonglei             .name = "ipv6",
335488428b7aSGonglei             .type = QEMU_OPT_BOOL,
335588428b7aSGonglei         },{
33564db14629SGerd Hoffmann             .name = "password",
33574db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33584db14629SGerd Hoffmann         },{
33594db14629SGerd Hoffmann             .name = "reverse",
33604db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33614db14629SGerd Hoffmann         },{
33624db14629SGerd Hoffmann             .name = "lock-key-sync",
33634db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33644db14629SGerd Hoffmann         },{
3365c5ce8333SGerd Hoffmann             .name = "key-delay-ms",
3366c5ce8333SGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3367c5ce8333SGerd Hoffmann         },{
33684db14629SGerd Hoffmann             .name = "sasl",
33694db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33704db14629SGerd Hoffmann         },{
33713e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33724db14629SGerd Hoffmann             .name = "tls",
33734db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33744db14629SGerd Hoffmann         },{
33753e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33764db14629SGerd Hoffmann             .name = "x509verify",
33778c7d0645SDaniel P. Berrange             .type = QEMU_OPT_STRING,
33784db14629SGerd Hoffmann         },{
33794db14629SGerd Hoffmann             .name = "acl",
33804db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33814db14629SGerd Hoffmann         },{
33824db14629SGerd Hoffmann             .name = "lossy",
33834db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33844db14629SGerd Hoffmann         },{
33854db14629SGerd Hoffmann             .name = "non-adaptive",
33864db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33874db14629SGerd Hoffmann         },
33884db14629SGerd Hoffmann         { /* end of list */ }
33894db14629SGerd Hoffmann     },
33904db14629SGerd Hoffmann };
33914db14629SGerd Hoffmann 
33920dd72e15SDaniel P. Berrange 
33933e305e4aSDaniel P. Berrange static int
3394eda24e18SDaniel P. Berrange vnc_display_setup_auth(int *auth,
3395eda24e18SDaniel P. Berrange                        int *subauth,
3396eda24e18SDaniel P. Berrange                        QCryptoTLSCreds *tlscreds,
33970dd72e15SDaniel P. Berrange                        bool password,
33980dd72e15SDaniel P. Berrange                        bool sasl,
33993e305e4aSDaniel P. Berrange                        bool websocket,
34003e305e4aSDaniel P. Berrange                        Error **errp)
34010dd72e15SDaniel P. Berrange {
34020dd72e15SDaniel P. Berrange     /*
34030dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
34040dd72e15SDaniel P. Berrange      *
34050dd72e15SDaniel P. Berrange      *   1. none
34060dd72e15SDaniel P. Berrange      *   2. vnc
34070dd72e15SDaniel P. Berrange      *   3. sasl
34080dd72e15SDaniel P. Berrange      *
34090dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
34100dd72e15SDaniel P. Berrange      *
34110dd72e15SDaniel P. Berrange      *   1. clear
34120dd72e15SDaniel P. Berrange      *   2. tls
34130dd72e15SDaniel P. Berrange      *
34140dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
34150dd72e15SDaniel P. Berrange      *
34160dd72e15SDaniel P. Berrange      *   1. anon
34170dd72e15SDaniel P. Berrange      *   2. x509
34180dd72e15SDaniel P. Berrange      *
34190dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
34200dd72e15SDaniel P. Berrange      *
34210dd72e15SDaniel P. Berrange      *   1. clear + none
34220dd72e15SDaniel P. Berrange      *   2. clear + vnc
34230dd72e15SDaniel P. Berrange      *   3. clear + sasl
34240dd72e15SDaniel P. Berrange      *   4. tls + anon + none
34250dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
34260dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
34270dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
34280dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
34290dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
34300dd72e15SDaniel P. Berrange      *
34310dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
34320dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
34330dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
34340dd72e15SDaniel P. Berrange      * sub-auth types.
3435f9148c8aSDaniel P. Berrange      *
3436f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3437f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3438f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3439f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3440f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3441f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3442f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3443f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3444f9148c8aSDaniel P. Berrange      *
3445f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3446f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3447f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
34480dd72e15SDaniel P. Berrange      */
3449eda24e18SDaniel P. Berrange     if (websocket || !tlscreds) {
34500dd72e15SDaniel P. Berrange         if (password) {
34510dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
3452eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_VNC;
34530dd72e15SDaniel P. Berrange         } else if (sasl) {
34540dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3455eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_SASL;
34560dd72e15SDaniel P. Berrange         } else {
34570dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
3458eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_NONE;
34590dd72e15SDaniel P. Berrange         }
3460eda24e18SDaniel P. Berrange         *subauth = VNC_AUTH_INVALID;
3461f9148c8aSDaniel P. Berrange     } else {
3462eda24e18SDaniel P. Berrange         bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3463eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3464eda24e18SDaniel P. Berrange         bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3465eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3466eda24e18SDaniel P. Berrange 
3467eda24e18SDaniel P. Berrange         if (!is_x509 && !is_anon) {
3468eda24e18SDaniel P. Berrange             error_setg(errp,
3469eda24e18SDaniel P. Berrange                        "Unsupported TLS cred type %s",
3470eda24e18SDaniel P. Berrange                        object_get_typename(OBJECT(tlscreds)));
3471eda24e18SDaniel P. Berrange             return -1;
3472eda24e18SDaniel P. Berrange         }
3473eda24e18SDaniel P. Berrange         *auth = VNC_AUTH_VENCRYPT;
3474eda24e18SDaniel P. Berrange         if (password) {
3475eda24e18SDaniel P. Berrange             if (is_x509) {
3476eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3477eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3478eda24e18SDaniel P. Berrange             } else {
3479eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3480eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3481eda24e18SDaniel P. Berrange             }
3482eda24e18SDaniel P. Berrange 
3483eda24e18SDaniel P. Berrange         } else if (sasl) {
3484eda24e18SDaniel P. Berrange             if (is_x509) {
3485eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3486eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3487eda24e18SDaniel P. Berrange             } else {
3488eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3489eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3490eda24e18SDaniel P. Berrange             }
3491eda24e18SDaniel P. Berrange         } else {
3492eda24e18SDaniel P. Berrange             if (is_x509) {
3493eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3494eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3495eda24e18SDaniel P. Berrange             } else {
3496eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3497eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3498eda24e18SDaniel P. Berrange             }
3499f9148c8aSDaniel P. Berrange         }
35000dd72e15SDaniel P. Berrange     }
35013e305e4aSDaniel P. Berrange     return 0;
35020dd72e15SDaniel P. Berrange }
35030dd72e15SDaniel P. Berrange 
35043e305e4aSDaniel P. Berrange 
35053e305e4aSDaniel P. Berrange /*
35063e305e4aSDaniel P. Berrange  * Handle back compat with old CLI syntax by creating some
35073e305e4aSDaniel P. Berrange  * suitable QCryptoTLSCreds objects
35083e305e4aSDaniel P. Berrange  */
35093e305e4aSDaniel P. Berrange static QCryptoTLSCreds *
35103e305e4aSDaniel P. Berrange vnc_display_create_creds(bool x509,
35113e305e4aSDaniel P. Berrange                          bool x509verify,
35123e305e4aSDaniel P. Berrange                          const char *dir,
35133e305e4aSDaniel P. Berrange                          const char *id,
35143e305e4aSDaniel P. Berrange                          Error **errp)
35153e305e4aSDaniel P. Berrange {
35163e305e4aSDaniel P. Berrange     gchar *credsid = g_strdup_printf("tlsvnc%s", id);
35173e305e4aSDaniel P. Berrange     Object *parent = object_get_objects_root();
35183e305e4aSDaniel P. Berrange     Object *creds;
35193e305e4aSDaniel P. Berrange     Error *err = NULL;
35203e305e4aSDaniel P. Berrange 
35213e305e4aSDaniel P. Berrange     if (x509) {
35223e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
35233e305e4aSDaniel P. Berrange                                       parent,
35243e305e4aSDaniel P. Berrange                                       credsid,
35253e305e4aSDaniel P. Berrange                                       &err,
35263e305e4aSDaniel P. Berrange                                       "endpoint", "server",
35273e305e4aSDaniel P. Berrange                                       "dir", dir,
35283e305e4aSDaniel P. Berrange                                       "verify-peer", x509verify ? "yes" : "no",
35293e305e4aSDaniel P. Berrange                                       NULL);
35303e305e4aSDaniel P. Berrange     } else {
35313e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
35323e305e4aSDaniel P. Berrange                                       parent,
35333e305e4aSDaniel P. Berrange                                       credsid,
35343e305e4aSDaniel P. Berrange                                       &err,
35353e305e4aSDaniel P. Berrange                                       "endpoint", "server",
35363e305e4aSDaniel P. Berrange                                       NULL);
35373e305e4aSDaniel P. Berrange     }
35383e305e4aSDaniel P. Berrange 
35393e305e4aSDaniel P. Berrange     g_free(credsid);
35403e305e4aSDaniel P. Berrange 
35413e305e4aSDaniel P. Berrange     if (err) {
35423e305e4aSDaniel P. Berrange         error_propagate(errp, err);
35433e305e4aSDaniel P. Berrange         return NULL;
35443e305e4aSDaniel P. Berrange     }
35453e305e4aSDaniel P. Berrange 
35463e305e4aSDaniel P. Berrange     return QCRYPTO_TLS_CREDS(creds);
35473e305e4aSDaniel P. Berrange }
35483e305e4aSDaniel P. Berrange 
35493e305e4aSDaniel P. Berrange 
3550275e0d61SDaniel P. Berrange static int vnc_display_get_address(const char *addrstr,
3551275e0d61SDaniel P. Berrange                                    bool websocket,
3552e5766eb4SGerd Hoffmann                                    bool reverse,
3553275e0d61SDaniel P. Berrange                                    int displaynum,
3554275e0d61SDaniel P. Berrange                                    int to,
3555275e0d61SDaniel P. Berrange                                    bool has_ipv4,
3556275e0d61SDaniel P. Berrange                                    bool has_ipv6,
3557275e0d61SDaniel P. Berrange                                    bool ipv4,
3558275e0d61SDaniel P. Berrange                                    bool ipv6,
3559bd269ebcSMarkus Armbruster                                    SocketAddress **retaddr,
3560275e0d61SDaniel P. Berrange                                    Error **errp)
3561275e0d61SDaniel P. Berrange {
3562275e0d61SDaniel P. Berrange     int ret = -1;
3563bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3564275e0d61SDaniel P. Berrange 
3565bd269ebcSMarkus Armbruster     addr = g_new0(SocketAddress, 1);
3566275e0d61SDaniel P. Berrange 
3567275e0d61SDaniel P. Berrange     if (strncmp(addrstr, "unix:", 5) == 0) {
3568bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3569bd269ebcSMarkus Armbruster         addr->u.q_unix.path = g_strdup(addrstr + 5);
3570275e0d61SDaniel P. Berrange 
3571275e0d61SDaniel P. Berrange         if (websocket) {
3572275e0d61SDaniel P. Berrange             error_setg(errp, "UNIX sockets not supported with websock");
3573275e0d61SDaniel P. Berrange             goto cleanup;
3574275e0d61SDaniel P. Berrange         }
3575275e0d61SDaniel P. Berrange 
3576275e0d61SDaniel P. Berrange         if (to) {
3577275e0d61SDaniel P. Berrange             error_setg(errp, "Port range not support with UNIX socket");
3578275e0d61SDaniel P. Berrange             goto cleanup;
3579275e0d61SDaniel P. Berrange         }
3580275e0d61SDaniel P. Berrange         ret = 0;
3581275e0d61SDaniel P. Berrange     } else {
3582275e0d61SDaniel P. Berrange         const char *port;
3583275e0d61SDaniel P. Berrange         size_t hostlen;
3584275e0d61SDaniel P. Berrange         unsigned long long baseport = 0;
3585275e0d61SDaniel P. Berrange         InetSocketAddress *inet;
3586275e0d61SDaniel P. Berrange 
3587275e0d61SDaniel P. Berrange         port = strrchr(addrstr, ':');
3588275e0d61SDaniel P. Berrange         if (!port) {
3589275e0d61SDaniel P. Berrange             if (websocket) {
3590275e0d61SDaniel P. Berrange                 hostlen = 0;
3591275e0d61SDaniel P. Berrange                 port = addrstr;
3592275e0d61SDaniel P. Berrange             } else {
3593275e0d61SDaniel P. Berrange                 error_setg(errp, "no vnc port specified");
3594275e0d61SDaniel P. Berrange                 goto cleanup;
3595275e0d61SDaniel P. Berrange             }
3596275e0d61SDaniel P. Berrange         } else {
3597275e0d61SDaniel P. Berrange             hostlen = port - addrstr;
3598275e0d61SDaniel P. Berrange             port++;
3599275e0d61SDaniel P. Berrange             if (*port == '\0') {
3600275e0d61SDaniel P. Berrange                 error_setg(errp, "vnc port cannot be empty");
3601275e0d61SDaniel P. Berrange                 goto cleanup;
3602275e0d61SDaniel P. Berrange             }
3603275e0d61SDaniel P. Berrange         }
3604275e0d61SDaniel P. Berrange 
3605bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_INET;
3606bd269ebcSMarkus Armbruster         inet = &addr->u.inet;
3607275e0d61SDaniel P. Berrange         if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3608275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr + 1, hostlen - 2);
3609275e0d61SDaniel P. Berrange         } else {
3610275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr, hostlen);
3611275e0d61SDaniel P. Berrange         }
3612275e0d61SDaniel P. Berrange         /* plain VNC port is just an offset, for websocket
3613275e0d61SDaniel P. Berrange          * port is absolute */
3614275e0d61SDaniel P. Berrange         if (websocket) {
3615275e0d61SDaniel P. Berrange             if (g_str_equal(addrstr, "") ||
3616275e0d61SDaniel P. Berrange                 g_str_equal(addrstr, "on")) {
3617396f935aSDaniel P. Berrange                 if (displaynum == -1) {
3618396f935aSDaniel P. Berrange                     error_setg(errp, "explicit websocket port is required");
3619396f935aSDaniel P. Berrange                     goto cleanup;
3620396f935aSDaniel P. Berrange                 }
3621275e0d61SDaniel P. Berrange                 inet->port = g_strdup_printf(
3622275e0d61SDaniel P. Berrange                     "%d", displaynum + 5700);
3623275e0d61SDaniel P. Berrange                 if (to) {
3624275e0d61SDaniel P. Berrange                     inet->has_to = true;
3625275e0d61SDaniel P. Berrange                     inet->to = to + 5700;
3626275e0d61SDaniel P. Berrange                 }
3627275e0d61SDaniel P. Berrange             } else {
3628275e0d61SDaniel P. Berrange                 inet->port = g_strdup(port);
3629275e0d61SDaniel P. Berrange             }
3630275e0d61SDaniel P. Berrange         } else {
3631e5766eb4SGerd Hoffmann             int offset = reverse ? 0 : 5900;
3632275e0d61SDaniel P. Berrange             if (parse_uint_full(port, &baseport, 10) < 0) {
3633275e0d61SDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", port);
3634275e0d61SDaniel P. Berrange                 goto cleanup;
3635275e0d61SDaniel P. Berrange             }
3636275e0d61SDaniel P. Berrange             if (baseport > 65535 ||
3637e5766eb4SGerd Hoffmann                 baseport + offset > 65535) {
3638275e0d61SDaniel P. Berrange                 error_setg(errp, "port %s out of range", port);
3639275e0d61SDaniel P. Berrange                 goto cleanup;
3640275e0d61SDaniel P. Berrange             }
3641275e0d61SDaniel P. Berrange             inet->port = g_strdup_printf(
3642e5766eb4SGerd Hoffmann                 "%d", (int)baseport + offset);
3643275e0d61SDaniel P. Berrange 
3644275e0d61SDaniel P. Berrange             if (to) {
3645275e0d61SDaniel P. Berrange                 inet->has_to = true;
3646e5766eb4SGerd Hoffmann                 inet->to = to + offset;
3647275e0d61SDaniel P. Berrange             }
3648275e0d61SDaniel P. Berrange         }
3649275e0d61SDaniel P. Berrange 
3650275e0d61SDaniel P. Berrange         inet->ipv4 = ipv4;
3651275e0d61SDaniel P. Berrange         inet->has_ipv4 = has_ipv4;
3652275e0d61SDaniel P. Berrange         inet->ipv6 = ipv6;
3653275e0d61SDaniel P. Berrange         inet->has_ipv6 = has_ipv6;
3654275e0d61SDaniel P. Berrange 
3655275e0d61SDaniel P. Berrange         ret = baseport;
3656275e0d61SDaniel P. Berrange     }
3657275e0d61SDaniel P. Berrange 
3658275e0d61SDaniel P. Berrange     *retaddr = addr;
3659275e0d61SDaniel P. Berrange 
3660275e0d61SDaniel P. Berrange  cleanup:
3661275e0d61SDaniel P. Berrange     if (ret < 0) {
3662bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
3663275e0d61SDaniel P. Berrange     }
3664275e0d61SDaniel P. Berrange     return ret;
3665275e0d61SDaniel P. Berrange }
3666275e0d61SDaniel P. Berrange 
36679f26f325SPhilippe Mathieu-Daudé static void vnc_free_addresses(SocketAddress ***retsaddr,
36689f26f325SPhilippe Mathieu-Daudé                                size_t *retnsaddr)
36699f26f325SPhilippe Mathieu-Daudé {
36709f26f325SPhilippe Mathieu-Daudé     size_t i;
36719f26f325SPhilippe Mathieu-Daudé 
36729f26f325SPhilippe Mathieu-Daudé     for (i = 0; i < *retnsaddr; i++) {
36739f26f325SPhilippe Mathieu-Daudé         qapi_free_SocketAddress((*retsaddr)[i]);
36749f26f325SPhilippe Mathieu-Daudé     }
36759f26f325SPhilippe Mathieu-Daudé     g_free(*retsaddr);
36769f26f325SPhilippe Mathieu-Daudé 
36779f26f325SPhilippe Mathieu-Daudé     *retsaddr = NULL;
36789f26f325SPhilippe Mathieu-Daudé     *retnsaddr = 0;
36799f26f325SPhilippe Mathieu-Daudé }
36809f26f325SPhilippe Mathieu-Daudé 
3681275e0d61SDaniel P. Berrange static int vnc_display_get_addresses(QemuOpts *opts,
3682e5766eb4SGerd Hoffmann                                      bool reverse,
3683bd269ebcSMarkus Armbruster                                      SocketAddress ***retsaddr,
3684396f935aSDaniel P. Berrange                                      size_t *retnsaddr,
3685bd269ebcSMarkus Armbruster                                      SocketAddress ***retwsaddr,
3686396f935aSDaniel P. Berrange                                      size_t *retnwsaddr,
3687275e0d61SDaniel P. Berrange                                      Error **errp)
3688275e0d61SDaniel P. Berrange {
3689bd269ebcSMarkus Armbruster     SocketAddress *saddr = NULL;
3690bd269ebcSMarkus Armbruster     SocketAddress *wsaddr = NULL;
3691396f935aSDaniel P. Berrange     QemuOptsIter addriter;
3692396f935aSDaniel P. Berrange     const char *addr;
3693275e0d61SDaniel P. Berrange     int to = qemu_opt_get_number(opts, "to", 0);
3694275e0d61SDaniel P. Berrange     bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3695275e0d61SDaniel P. Berrange     bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3696275e0d61SDaniel P. Berrange     bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3697275e0d61SDaniel P. Berrange     bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3698396f935aSDaniel P. Berrange     int displaynum = -1;
3699396f935aSDaniel P. Berrange     int ret = -1;
3700275e0d61SDaniel P. Berrange 
3701275e0d61SDaniel P. Berrange     *retsaddr = NULL;
3702396f935aSDaniel P. Berrange     *retnsaddr = 0;
3703275e0d61SDaniel P. Berrange     *retwsaddr = NULL;
3704396f935aSDaniel P. Berrange     *retnwsaddr = 0;
3705275e0d61SDaniel P. Berrange 
3706396f935aSDaniel P. Berrange     addr = qemu_opt_get(opts, "vnc");
3707396f935aSDaniel P. Berrange     if (addr == NULL || g_str_equal(addr, "none")) {
3708396f935aSDaniel P. Berrange         ret = 0;
3709396f935aSDaniel P. Berrange         goto cleanup;
3710396f935aSDaniel P. Berrange     }
3711396f935aSDaniel P. Berrange     if (qemu_opt_get(opts, "websocket") &&
3712275e0d61SDaniel P. Berrange         !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3713275e0d61SDaniel P. Berrange         error_setg(errp,
3714275e0d61SDaniel P. Berrange                    "SHA1 hash support is required for websockets");
3715396f935aSDaniel P. Berrange         goto cleanup;
3716275e0d61SDaniel P. Berrange     }
3717275e0d61SDaniel P. Berrange 
3718396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "vnc");
3719396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3720396f935aSDaniel P. Berrange         int rv;
3721e5766eb4SGerd Hoffmann         rv = vnc_display_get_address(addr, false, reverse, 0, to,
3722275e0d61SDaniel P. Berrange                                      has_ipv4, has_ipv6,
3723275e0d61SDaniel P. Berrange                                      ipv4, ipv6,
3724275e0d61SDaniel P. Berrange                                      &saddr, errp);
3725396f935aSDaniel P. Berrange         if (rv < 0) {
3726396f935aSDaniel P. Berrange             goto cleanup;
3727275e0d61SDaniel P. Berrange         }
3728396f935aSDaniel P. Berrange         /* Historical compat - first listen address can be used
3729396f935aSDaniel P. Berrange          * to set the default websocket port
3730396f935aSDaniel P. Berrange          */
3731396f935aSDaniel P. Berrange         if (displaynum == -1) {
3732396f935aSDaniel P. Berrange             displaynum = rv;
3733396f935aSDaniel P. Berrange         }
3734bd269ebcSMarkus Armbruster         *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3735396f935aSDaniel P. Berrange         (*retsaddr)[(*retnsaddr)++] = saddr;
3736396f935aSDaniel P. Berrange     }
3737396f935aSDaniel P. Berrange 
3738396f935aSDaniel P. Berrange     /* If we had multiple primary displays, we don't do defaults
3739396f935aSDaniel P. Berrange      * for websocket, and require explicit config instead. */
3740396f935aSDaniel P. Berrange     if (*retnsaddr > 1) {
3741396f935aSDaniel P. Berrange         displaynum = -1;
3742396f935aSDaniel P. Berrange     }
3743396f935aSDaniel P. Berrange 
3744396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "websocket");
3745396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3746e5766eb4SGerd Hoffmann         if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3747275e0d61SDaniel P. Berrange                                     has_ipv4, has_ipv6,
3748275e0d61SDaniel P. Berrange                                     ipv4, ipv6,
3749275e0d61SDaniel P. Berrange                                     &wsaddr, errp) < 0) {
3750396f935aSDaniel P. Berrange             goto cleanup;
3751275e0d61SDaniel P. Berrange         }
3752396f935aSDaniel P. Berrange 
3753396f935aSDaniel P. Berrange         /* Historical compat - if only a single listen address was
3754396f935aSDaniel P. Berrange          * provided, then this is used to set the default listen
3755396f935aSDaniel P. Berrange          * address for websocket too
3756396f935aSDaniel P. Berrange          */
3757396f935aSDaniel P. Berrange         if (*retnsaddr == 1 &&
3758bd269ebcSMarkus Armbruster             (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3759bd269ebcSMarkus Armbruster             wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3760bd269ebcSMarkus Armbruster             g_str_equal(wsaddr->u.inet.host, "") &&
3761bd269ebcSMarkus Armbruster             !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3762bd269ebcSMarkus Armbruster             g_free(wsaddr->u.inet.host);
3763bd269ebcSMarkus Armbruster             wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3764275e0d61SDaniel P. Berrange         }
3765275e0d61SDaniel P. Berrange 
3766bd269ebcSMarkus Armbruster         *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3767396f935aSDaniel P. Berrange         (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3768396f935aSDaniel P. Berrange     }
3769396f935aSDaniel P. Berrange 
3770396f935aSDaniel P. Berrange     ret = 0;
3771396f935aSDaniel P. Berrange  cleanup:
3772396f935aSDaniel P. Berrange     if (ret < 0) {
37739f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retsaddr, retnsaddr);
37749f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retwsaddr, retnwsaddr);
3775396f935aSDaniel P. Berrange     }
3776396f935aSDaniel P. Berrange     return ret;
3777275e0d61SDaniel P. Berrange }
3778275e0d61SDaniel P. Berrange 
37798bd22f47SDaniel P. Berrange static int vnc_display_connect(VncDisplay *vd,
3780bd269ebcSMarkus Armbruster                                SocketAddress **saddr,
3781396f935aSDaniel P. Berrange                                size_t nsaddr,
3782bd269ebcSMarkus Armbruster                                SocketAddress **wsaddr,
3783396f935aSDaniel P. Berrange                                size_t nwsaddr,
37848bd22f47SDaniel P. Berrange                                Error **errp)
37858bd22f47SDaniel P. Berrange {
37868bd22f47SDaniel P. Berrange     /* connect to viewer */
37878bd22f47SDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
3788396f935aSDaniel P. Berrange     if (nwsaddr != 0) {
37898bd22f47SDaniel P. Berrange         error_setg(errp, "Cannot use websockets in reverse mode");
37908bd22f47SDaniel P. Berrange         return -1;
37918bd22f47SDaniel P. Berrange     }
3792396f935aSDaniel P. Berrange     if (nsaddr != 1) {
3793396f935aSDaniel P. Berrange         error_setg(errp, "Expected a single address in reverse mode");
3794396f935aSDaniel P. Berrange         return -1;
3795396f935aSDaniel P. Berrange     }
3796bd269ebcSMarkus Armbruster     /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3797bd269ebcSMarkus Armbruster     vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
37988bd22f47SDaniel P. Berrange     sioc = qio_channel_socket_new();
37998bd22f47SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3800396f935aSDaniel P. Berrange     if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
38018bd22f47SDaniel P. Berrange         return -1;
38028bd22f47SDaniel P. Berrange     }
38038bd22f47SDaniel P. Berrange     vnc_connect(vd, sioc, false, false);
38048bd22f47SDaniel P. Berrange     object_unref(OBJECT(sioc));
38058bd22f47SDaniel P. Berrange     return 0;
38068bd22f47SDaniel P. Berrange }
38078bd22f47SDaniel P. Berrange 
38088bd22f47SDaniel P. Berrange 
38098bd22f47SDaniel P. Berrange static int vnc_display_listen_addr(VncDisplay *vd,
3810bd269ebcSMarkus Armbruster                                    SocketAddress *addr,
38118bd22f47SDaniel P. Berrange                                    const char *name,
38128bd22f47SDaniel P. Berrange                                    QIOChannelSocket ***lsock,
38138bd22f47SDaniel P. Berrange                                    guint **lsock_tag,
38148bd22f47SDaniel P. Berrange                                    size_t *nlsock,
38158bd22f47SDaniel P. Berrange                                    Error **errp)
38168bd22f47SDaniel P. Berrange {
381757a6d6d5SDaniel P. Berrange     QIODNSResolver *resolver = qio_dns_resolver_get_instance();
3818bd269ebcSMarkus Armbruster     SocketAddress **rawaddrs = NULL;
381957a6d6d5SDaniel P. Berrange     size_t nrawaddrs = 0;
382057a6d6d5SDaniel P. Berrange     Error *listenerr = NULL;
3821396f935aSDaniel P. Berrange     bool listening = false;
382257a6d6d5SDaniel P. Berrange     size_t i;
38238bd22f47SDaniel P. Berrange 
382457a6d6d5SDaniel P. Berrange     if (qio_dns_resolver_lookup_sync(resolver, addr, &nrawaddrs,
382557a6d6d5SDaniel P. Berrange                                      &rawaddrs, errp) < 0) {
38268bd22f47SDaniel P. Berrange         return -1;
38278bd22f47SDaniel P. Berrange     }
38288bd22f47SDaniel P. Berrange 
382957a6d6d5SDaniel P. Berrange     for (i = 0; i < nrawaddrs; i++) {
383057a6d6d5SDaniel P. Berrange         QIOChannelSocket *sioc = qio_channel_socket_new();
383157a6d6d5SDaniel P. Berrange 
383257a6d6d5SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc), name);
383357a6d6d5SDaniel P. Berrange         if (qio_channel_socket_listen_sync(
383457a6d6d5SDaniel P. Berrange                 sioc, rawaddrs[i], listenerr == NULL ? &listenerr : NULL) < 0) {
38357bc4f084SMarc-André Lureau             object_unref(OBJECT(sioc));
383657a6d6d5SDaniel P. Berrange             continue;
383757a6d6d5SDaniel P. Berrange         }
3838396f935aSDaniel P. Berrange         listening = true;
383957a6d6d5SDaniel P. Berrange         (*nlsock)++;
384057a6d6d5SDaniel P. Berrange         *lsock = g_renew(QIOChannelSocket *, *lsock, *nlsock);
384157a6d6d5SDaniel P. Berrange         *lsock_tag = g_renew(guint, *lsock_tag, *nlsock);
384257a6d6d5SDaniel P. Berrange 
384357a6d6d5SDaniel P. Berrange         (*lsock)[*nlsock - 1] = sioc;
384457a6d6d5SDaniel P. Berrange         (*lsock_tag)[*nlsock - 1] = 0;
384557a6d6d5SDaniel P. Berrange     }
384657a6d6d5SDaniel P. Berrange 
384757a6d6d5SDaniel P. Berrange     for (i = 0; i < nrawaddrs; i++) {
3848bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(rawaddrs[i]);
384957a6d6d5SDaniel P. Berrange     }
385057a6d6d5SDaniel P. Berrange     g_free(rawaddrs);
385157a6d6d5SDaniel P. Berrange 
385257a6d6d5SDaniel P. Berrange     if (listenerr) {
3853396f935aSDaniel P. Berrange         if (!listening) {
385457a6d6d5SDaniel P. Berrange             error_propagate(errp, listenerr);
385557a6d6d5SDaniel P. Berrange             return -1;
385657a6d6d5SDaniel P. Berrange         } else {
385757a6d6d5SDaniel P. Berrange             error_free(listenerr);
385857a6d6d5SDaniel P. Berrange         }
385957a6d6d5SDaniel P. Berrange     }
386057a6d6d5SDaniel P. Berrange 
386157a6d6d5SDaniel P. Berrange     for (i = 0; i < *nlsock; i++) {
386257a6d6d5SDaniel P. Berrange         (*lsock_tag)[i] = qio_channel_add_watch(
386357a6d6d5SDaniel P. Berrange             QIO_CHANNEL((*lsock)[i]),
38648bd22f47SDaniel P. Berrange             G_IO_IN, vnc_listen_io, vd, NULL);
386557a6d6d5SDaniel P. Berrange     }
38668bd22f47SDaniel P. Berrange 
38678bd22f47SDaniel P. Berrange     return 0;
38688bd22f47SDaniel P. Berrange }
38698bd22f47SDaniel P. Berrange 
38708bd22f47SDaniel P. Berrange 
38718bd22f47SDaniel P. Berrange static int vnc_display_listen(VncDisplay *vd,
3872bd269ebcSMarkus Armbruster                               SocketAddress **saddr,
3873396f935aSDaniel P. Berrange                               size_t nsaddr,
3874bd269ebcSMarkus Armbruster                               SocketAddress **wsaddr,
3875396f935aSDaniel P. Berrange                               size_t nwsaddr,
38768bd22f47SDaniel P. Berrange                               Error **errp)
38778bd22f47SDaniel P. Berrange {
3878396f935aSDaniel P. Berrange     size_t i;
38798bd22f47SDaniel P. Berrange 
3880396f935aSDaniel P. Berrange     for (i = 0; i < nsaddr; i++) {
3881396f935aSDaniel P. Berrange         if (vnc_display_listen_addr(vd, saddr[i],
38828bd22f47SDaniel P. Berrange                                     "vnc-listen",
38838bd22f47SDaniel P. Berrange                                     &vd->lsock,
38848bd22f47SDaniel P. Berrange                                     &vd->lsock_tag,
38858bd22f47SDaniel P. Berrange                                     &vd->nlsock,
38868bd22f47SDaniel P. Berrange                                     errp) < 0) {
38878bd22f47SDaniel P. Berrange             return -1;
38888bd22f47SDaniel P. Berrange         }
3889396f935aSDaniel P. Berrange     }
3890396f935aSDaniel P. Berrange     for (i = 0; i < nwsaddr; i++) {
3891396f935aSDaniel P. Berrange         if (vnc_display_listen_addr(vd, wsaddr[i],
38928bd22f47SDaniel P. Berrange                                     "vnc-ws-listen",
38938bd22f47SDaniel P. Berrange                                     &vd->lwebsock,
38948bd22f47SDaniel P. Berrange                                     &vd->lwebsock_tag,
38958bd22f47SDaniel P. Berrange                                     &vd->nlwebsock,
38968bd22f47SDaniel P. Berrange                                     errp) < 0) {
38978bd22f47SDaniel P. Berrange             return -1;
38988bd22f47SDaniel P. Berrange         }
3899396f935aSDaniel P. Berrange     }
39008bd22f47SDaniel P. Berrange 
39018bd22f47SDaniel P. Berrange     return 0;
39028bd22f47SDaniel P. Berrange }
39038bd22f47SDaniel P. Berrange 
39048bd22f47SDaniel P. Berrange 
39054db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
39063e230dd2SCorentin Chary {
3907bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
39084db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3909bd269ebcSMarkus Armbruster     SocketAddress **saddr = NULL, **wsaddr = NULL;
3910396f935aSDaniel P. Berrange     size_t nsaddr, nwsaddr;
3911e2a11d9dSGonglei     const char *share, *device_id;
39121d0d59feSGerd Hoffmann     QemuConsole *con;
3913a2c72de0SGonglei     bool password = false;
3914a2c72de0SGonglei     bool reverse = false;
39153e305e4aSDaniel P. Berrange     const char *credid;
3916a2c72de0SGonglei     bool sasl = false;
3917d169f04bSDaniel P. Berrange #ifdef CONFIG_VNC_SASL
39183e230dd2SCorentin Chary     int saslErr;
39193e230dd2SCorentin Chary #endif
39203e230dd2SCorentin Chary     int acl = 0;
39213e230dd2SCorentin Chary     int lock_key_sync = 1;
3922c5ce8333SGerd Hoffmann     int key_delay_ms;
39233e230dd2SCorentin Chary 
3924bf01c179SDaniel P. Berrange     if (!vd) {
39252d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
39262d55f0e8SPaolo Bonzini         return;
39272d55f0e8SPaolo Bonzini     }
3928bf01c179SDaniel P. Berrange     vnc_display_close(vd);
39294db14629SGerd Hoffmann 
39304db14629SGerd Hoffmann     if (!opts) {
39312d55f0e8SPaolo Bonzini         return;
39324db14629SGerd Hoffmann     }
3933275e0d61SDaniel P. Berrange 
3934e5766eb4SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
3935e5766eb4SGerd Hoffmann     if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3936396f935aSDaniel P. Berrange                                   &wsaddr, &nwsaddr, errp) < 0) {
3937275e0d61SDaniel P. Berrange         goto fail;
3938275e0d61SDaniel P. Berrange     }
3939275e0d61SDaniel P. Berrange 
39404db14629SGerd Hoffmann     password = qemu_opt_get_bool(opts, "password", false);
3941800567a6SDaniel P. Berrange     if (password) {
3942800567a6SDaniel P. Berrange         if (fips_get_state()) {
39432d55f0e8SPaolo Bonzini             error_setg(errp,
39440f66998fSPaul Moore                        "VNC password auth disabled due to FIPS mode, "
39450f66998fSPaul Moore                        "consider using the VeNCrypt or SASL authentication "
39462d55f0e8SPaolo Bonzini                        "methods as an alternative");
39471ce52c78SPaolo Bonzini             goto fail;
39480f66998fSPaul Moore         }
3949800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
3950f844836dSGonglei                 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3951800567a6SDaniel P. Berrange             error_setg(errp,
3952800567a6SDaniel P. Berrange                        "Cipher backend does not support DES RFB algorithm");
3953800567a6SDaniel P. Berrange             goto fail;
3954800567a6SDaniel P. Berrange         }
3955800567a6SDaniel P. Berrange     }
39564db14629SGerd Hoffmann 
39574db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3958d3b0db6dSAlexander Graf     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
39594db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
3960d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
3961d169f04bSDaniel P. Berrange     if (sasl) {
3962d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3963d169f04bSDaniel P. Berrange         goto fail;
3964d169f04bSDaniel P. Berrange     }
3965d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
39663e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
39673e305e4aSDaniel P. Berrange     if (credid) {
39683e305e4aSDaniel P. Berrange         Object *creds;
39693e305e4aSDaniel P. Berrange         if (qemu_opt_get(opts, "tls") ||
39703e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509") ||
39713e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509verify")) {
39723e305e4aSDaniel P. Berrange             error_setg(errp,
3973c62e90afSWolfgang Bumiller                        "'tls-creds' parameter is mutually exclusive with "
39743e305e4aSDaniel P. Berrange                        "'tls', 'x509' and 'x509verify' parameters");
39753e305e4aSDaniel P. Berrange             goto fail;
39763e305e4aSDaniel P. Berrange         }
39773e305e4aSDaniel P. Berrange 
39783e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
39793e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
39803e305e4aSDaniel P. Berrange         if (!creds) {
39813e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
39823e305e4aSDaniel P. Berrange                        credid);
39833e305e4aSDaniel P. Berrange             goto fail;
39843e305e4aSDaniel P. Berrange         }
3985bf01c179SDaniel P. Berrange         vd->tlscreds = (QCryptoTLSCreds *)
39863e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
39873e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
3988bf01c179SDaniel P. Berrange         if (!vd->tlscreds) {
39893e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
39903e305e4aSDaniel P. Berrange                        credid);
39913e305e4aSDaniel P. Berrange             goto fail;
39923e305e4aSDaniel P. Berrange         }
3993bf01c179SDaniel P. Berrange         object_ref(OBJECT(vd->tlscreds));
39943e305e4aSDaniel P. Berrange 
3995bf01c179SDaniel P. Berrange         if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
39963e305e4aSDaniel P. Berrange             error_setg(errp,
39973e305e4aSDaniel P. Berrange                        "Expecting TLS credentials with a server endpoint");
39983e305e4aSDaniel P. Berrange             goto fail;
39993e305e4aSDaniel P. Berrange         }
40003e305e4aSDaniel P. Berrange     } else {
40013e305e4aSDaniel P. Berrange         const char *path;
40023e305e4aSDaniel P. Berrange         bool tls = false, x509 = false, x509verify = false;
40034db14629SGerd Hoffmann         tls  = qemu_opt_get_bool(opts, "tls", false);
40043e305e4aSDaniel P. Berrange         if (tls) {
40054db14629SGerd Hoffmann             path = qemu_opt_get(opts, "x509");
40063e305e4aSDaniel P. Berrange 
40074db14629SGerd Hoffmann             if (path) {
4008a2c72de0SGonglei                 x509 = true;
40093e305e4aSDaniel P. Berrange             } else {
40103e305e4aSDaniel P. Berrange                 path = qemu_opt_get(opts, "x509verify");
40113e305e4aSDaniel P. Berrange                 if (path) {
40123e305e4aSDaniel P. Berrange                     x509 = true;
40133e305e4aSDaniel P. Berrange                     x509verify = true;
40143e305e4aSDaniel P. Berrange                 }
40153e305e4aSDaniel P. Berrange             }
4016bf01c179SDaniel P. Berrange             vd->tlscreds = vnc_display_create_creds(x509,
40173e305e4aSDaniel P. Berrange                                                     x509verify,
40183e305e4aSDaniel P. Berrange                                                     path,
4019bf01c179SDaniel P. Berrange                                                     vd->id,
40203e305e4aSDaniel P. Berrange                                                     errp);
4021bf01c179SDaniel P. Berrange             if (!vd->tlscreds) {
40221ce52c78SPaolo Bonzini                 goto fail;
40233e230dd2SCorentin Chary             }
40243e230dd2SCorentin Chary         }
4025d169f04bSDaniel P. Berrange     }
40264db14629SGerd Hoffmann     acl = qemu_opt_get_bool(opts, "acl", false);
40274db14629SGerd Hoffmann 
40284db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
40294db14629SGerd Hoffmann     if (share) {
40304db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
4031bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_IGNORE;
40324db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
4033bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
40344db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
4035bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
40368cf36489SGerd Hoffmann         } else {
40372d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
40381ce52c78SPaolo Bonzini             goto fail;
40398cf36489SGerd Hoffmann         }
40404db14629SGerd Hoffmann     } else {
4041bf01c179SDaniel P. Berrange         vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
40423e230dd2SCorentin Chary     }
4043bf01c179SDaniel P. Berrange     vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
40443e230dd2SCorentin Chary 
40454db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
4046bf01c179SDaniel P. Berrange     vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
40474db14629SGerd Hoffmann #endif
4048bf01c179SDaniel P. Berrange     vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4049e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
4050e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
4051e22492d3SPeter Lieven      * calculations otherwise */
4052bf01c179SDaniel P. Berrange     if (!vd->lossy) {
4053bf01c179SDaniel P. Berrange         vd->non_adaptive = true;
4054e22492d3SPeter Lieven     }
4055e22492d3SPeter Lieven 
40563e305e4aSDaniel P. Berrange     if (acl) {
4057bf01c179SDaniel P. Berrange         if (strcmp(vd->id, "default") == 0) {
4058bf01c179SDaniel P. Berrange             vd->tlsaclname = g_strdup("vnc.x509dname");
4059c8496408SGerd Hoffmann         } else {
4060bf01c179SDaniel P. Berrange             vd->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vd->id);
4061c8496408SGerd Hoffmann         }
4062bf01c179SDaniel P. Berrange         qemu_acl_init(vd->tlsaclname);
40633e230dd2SCorentin Chary     }
40643e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
40653e230dd2SCorentin Chary     if (acl && sasl) {
4066c8496408SGerd Hoffmann         char *aclname;
4067c8496408SGerd Hoffmann 
4068bf01c179SDaniel P. Berrange         if (strcmp(vd->id, "default") == 0) {
4069c8496408SGerd Hoffmann             aclname = g_strdup("vnc.username");
4070c8496408SGerd Hoffmann         } else {
4071bf01c179SDaniel P. Berrange             aclname = g_strdup_printf("vnc.%s.username", vd->id);
4072c8496408SGerd Hoffmann         }
4073bf01c179SDaniel P. Berrange         vd->sasl.acl = qemu_acl_init(aclname);
4074c8496408SGerd Hoffmann         g_free(aclname);
40753e230dd2SCorentin Chary     }
40763e230dd2SCorentin Chary #endif
40773e230dd2SCorentin Chary 
4078eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4079eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4080eda24e18SDaniel P. Berrange                                sasl, false, errp) < 0) {
4081eda24e18SDaniel P. Berrange         goto fail;
4082eda24e18SDaniel P. Berrange     }
40837364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4084eda24e18SDaniel P. Berrange 
4085eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4086eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4087eda24e18SDaniel P. Berrange                                sasl, true, errp) < 0) {
40883e305e4aSDaniel P. Berrange         goto fail;
40893e305e4aSDaniel P. Berrange     }
40907364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
40913e230dd2SCorentin Chary 
40923e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
40933e230dd2SCorentin Chary     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
40942d55f0e8SPaolo Bonzini         error_setg(errp, "Failed to initialize SASL auth: %s",
40953e230dd2SCorentin Chary                    sasl_errstring(saslErr, NULL, NULL));
40961ce52c78SPaolo Bonzini         goto fail;
40973e230dd2SCorentin Chary     }
40983e230dd2SCorentin Chary #endif
4099bf01c179SDaniel P. Berrange     vd->lock_key_sync = lock_key_sync;
4100a54f0d2bSPierre Ossman     if (lock_key_sync) {
4101a54f0d2bSPierre Ossman         vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4102a54f0d2bSPierre Ossman     }
4103a54f0d2bSPierre Ossman     vd->ledstate = 0;
4104bf01c179SDaniel P. Berrange     vd->key_delay_ms = key_delay_ms;
41053e230dd2SCorentin Chary 
41061d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
41071d0d59feSGerd Hoffmann     if (device_id) {
41081d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
4109f2c1d54cSGerd Hoffmann         Error *err = NULL;
41101d0d59feSGerd Hoffmann 
4111f2c1d54cSGerd Hoffmann         con = qemu_console_lookup_by_device_name(device_id, head, &err);
4112f2c1d54cSGerd Hoffmann         if (err) {
4113f2c1d54cSGerd Hoffmann             error_propagate(errp, err);
41141d0d59feSGerd Hoffmann             goto fail;
41151d0d59feSGerd Hoffmann         }
41161d0d59feSGerd Hoffmann     } else {
41171d0d59feSGerd Hoffmann         con = NULL;
41181d0d59feSGerd Hoffmann     }
41191d0d59feSGerd Hoffmann 
4120bf01c179SDaniel P. Berrange     if (con != vd->dcl.con) {
4121bf01c179SDaniel P. Berrange         unregister_displaychangelistener(&vd->dcl);
4122bf01c179SDaniel P. Berrange         vd->dcl.con = con;
4123bf01c179SDaniel P. Berrange         register_displaychangelistener(&vd->dcl);
41241d0d59feSGerd Hoffmann     }
41251d0d59feSGerd Hoffmann 
4126fa03cb7fSMarc-André Lureau     if (saddr == NULL) {
4127fa03cb7fSMarc-André Lureau         goto cleanup;
4128fa03cb7fSMarc-André Lureau     }
4129fa03cb7fSMarc-André Lureau 
41303e230dd2SCorentin Chary     if (reverse) {
4131396f935aSDaniel P. Berrange         if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4132e0d03b8cSDaniel P. Berrange             goto fail;
41333e230dd2SCorentin Chary         }
41343e230dd2SCorentin Chary     } else {
4135396f935aSDaniel P. Berrange         if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
41363d00ac1aSCole Robinson             goto fail;
41373d00ac1aSCole Robinson         }
41383e230dd2SCorentin Chary     }
4139e0d03b8cSDaniel P. Berrange 
4140275e0d61SDaniel P. Berrange     if (qemu_opt_get(opts, "to")) {
4141bf01c179SDaniel P. Berrange         vnc_display_print_local_addr(vd);
414233df7bf3SPaolo Bonzini     }
414333df7bf3SPaolo Bonzini 
4144396f935aSDaniel P. Berrange  cleanup:
41459f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&saddr, &nsaddr);
41469f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&wsaddr, &nwsaddr);
41472d55f0e8SPaolo Bonzini     return;
41481ce52c78SPaolo Bonzini 
41491ce52c78SPaolo Bonzini fail:
41504ee74fa7SDaniel P. Berrange     vnc_display_close(vd);
4151396f935aSDaniel P. Berrange     goto cleanup;
41523e230dd2SCorentin Chary }
415313661089SDaniel P. Berrange 
415414f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
415513661089SDaniel P. Berrange {
4156bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
415704d2529dSDaniel P. Berrange     QIOChannelSocket *sioc;
415813661089SDaniel P. Berrange 
4159bf01c179SDaniel P. Berrange     if (!vd) {
4160d616ccc5SGerd Hoffmann         return;
4161d616ccc5SGerd Hoffmann     }
416204d2529dSDaniel P. Berrange 
416304d2529dSDaniel P. Berrange     sioc = qio_channel_socket_new_fd(csock, NULL);
416404d2529dSDaniel P. Berrange     if (sioc) {
416510bcfe58SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4166bf01c179SDaniel P. Berrange         vnc_connect(vd, sioc, skipauth, false);
416704d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
416804d2529dSDaniel P. Berrange     }
416913661089SDaniel P. Berrange }
41704db14629SGerd Hoffmann 
41719634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
41722779672fSGonglei {
41732779672fSGonglei     int i = 2;
41742779672fSGonglei     char *id;
41752779672fSGonglei 
41762779672fSGonglei     id = g_strdup("default");
41772779672fSGonglei     while (qemu_opts_find(olist, id)) {
41782779672fSGonglei         g_free(id);
41792779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
41802779672fSGonglei     }
41812779672fSGonglei     qemu_opts_set_id(opts, id);
41822779672fSGonglei }
41832779672fSGonglei 
418470b94331SMarkus Armbruster QemuOpts *vnc_parse(const char *str, Error **errp)
41854db14629SGerd Hoffmann {
41864db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
418770b94331SMarkus Armbruster     QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
418881607cbfSGonglei     const char *id;
41894db14629SGerd Hoffmann 
419081607cbfSGonglei     if (!opts) {
419181607cbfSGonglei         return NULL;
419281607cbfSGonglei     }
419381607cbfSGonglei 
419481607cbfSGonglei     id = qemu_opts_id(opts);
41954db14629SGerd Hoffmann     if (!id) {
41964db14629SGerd Hoffmann         /* auto-assign id if not present */
41972779672fSGonglei         vnc_auto_assign_id(olist, opts);
41989634f4e3SGerd Hoffmann     }
41999634f4e3SGerd Hoffmann     return opts;
42004db14629SGerd Hoffmann }
42014db14629SGerd Hoffmann 
420228d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
42039634f4e3SGerd Hoffmann {
42049634f4e3SGerd Hoffmann     Error *local_err = NULL;
42059634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
42069634f4e3SGerd Hoffmann 
42079634f4e3SGerd Hoffmann     assert(id);
42084db14629SGerd Hoffmann     vnc_display_init(id);
42094db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
42104db14629SGerd Hoffmann     if (local_err != NULL) {
4211c29b77f9SMarkus Armbruster         error_reportf_err(local_err, "Failed to start VNC server: ");
42124db14629SGerd Hoffmann         exit(1);
42134db14629SGerd Hoffmann     }
42144db14629SGerd Hoffmann     return 0;
42154db14629SGerd Hoffmann }
42164db14629SGerd Hoffmann 
42174db14629SGerd Hoffmann static void vnc_register_config(void)
42184db14629SGerd Hoffmann {
42194db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
42204db14629SGerd Hoffmann }
422134294e2fSEduardo Habkost opts_init(vnc_register_config);
4222