xref: /openbmc/qemu/ui/vnc.c (revision d49b87f0d1e0520443a990fc610d0f02bc63c556)
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"
33922a01a0SMarkus Armbruster #include "qemu/option.h"
341de7afc9SPaolo Bonzini #include "qemu/sockets.h"
351de7afc9SPaolo Bonzini #include "qemu/timer.h"
361de7afc9SPaolo Bonzini #include "qemu/acl.h"
374db14629SGerd Hoffmann #include "qemu/config-file.h"
38e688df6bSMarkus Armbruster #include "qapi/error.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 
23113e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
2324ee74fa7SDaniel P. Berrange         return NULL;
2334ee74fa7SDaniel P. Berrange     }
2344ee74fa7SDaniel P. Berrange 
2353e7f136dSDaniel P. Berrange     info = g_malloc0(sizeof(*info));
23613e1d0e7SDaniel P. Berrange     vnc_init_basic_info_from_server_addr(vd->listener->sioc[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 
38213e1d0e7SDaniel P. Berrange     if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
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 
39113e1d0e7SDaniel P. Berrange         addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
39213e1d0e7SDaniel P. Berrange                                                     errp);
39304d2529dSDaniel P. Berrange         if (!addr) {
3942b54aa87SLuiz Capitulino             goto out_error;
3952b54aa87SLuiz Capitulino         }
3963e230dd2SCorentin Chary 
39704d2529dSDaniel P. Berrange         switch (addr->type) {
398bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_INET:
399bd269ebcSMarkus Armbruster             info->host = g_strdup(addr->u.inet.host);
400bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.inet.port);
401bd269ebcSMarkus Armbruster             if (addr->u.inet.ipv6) {
40204d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
40304d2529dSDaniel P. Berrange             } else {
40404d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
40504d2529dSDaniel P. Berrange             }
40604d2529dSDaniel P. Berrange             break;
40704d2529dSDaniel P. Berrange 
408bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_UNIX:
40904d2529dSDaniel P. Berrange             info->host = g_strdup("");
410bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.q_unix.path);
41104d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
41204d2529dSDaniel P. Berrange             break;
41304d2529dSDaniel P. Berrange 
414bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_VSOCK:
415bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_FD:
416a6c76285SMarkus Armbruster             error_setg(errp, "Unsupported socket address type %s",
417977c736fSMarkus Armbruster                        SocketAddressType_str(addr->type));
4182b54aa87SLuiz Capitulino             goto out_error;
419a6c76285SMarkus Armbruster         default:
420a6c76285SMarkus Armbruster             abort();
4213e230dd2SCorentin Chary         }
4222b54aa87SLuiz Capitulino 
4232b54aa87SLuiz Capitulino         info->has_host = true;
4242b54aa87SLuiz Capitulino         info->has_service = true;
4252b54aa87SLuiz Capitulino         info->has_family = true;
4262b54aa87SLuiz Capitulino 
4272b54aa87SLuiz Capitulino         info->has_auth = true;
428d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4293e230dd2SCorentin Chary     }
4302b54aa87SLuiz Capitulino 
431bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4322b54aa87SLuiz Capitulino     return info;
4332b54aa87SLuiz Capitulino 
4342b54aa87SLuiz Capitulino out_error:
435bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4362b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4372b54aa87SLuiz Capitulino     return NULL;
4383e230dd2SCorentin Chary }
4393e230dd2SCorentin Chary 
4402a7e6857SDaniel P. Berrange 
4412a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4422a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4432a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4442a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt);
4452a7e6857SDaniel P. Berrange 
4462a7e6857SDaniel P. Berrange static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
4474478aa76SGerd Hoffmann                                                   bool websocket,
4482a7e6857SDaniel P. Berrange                                                   int auth,
4492a7e6857SDaniel P. Berrange                                                   int subauth,
4502a7e6857SDaniel P. Berrange                                                   VncServerInfo2List *prev)
451df887684SGerd Hoffmann {
4522a7e6857SDaniel P. Berrange     VncServerInfo2List *list;
4532a7e6857SDaniel P. Berrange     VncServerInfo2 *info;
45404d2529dSDaniel P. Berrange     Error *err = NULL;
455bd269ebcSMarkus Armbruster     SocketAddress *addr;
456df887684SGerd Hoffmann 
45704d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, &err);
45804d2529dSDaniel P. Berrange     if (!addr) {
45904d2529dSDaniel P. Berrange         error_free(err);
460df887684SGerd Hoffmann         return prev;
461df887684SGerd Hoffmann     }
462df887684SGerd Hoffmann 
4632a7e6857SDaniel P. Berrange     info = g_new0(VncServerInfo2, 1);
4642a7e6857SDaniel P. Berrange     vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
465bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
46604d2529dSDaniel P. Berrange     if (err) {
4672a7e6857SDaniel P. Berrange         qapi_free_VncServerInfo2(info);
46804d2529dSDaniel P. Berrange         error_free(err);
46904d2529dSDaniel P. Berrange         return prev;
47004d2529dSDaniel P. Berrange     }
4714478aa76SGerd Hoffmann     info->websocket = websocket;
472df887684SGerd Hoffmann 
4732a7e6857SDaniel P. Berrange     qmp_query_auth(auth, subauth, &info->auth,
4742a7e6857SDaniel P. Berrange                    &info->vencrypt, &info->has_vencrypt);
4752a7e6857SDaniel P. Berrange 
4762a7e6857SDaniel P. Berrange     list = g_new0(VncServerInfo2List, 1);
477df887684SGerd Hoffmann     list->value = info;
478df887684SGerd Hoffmann     list->next = prev;
479df887684SGerd Hoffmann     return list;
480df887684SGerd Hoffmann }
481df887684SGerd Hoffmann 
4822a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4832a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4842a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4852a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt)
486df887684SGerd Hoffmann {
4872a7e6857SDaniel P. Berrange     switch (auth) {
488df887684SGerd Hoffmann     case VNC_AUTH_VNC:
4892a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VNC;
490df887684SGerd Hoffmann         break;
491df887684SGerd Hoffmann     case VNC_AUTH_RA2:
4922a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2;
493df887684SGerd Hoffmann         break;
494df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
4952a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
496df887684SGerd Hoffmann         break;
497df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
4982a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
499df887684SGerd Hoffmann         break;
500df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
5012a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
502df887684SGerd Hoffmann         break;
503df887684SGerd Hoffmann     case VNC_AUTH_TLS:
5042a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TLS;
505df887684SGerd Hoffmann         break;
506df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
5072a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
5082a7e6857SDaniel P. Berrange         *qmp_has_vencrypt = true;
5092a7e6857SDaniel P. Berrange         switch (subauth) {
510df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
5112a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
512df887684SGerd Hoffmann             break;
513df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
5142a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
515df887684SGerd Hoffmann             break;
516df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
5172a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
518df887684SGerd Hoffmann             break;
519df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
5202a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
521df887684SGerd Hoffmann             break;
522df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
5232a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
524df887684SGerd Hoffmann             break;
525df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
5262a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
527df887684SGerd Hoffmann             break;
528df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
5292a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
530df887684SGerd Hoffmann             break;
531df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
5322a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
533df887684SGerd Hoffmann             break;
534df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
5352a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
536df887684SGerd Hoffmann             break;
537df887684SGerd Hoffmann         default:
5382a7e6857SDaniel P. Berrange             *qmp_has_vencrypt = false;
539df887684SGerd Hoffmann             break;
540df887684SGerd Hoffmann         }
541df887684SGerd Hoffmann         break;
542df887684SGerd Hoffmann     case VNC_AUTH_SASL:
5432a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_SASL;
544df887684SGerd Hoffmann         break;
545df887684SGerd Hoffmann     case VNC_AUTH_NONE:
546df887684SGerd Hoffmann     default:
5472a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_NONE;
548df887684SGerd Hoffmann         break;
549df887684SGerd Hoffmann     }
550df887684SGerd Hoffmann }
551df887684SGerd Hoffmann 
552df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
553df887684SGerd Hoffmann {
554df887684SGerd Hoffmann     VncInfo2List *item, *prev = NULL;
555df887684SGerd Hoffmann     VncInfo2 *info;
556df887684SGerd Hoffmann     VncDisplay *vd;
557df887684SGerd Hoffmann     DeviceState *dev;
5584ee74fa7SDaniel P. Berrange     size_t i;
559df887684SGerd Hoffmann 
560df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
561df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
562df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
563df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
5642a7e6857SDaniel P. Berrange         qmp_query_auth(vd->auth, vd->subauth, &info->auth,
5652a7e6857SDaniel P. Berrange                        &info->vencrypt, &info->has_vencrypt);
566df887684SGerd Hoffmann         if (vd->dcl.con) {
567df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
568df887684SGerd Hoffmann                                                   "device", NULL));
569df887684SGerd Hoffmann             info->has_display = true;
570df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
571df887684SGerd Hoffmann         }
57213e1d0e7SDaniel P. Berrange         for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
57304d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57413e1d0e7SDaniel P. Berrange                 vd->listener->sioc[i], false, vd->auth, vd->subauth,
57513e1d0e7SDaniel P. Berrange                 info->server);
576df887684SGerd Hoffmann         }
57713e1d0e7SDaniel P. Berrange         for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
57804d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57913e1d0e7SDaniel P. Berrange                 vd->wslistener->sioc[i], true, vd->ws_auth,
5804ee74fa7SDaniel P. Berrange                 vd->ws_subauth, info->server);
581df887684SGerd Hoffmann         }
582df887684SGerd Hoffmann 
583df887684SGerd Hoffmann         item = g_new0(VncInfo2List, 1);
584df887684SGerd Hoffmann         item->value = info;
585df887684SGerd Hoffmann         item->next = prev;
586df887684SGerd Hoffmann         prev = item;
587df887684SGerd Hoffmann     }
588df887684SGerd Hoffmann     return prev;
589df887684SGerd Hoffmann }
590df887684SGerd Hoffmann 
5913e230dd2SCorentin Chary /* TODO
5923e230dd2SCorentin Chary    1) Get the queue working for IO.
5933e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
5943e230dd2SCorentin Chary       and not totally invalidated
5953e230dd2SCorentin Chary    3) resolutions > 1024
5963e230dd2SCorentin Chary */
5973e230dd2SCorentin Chary 
5986af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty);
5993e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
6003e230dd2SCorentin Chary 
6013e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
6023e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
6033e230dd2SCorentin Chary                                        int x_position, int y_position,
6043e230dd2SCorentin Chary                                        int w, int h);
6050f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
6063e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
6073e230dd2SCorentin Chary 
608d05959c2SGerd Hoffmann static int vnc_width(VncDisplay *vd)
609d05959c2SGerd Hoffmann {
610d05959c2SGerd Hoffmann     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
611d05959c2SGerd Hoffmann                                        VNC_DIRTY_PIXELS_PER_BIT));
612d05959c2SGerd Hoffmann }
613d05959c2SGerd Hoffmann 
614d05959c2SGerd Hoffmann static int vnc_height(VncDisplay *vd)
615d05959c2SGerd Hoffmann {
616d05959c2SGerd Hoffmann     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
617d05959c2SGerd Hoffmann }
618d05959c2SGerd Hoffmann 
619bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
620bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
621f7b3d68cSGerd Hoffmann                                VncDisplay *vd,
622f7b3d68cSGerd Hoffmann                                int x, int y, int w, int h)
623f7b3d68cSGerd Hoffmann {
624f7b3d68cSGerd Hoffmann     int width = vnc_width(vd);
625f7b3d68cSGerd Hoffmann     int height = vnc_height(vd);
626f7b3d68cSGerd Hoffmann 
62791937225SPeter Lieven     /* this is needed this to ensure we updated all affected
62891937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
629b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
630b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6313e230dd2SCorentin Chary 
6329f64916dSGerd Hoffmann     x = MIN(x, width);
6339f64916dSGerd Hoffmann     y = MIN(y, height);
6349f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
63591937225SPeter Lieven     h = MIN(y + h, height);
6363e230dd2SCorentin Chary 
637b4c85ddcSPeter Lieven     for (; y < h; y++) {
638bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
63991937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
640b4c85ddcSPeter Lieven     }
6413e230dd2SCorentin Chary }
6423e230dd2SCorentin Chary 
643bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
644bea60dd7SPeter Lieven                            int x, int y, int w, int h)
645bea60dd7SPeter Lieven {
646bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
647bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
648bea60dd7SPeter Lieven 
649f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
650bea60dd7SPeter Lieven }
651bea60dd7SPeter Lieven 
6523e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6533e230dd2SCorentin Chary                             int32_t encoding)
6543e230dd2SCorentin Chary {
6553e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6563e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6573e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6583e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6593e230dd2SCorentin Chary 
6603e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6613e230dd2SCorentin Chary }
6623e230dd2SCorentin Chary 
66332ed2680STim Hardeck 
6643e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
6653e230dd2SCorentin Chary {
66604d2529dSDaniel P. Berrange     if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
6673e230dd2SCorentin Chary         return;
6683e230dd2SCorentin Chary     }
669bea60dd7SPeter Lieven     if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
670bea60dd7SPeter Lieven         vs->client_height == pixman_image_get_height(vs->vd->server)) {
6713e230dd2SCorentin Chary         return;
6723e230dd2SCorentin Chary     }
6734c956bd8SDaniel P. Berrange 
6744c956bd8SDaniel P. Berrange     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
6754c956bd8SDaniel P. Berrange            pixman_image_get_width(vs->vd->server) >= 0);
6764c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
6774c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
678bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
679bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
680bd023f95SCorentin Chary     vnc_lock_output(vs);
6813e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
6823e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
6833e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
6843e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
6853e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
686bd023f95SCorentin Chary     vnc_unlock_output(vs);
6873e230dd2SCorentin Chary     vnc_flush(vs);
6883e230dd2SCorentin Chary }
6893e230dd2SCorentin Chary 
690bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
691bd023f95SCorentin Chary {
692bd023f95SCorentin Chary     VncState *vs;
693bd023f95SCorentin Chary 
694bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
695bd023f95SCorentin Chary         vnc_lock_output(vs);
696bd023f95SCorentin Chary         vs->abort = true;
697bd023f95SCorentin Chary         vnc_unlock_output(vs);
698bd023f95SCorentin Chary     }
699bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
700bd023f95SCorentin Chary         vnc_jobs_join(vs);
701bd023f95SCorentin Chary     }
702bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
703bd023f95SCorentin Chary         vnc_lock_output(vs);
704bd023f95SCorentin Chary         vs->abort = false;
705bd023f95SCorentin Chary         vnc_unlock_output(vs);
706bd023f95SCorentin Chary     }
707bd023f95SCorentin Chary }
708bd023f95SCorentin Chary 
7099f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
7109f64916dSGerd Hoffmann {
7119f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
7129f64916dSGerd Hoffmann }
7139f64916dSGerd Hoffmann 
7149f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
7159f64916dSGerd Hoffmann {
7169f64916dSGerd Hoffmann     uint8_t *ptr;
7179f64916dSGerd Hoffmann 
7189f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
7199f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
7209f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
7219f64916dSGerd Hoffmann     return ptr;
7229f64916dSGerd Hoffmann }
7239f64916dSGerd Hoffmann 
724453f842bSGerd Hoffmann static void vnc_update_server_surface(VncDisplay *vd)
725453f842bSGerd Hoffmann {
726b69a553bSDaniel P. Berrange     int width, height;
727b69a553bSDaniel P. Berrange 
728453f842bSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
729453f842bSGerd Hoffmann     vd->server = NULL;
730453f842bSGerd Hoffmann 
731c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vd->clients)) {
732c7628bffSGerd Hoffmann         return;
733c7628bffSGerd Hoffmann     }
734c7628bffSGerd Hoffmann 
735b69a553bSDaniel P. Berrange     width = vnc_width(vd);
736b69a553bSDaniel P. Berrange     height = vnc_height(vd);
737453f842bSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
738b69a553bSDaniel P. Berrange                                           width, height,
739453f842bSGerd Hoffmann                                           NULL, 0);
740b69a553bSDaniel P. Berrange 
741b69a553bSDaniel P. Berrange     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
742b69a553bSDaniel P. Berrange     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
743b69a553bSDaniel P. Berrange                        width, height);
744453f842bSGerd Hoffmann }
745453f842bSGerd Hoffmann 
746c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
747c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
7483e230dd2SCorentin Chary {
74921ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
7503e230dd2SCorentin Chary     VncState *vs;
7513e230dd2SCorentin Chary 
752bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
753453f842bSGerd Hoffmann     vd->ds = surface;
754bd023f95SCorentin Chary 
7553e230dd2SCorentin Chary     /* server surface */
756453f842bSGerd Hoffmann     vnc_update_server_surface(vd);
7573e230dd2SCorentin Chary 
7583e230dd2SCorentin Chary     /* guest surface */
7599f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
760d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
761d39fa6d8SGerd Hoffmann     vd->guest.format = surface->format;
7623e230dd2SCorentin Chary 
7633e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
7643e230dd2SCorentin Chary         vnc_colordepth(vs);
7653e230dd2SCorentin Chary         vnc_desktop_resize(vs);
7663e230dd2SCorentin Chary         if (vs->vd->cursor) {
7673e230dd2SCorentin Chary             vnc_cursor_define(vs);
7683e230dd2SCorentin Chary         }
769bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
770f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
771b69a553bSDaniel P. Berrange                            vnc_width(vd),
772b69a553bSDaniel P. Berrange                            vnc_height(vd));
773e2b72cb6SDaniel P. Berrange         vnc_update_throttle_offset(vs);
7743e230dd2SCorentin Chary     }
7753e230dd2SCorentin Chary }
7763e230dd2SCorentin Chary 
7773e230dd2SCorentin Chary /* fastest code */
7789f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
7793e230dd2SCorentin Chary                                   void *pixels, int size)
7803e230dd2SCorentin Chary {
7813e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
7823e230dd2SCorentin Chary }
7833e230dd2SCorentin Chary 
7843e230dd2SCorentin Chary /* slowest but generic code. */
7853e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
7863e230dd2SCorentin Chary {
7873e230dd2SCorentin Chary     uint8_t r, g, b;
7883e230dd2SCorentin Chary 
7899f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
7909f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
7919f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
7929f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
7939f64916dSGerd Hoffmann #else
7949f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
7959f64916dSGerd Hoffmann #endif
7969f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
7979f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
7989f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
7999f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
8003e230dd2SCorentin Chary     case 1:
8013e230dd2SCorentin Chary         buf[0] = v;
8023e230dd2SCorentin Chary         break;
8033e230dd2SCorentin Chary     case 2:
8049f64916dSGerd Hoffmann         if (vs->client_be) {
8053e230dd2SCorentin Chary             buf[0] = v >> 8;
8063e230dd2SCorentin Chary             buf[1] = v;
8073e230dd2SCorentin Chary         } else {
8083e230dd2SCorentin Chary             buf[1] = v >> 8;
8093e230dd2SCorentin Chary             buf[0] = v;
8103e230dd2SCorentin Chary         }
8113e230dd2SCorentin Chary         break;
8123e230dd2SCorentin Chary     default:
8133e230dd2SCorentin Chary     case 4:
8149f64916dSGerd Hoffmann         if (vs->client_be) {
8153e230dd2SCorentin Chary             buf[0] = v >> 24;
8163e230dd2SCorentin Chary             buf[1] = v >> 16;
8173e230dd2SCorentin Chary             buf[2] = v >> 8;
8183e230dd2SCorentin Chary             buf[3] = v;
8193e230dd2SCorentin Chary         } else {
8203e230dd2SCorentin Chary             buf[3] = v >> 24;
8213e230dd2SCorentin Chary             buf[2] = v >> 16;
8223e230dd2SCorentin Chary             buf[1] = v >> 8;
8233e230dd2SCorentin Chary             buf[0] = v;
8243e230dd2SCorentin Chary         }
8253e230dd2SCorentin Chary         break;
8263e230dd2SCorentin Chary     }
8273e230dd2SCorentin Chary }
8283e230dd2SCorentin Chary 
8299f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
8303e230dd2SCorentin Chary                                      void *pixels1, int size)
8313e230dd2SCorentin Chary {
8323e230dd2SCorentin Chary     uint8_t buf[4];
8333e230dd2SCorentin Chary 
8349f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
8353e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
8363e230dd2SCorentin Chary         int n, i;
8373e230dd2SCorentin Chary         n = size >> 2;
8383e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
8393e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
8409f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
8413e230dd2SCorentin Chary         }
8423e230dd2SCorentin Chary     }
8433e230dd2SCorentin Chary }
8443e230dd2SCorentin Chary 
8453e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8463e230dd2SCorentin Chary {
8473e230dd2SCorentin Chary     int i;
8483e230dd2SCorentin Chary     uint8_t *row;
8493e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
8503e230dd2SCorentin Chary 
8519f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
8523e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
8539f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
8549f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
8553e230dd2SCorentin Chary     }
8563e230dd2SCorentin Chary     return 1;
8573e230dd2SCorentin Chary }
8583e230dd2SCorentin Chary 
859bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8603e230dd2SCorentin Chary {
8613e230dd2SCorentin Chary     int n = 0;
862de3f7de7SPeter Lieven     bool encode_raw = false;
863de3f7de7SPeter Lieven     size_t saved_offs = vs->output.offset;
8643e230dd2SCorentin Chary 
8653e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
8663e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
8673e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
8683e230dd2SCorentin Chary             break;
8693e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
8703e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
8713e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
8723e230dd2SCorentin Chary             break;
8733e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
8743e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
8753e230dd2SCorentin Chary             break;
876efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
877efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
878efe556adSCorentin Chary             break;
879148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
880148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
881148954faSCorentin Chary             break;
882148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
883148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
884148954faSCorentin Chary             break;
8853e230dd2SCorentin Chary         default:
886de3f7de7SPeter Lieven             encode_raw = true;
8873e230dd2SCorentin Chary             break;
8883e230dd2SCorentin Chary     }
889de3f7de7SPeter Lieven 
890de3f7de7SPeter Lieven     /* If the client has the same pixel format as our internal buffer and
891de3f7de7SPeter Lieven      * a RAW encoding would need less space fall back to RAW encoding to
892de3f7de7SPeter Lieven      * save bandwidth and processing power in the client. */
893de3f7de7SPeter Lieven     if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
894de3f7de7SPeter Lieven         12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
895de3f7de7SPeter Lieven         vs->output.offset = saved_offs;
896de3f7de7SPeter Lieven         encode_raw = true;
897de3f7de7SPeter Lieven     }
898de3f7de7SPeter Lieven 
899de3f7de7SPeter Lieven     if (encode_raw) {
900de3f7de7SPeter Lieven         vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
901de3f7de7SPeter Lieven         n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
902de3f7de7SPeter Lieven     }
903de3f7de7SPeter Lieven 
9043e230dd2SCorentin Chary     return n;
9053e230dd2SCorentin Chary }
9063e230dd2SCorentin Chary 
9077c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9087c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9093e230dd2SCorentin Chary {
9103e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9113e230dd2SCorentin Chary }
9123e230dd2SCorentin Chary 
9133e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
9143e230dd2SCorentin Chary {
9153e230dd2SCorentin Chary     QEMUCursor *c = vs->vd->cursor;
9163e230dd2SCorentin Chary     int isize;
9173e230dd2SCorentin Chary 
9183e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
919d01f9595SCorentin Chary         vnc_lock_output(vs);
9203e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
9213e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
9223e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
9233e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
9243e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
9259f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
9269f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
9273e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
928d01f9595SCorentin Chary         vnc_unlock_output(vs);
9293e230dd2SCorentin Chary         return 0;
9303e230dd2SCorentin Chary     }
9313e230dd2SCorentin Chary     return -1;
9323e230dd2SCorentin Chary }
9333e230dd2SCorentin Chary 
9347c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
9357c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
9363e230dd2SCorentin Chary {
937d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
9383e230dd2SCorentin Chary     VncState *vs;
9393e230dd2SCorentin Chary 
9403e230dd2SCorentin Chary     cursor_put(vd->cursor);
9417267c094SAnthony Liguori     g_free(vd->cursor_mask);
9423e230dd2SCorentin Chary 
9433e230dd2SCorentin Chary     vd->cursor = c;
9443e230dd2SCorentin Chary     cursor_get(vd->cursor);
9453e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
9467267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
9473e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
9483e230dd2SCorentin Chary 
9493e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
9503e230dd2SCorentin Chary         vnc_cursor_define(vs);
9513e230dd2SCorentin Chary     }
9523e230dd2SCorentin Chary }
9533e230dd2SCorentin Chary 
9544769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
9556c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
9563e230dd2SCorentin Chary {
9573e230dd2SCorentin Chary     int h;
9583e230dd2SCorentin Chary 
9596c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
960bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
9613e230dd2SCorentin Chary             break;
962bc2429b9SCorentin Chary         }
963863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
9643e230dd2SCorentin Chary     }
9653e230dd2SCorentin Chary 
9663e230dd2SCorentin Chary     return h;
9673e230dd2SCorentin Chary }
9683e230dd2SCorentin Chary 
969e2b72cb6SDaniel P. Berrange /*
970e2b72cb6SDaniel P. Berrange  * Figure out how much pending data we should allow in the output
971e2b72cb6SDaniel P. Berrange  * buffer before we throttle incremental display updates, and/or
972e2b72cb6SDaniel P. Berrange  * drop audio samples.
973e2b72cb6SDaniel P. Berrange  *
974e2b72cb6SDaniel P. Berrange  * We allow for equiv of 1 full display's worth of FB updates,
975e2b72cb6SDaniel P. Berrange  * and 1 second of audio samples. If audio backlog was larger
976e2b72cb6SDaniel P. Berrange  * than that the client would already suffering awful audio
977e2b72cb6SDaniel P. Berrange  * glitches, so dropping samples is no worse really).
978e2b72cb6SDaniel P. Berrange  */
979e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs)
980e2b72cb6SDaniel P. Berrange {
981e2b72cb6SDaniel P. Berrange     size_t offset =
982e2b72cb6SDaniel P. Berrange         vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
983e2b72cb6SDaniel P. Berrange 
984e2b72cb6SDaniel P. Berrange     if (vs->audio_cap) {
985e2b72cb6SDaniel P. Berrange         int freq = vs->as.freq;
986e2b72cb6SDaniel P. Berrange         /* We don't limit freq when reading settings from client, so
987e2b72cb6SDaniel P. Berrange          * it could be upto MAX_INT in size. 48khz is a sensible
988e2b72cb6SDaniel P. Berrange          * upper bound for trustworthy clients */
989e2b72cb6SDaniel P. Berrange         int bps;
990e2b72cb6SDaniel P. Berrange         if (freq > 48000) {
991e2b72cb6SDaniel P. Berrange             freq = 48000;
992e2b72cb6SDaniel P. Berrange         }
993e2b72cb6SDaniel P. Berrange         switch (vs->as.fmt) {
994e2b72cb6SDaniel P. Berrange         default:
995e2b72cb6SDaniel P. Berrange         case  AUD_FMT_U8:
996e2b72cb6SDaniel P. Berrange         case  AUD_FMT_S8:
997e2b72cb6SDaniel P. Berrange             bps = 1;
998e2b72cb6SDaniel P. Berrange             break;
999e2b72cb6SDaniel P. Berrange         case  AUD_FMT_U16:
1000e2b72cb6SDaniel P. Berrange         case  AUD_FMT_S16:
1001e2b72cb6SDaniel P. Berrange             bps = 2;
1002e2b72cb6SDaniel P. Berrange             break;
1003e2b72cb6SDaniel P. Berrange         case  AUD_FMT_U32:
1004e2b72cb6SDaniel P. Berrange         case  AUD_FMT_S32:
1005e2b72cb6SDaniel P. Berrange             bps = 4;
1006e2b72cb6SDaniel P. Berrange             break;
1007e2b72cb6SDaniel P. Berrange         }
1008e2b72cb6SDaniel P. Berrange         offset += freq * bps * vs->as.nchannels;
1009e2b72cb6SDaniel P. Berrange     }
1010e2b72cb6SDaniel P. Berrange 
1011e2b72cb6SDaniel P. Berrange     /* Put a floor of 1MB on offset, so that if we have a large pending
1012e2b72cb6SDaniel P. Berrange      * buffer and the display is resized to a small size & back again
1013e2b72cb6SDaniel P. Berrange      * we don't suddenly apply a tiny send limit
1014e2b72cb6SDaniel P. Berrange      */
1015e2b72cb6SDaniel P. Berrange     offset = MAX(offset, 1024 * 1024);
1016e2b72cb6SDaniel P. Berrange 
10176aa22a29SDaniel P. Berrange     if (vs->throttle_output_offset != offset) {
10186aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_threshold(
10196aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
10206aa22a29SDaniel P. Berrange             vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
10216aa22a29SDaniel P. Berrange     }
10226aa22a29SDaniel P. Berrange 
1023e2b72cb6SDaniel P. Berrange     vs->throttle_output_offset = offset;
1024e2b72cb6SDaniel P. Berrange }
1025e2b72cb6SDaniel P. Berrange 
10260bad8342SDaniel P. Berrange static bool vnc_should_update(VncState *vs)
10270bad8342SDaniel P. Berrange {
10280bad8342SDaniel P. Berrange     switch (vs->update) {
10290bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_NONE:
10300bad8342SDaniel P. Berrange         break;
10310bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_INCREMENTAL:
1032e2b72cb6SDaniel P. Berrange         /* Only allow incremental updates if the pending send queue
1033ada8d2e4SDaniel P. Berrange          * is less than the permitted threshold, and the job worker
1034ada8d2e4SDaniel P. Berrange          * is completely idle.
10350bad8342SDaniel P. Berrange          */
1036ada8d2e4SDaniel P. Berrange         if (vs->output.offset < vs->throttle_output_offset &&
1037ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
10380bad8342SDaniel P. Berrange             return true;
10390bad8342SDaniel P. Berrange         }
10406aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_incremental(
10416aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->output.offset);
10420bad8342SDaniel P. Berrange         break;
10430bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_FORCE:
1044ada8d2e4SDaniel P. Berrange         /* Only allow forced updates if the pending send queue
1045ada8d2e4SDaniel P. Berrange          * does not contain a previous forced update, and the
1046ada8d2e4SDaniel P. Berrange          * job worker is completely idle.
1047ada8d2e4SDaniel P. Berrange          *
1048ada8d2e4SDaniel P. Berrange          * Note this means we'll queue a forced update, even if
1049ada8d2e4SDaniel P. Berrange          * the output buffer size is otherwise over the throttle
1050ada8d2e4SDaniel P. Berrange          * output limit.
1051ada8d2e4SDaniel P. Berrange          */
1052ada8d2e4SDaniel P. Berrange         if (vs->force_update_offset == 0 &&
1053ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
10540bad8342SDaniel P. Berrange             return true;
10550bad8342SDaniel P. Berrange         }
10566aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_forced(
10576aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->force_update_offset);
1058ada8d2e4SDaniel P. Berrange         break;
1059ada8d2e4SDaniel P. Berrange     }
10600bad8342SDaniel P. Berrange     return false;
10610bad8342SDaniel P. Berrange }
10620bad8342SDaniel P. Berrange 
10636af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty)
10643e230dd2SCorentin Chary {
10653e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
1066bd023f95SCorentin Chary     VncJob *job;
10673e230dd2SCorentin Chary     int y;
10682f487a3dSPeter Lieven     int height, width;
1069bd023f95SCorentin Chary     int n = 0;
1070bd023f95SCorentin Chary 
1071b939eb89SDaniel P. Berrange     if (vs->disconnecting) {
1072b939eb89SDaniel P. Berrange         vnc_disconnect_finish(vs);
1073b939eb89SDaniel P. Berrange         return 0;
1074b939eb89SDaniel P. Berrange     }
1075b939eb89SDaniel P. Berrange 
1076b939eb89SDaniel P. Berrange     vs->has_dirty += has_dirty;
10770bad8342SDaniel P. Berrange     if (!vnc_should_update(vs)) {
10783e230dd2SCorentin Chary         return 0;
1079b939eb89SDaniel P. Berrange     }
10803e230dd2SCorentin Chary 
1081fef1bbadSDaniel P. Berrange     if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
10823e230dd2SCorentin Chary         return 0;
1083b939eb89SDaniel P. Berrange     }
10843e230dd2SCorentin Chary 
10853e230dd2SCorentin Chary     /*
10863e230dd2SCorentin Chary      * Send screen updates to the vnc client using the server
10873e230dd2SCorentin Chary      * surface and server dirty map.  guest surface updates
10883e230dd2SCorentin Chary      * happening in parallel don't disturb us, the next pass will
10893e230dd2SCorentin Chary      * send them to the client.
10903e230dd2SCorentin Chary      */
1091bd023f95SCorentin Chary     job = vnc_job_new(vs);
10923e230dd2SCorentin Chary 
1093bea60dd7SPeter Lieven     height = pixman_image_get_height(vd->server);
1094bea60dd7SPeter Lieven     width = pixman_image_get_width(vd->server);
10953e230dd2SCorentin Chary 
109612b316d4SPeter Lieven     y = 0;
109712b316d4SPeter Lieven     for (;;) {
109812b316d4SPeter Lieven         int x, h;
109912b316d4SPeter Lieven         unsigned long x2;
110012b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
110112b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(vs),
110212b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(vs));
110312b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(vs)) {
110412b316d4SPeter Lieven             /* no more dirty bits */
110512b316d4SPeter Lieven             break;
11063e230dd2SCorentin Chary         }
110712b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(vs);
110812b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(vs);
110912b316d4SPeter Lieven         x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
111012b316d4SPeter Lieven                                 VNC_DIRTY_BPL(vs), x);
111112b316d4SPeter Lieven         bitmap_clear(vs->dirty[y], x, x2 - x);
111212b316d4SPeter Lieven         h = find_and_clear_dirty_height(vs, y, x, x2, height);
11132f487a3dSPeter Lieven         x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
11142f487a3dSPeter Lieven         if (x2 > x) {
111512b316d4SPeter Lieven             n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
111612b316d4SPeter Lieven                                   (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
11173e230dd2SCorentin Chary         }
11180e7d6f60SPeter Lieven         if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
11190e7d6f60SPeter Lieven             y += h;
11200e7d6f60SPeter Lieven             if (y == height) {
11210e7d6f60SPeter Lieven                 break;
11220e7d6f60SPeter Lieven             }
11230e7d6f60SPeter Lieven         }
11242f487a3dSPeter Lieven     }
1125bd023f95SCorentin Chary 
1126ada8d2e4SDaniel P. Berrange     vs->job_update = vs->update;
1127728a7ac9SDaniel P. Berrange     vs->update = VNC_STATE_UPDATE_NONE;
1128ada8d2e4SDaniel P. Berrange     vnc_job_push(job);
112963658280SGerd Hoffmann     vs->has_dirty = 0;
1130bd023f95SCorentin Chary     return n;
11313e230dd2SCorentin Chary }
11323e230dd2SCorentin Chary 
11333e230dd2SCorentin Chary /* audio */
11343e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
11353e230dd2SCorentin Chary {
11363e230dd2SCorentin Chary     VncState *vs = opaque;
11373e230dd2SCorentin Chary 
11383e230dd2SCorentin Chary     switch (cmd) {
11393e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1140bd023f95SCorentin Chary         vnc_lock_output(vs);
11413e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11423e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11433e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1144bd023f95SCorentin Chary         vnc_unlock_output(vs);
11453e230dd2SCorentin Chary         vnc_flush(vs);
11463e230dd2SCorentin Chary         break;
11473e230dd2SCorentin Chary 
11483e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1149bd023f95SCorentin Chary         vnc_lock_output(vs);
11503e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11513e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11523e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1153bd023f95SCorentin Chary         vnc_unlock_output(vs);
11543e230dd2SCorentin Chary         vnc_flush(vs);
11553e230dd2SCorentin Chary         break;
11563e230dd2SCorentin Chary     }
11573e230dd2SCorentin Chary }
11583e230dd2SCorentin Chary 
11593e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
11603e230dd2SCorentin Chary {
11613e230dd2SCorentin Chary }
11623e230dd2SCorentin Chary 
11633e230dd2SCorentin Chary static void audio_capture(void *opaque, void *buf, int size)
11643e230dd2SCorentin Chary {
11653e230dd2SCorentin Chary     VncState *vs = opaque;
11663e230dd2SCorentin Chary 
1167bd023f95SCorentin Chary     vnc_lock_output(vs);
1168e2b72cb6SDaniel P. Berrange     if (vs->output.offset < vs->throttle_output_offset) {
11693e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11703e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11713e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
11723e230dd2SCorentin Chary         vnc_write_u32(vs, size);
11733e230dd2SCorentin Chary         vnc_write(vs, buf, size);
11746aa22a29SDaniel P. Berrange     } else {
11756aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1176e2b72cb6SDaniel P. Berrange     }
1177bd023f95SCorentin Chary     vnc_unlock_output(vs);
11783e230dd2SCorentin Chary     vnc_flush(vs);
11793e230dd2SCorentin Chary }
11803e230dd2SCorentin Chary 
11813e230dd2SCorentin Chary static void audio_add(VncState *vs)
11823e230dd2SCorentin Chary {
11833e230dd2SCorentin Chary     struct audio_capture_ops ops;
11843e230dd2SCorentin Chary 
11853e230dd2SCorentin Chary     if (vs->audio_cap) {
1186027a79c3SCole Robinson         error_report("audio already running");
11873e230dd2SCorentin Chary         return;
11883e230dd2SCorentin Chary     }
11893e230dd2SCorentin Chary 
11903e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
11913e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
11923e230dd2SCorentin Chary     ops.capture = audio_capture;
11933e230dd2SCorentin Chary 
11943e230dd2SCorentin Chary     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
11953e230dd2SCorentin Chary     if (!vs->audio_cap) {
1196027a79c3SCole Robinson         error_report("Failed to add audio capture");
11973e230dd2SCorentin Chary     }
11983e230dd2SCorentin Chary }
11993e230dd2SCorentin Chary 
12003e230dd2SCorentin Chary static void audio_del(VncState *vs)
12013e230dd2SCorentin Chary {
12023e230dd2SCorentin Chary     if (vs->audio_cap) {
12033e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
12043e230dd2SCorentin Chary         vs->audio_cap = NULL;
12053e230dd2SCorentin Chary     }
12063e230dd2SCorentin Chary }
12073e230dd2SCorentin Chary 
12083e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
12093e230dd2SCorentin Chary {
121004d2529dSDaniel P. Berrange     if (vs->disconnecting) {
12113e230dd2SCorentin Chary         return;
121204d2529dSDaniel P. Berrange     }
1213ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_start(vs, vs->ioc);
12148cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
121504d2529dSDaniel P. Berrange     if (vs->ioc_tag) {
121604d2529dSDaniel P. Berrange         g_source_remove(vs->ioc_tag);
1217a75d6f07SBrandon Carpenter         vs->ioc_tag = 0;
121804d2529dSDaniel P. Berrange     }
121904d2529dSDaniel P. Berrange     qio_channel_close(vs->ioc, NULL);
122004d2529dSDaniel P. Berrange     vs->disconnecting = TRUE;
12213e230dd2SCorentin Chary }
12223e230dd2SCorentin Chary 
12237536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
12243e230dd2SCorentin Chary {
12257d964c9dSCorentin Chary     int i;
12267d964c9dSCorentin Chary 
1227ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_finish(vs, vs->ioc);
1228ad6374c4SDaniel P. Berrange 
1229bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1230bd023f95SCorentin Chary 
1231bd023f95SCorentin Chary     vnc_lock_output(vs);
1232fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
12333e230dd2SCorentin Chary 
12343e230dd2SCorentin Chary     buffer_free(&vs->input);
12353e230dd2SCorentin Chary     buffer_free(&vs->output);
12363e230dd2SCorentin Chary 
1237fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
12383e230dd2SCorentin Chary 
12393e230dd2SCorentin Chary     vnc_zlib_clear(vs);
12403e230dd2SCorentin Chary     vnc_tight_clear(vs);
1241148954faSCorentin Chary     vnc_zrle_clear(vs);
12423e230dd2SCorentin Chary 
12433e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
12443e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
12453e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
12463e230dd2SCorentin Chary     audio_del(vs);
12477bc9318bSGerd Hoffmann     vnc_release_modifiers(vs);
12483e230dd2SCorentin Chary 
124990cd03a3SDaniel P. Berrange     if (vs->mouse_mode_notifier.notify != NULL) {
12506fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
125190cd03a3SDaniel P. Berrange     }
125290cd03a3SDaniel P. Berrange     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1253c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1254c7628bffSGerd Hoffmann         /* last client gone */
1255c7628bffSGerd Hoffmann         vnc_update_server_surface(vs->vd);
1256c7628bffSGerd Hoffmann     }
12573e230dd2SCorentin Chary 
1258bd023f95SCorentin Chary     vnc_unlock_output(vs);
1259bd023f95SCorentin Chary 
1260bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
12616fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1262175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
12636fd8e79aSTim Hardeck     }
1264175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1265175b2a6eSCorentin Chary 
12667d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
12677267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
12687d964c9dSCorentin Chary     }
12697267c094SAnthony Liguori     g_free(vs->lossy_rect);
127004d2529dSDaniel P. Berrange 
127104d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->ioc));
127204d2529dSDaniel P. Berrange     vs->ioc = NULL;
127304d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->sioc));
127404d2529dSDaniel P. Berrange     vs->sioc = NULL;
12757267c094SAnthony Liguori     g_free(vs);
12763e230dd2SCorentin Chary }
12773e230dd2SCorentin Chary 
127830b80fd5SDaniel P. Berrange size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
12793e230dd2SCorentin Chary {
128004d2529dSDaniel P. Berrange     if (ret <= 0) {
128104d2529dSDaniel P. Berrange         if (ret == 0) {
1282ad6374c4SDaniel P. Berrange             trace_vnc_client_eof(vs, vs->ioc);
1283537848eeSMichael Tokarev             vnc_disconnect_start(vs);
128404d2529dSDaniel P. Berrange         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1285ad6374c4SDaniel P. Berrange             trace_vnc_client_io_error(vs, vs->ioc,
1286ad6374c4SDaniel P. Berrange                                       errp ? error_get_pretty(*errp) :
1287ad6374c4SDaniel P. Berrange                                       "Unknown");
1288537848eeSMichael Tokarev             vnc_disconnect_start(vs);
12893e230dd2SCorentin Chary         }
12903e230dd2SCorentin Chary 
129104d2529dSDaniel P. Berrange         if (errp) {
129204d2529dSDaniel P. Berrange             error_free(*errp);
129304d2529dSDaniel P. Berrange             *errp = NULL;
129404d2529dSDaniel P. Berrange         }
12953e230dd2SCorentin Chary         return 0;
12963e230dd2SCorentin Chary     }
12973e230dd2SCorentin Chary     return ret;
12983e230dd2SCorentin Chary }
12993e230dd2SCorentin Chary 
13003e230dd2SCorentin Chary 
13013e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
13023e230dd2SCorentin Chary {
13033e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
13043e230dd2SCorentin Chary     vnc_disconnect_start(vs);
13053e230dd2SCorentin Chary }
13063e230dd2SCorentin Chary 
13073e305e4aSDaniel P. Berrange 
13083e230dd2SCorentin Chary /*
13093e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
13103e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
13113e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
13123e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
13133e230dd2SCorentin Chary  *
13143e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
13153e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
13163e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
13173e230dd2SCorentin Chary  * is active
13183e230dd2SCorentin Chary  *
13193e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13203e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
132130b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
13223e230dd2SCorentin Chary  */
132330b80fd5SDaniel P. Berrange size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
13243e230dd2SCorentin Chary {
132504d2529dSDaniel P. Berrange     Error *err = NULL;
1326fdd1ab6aSDaniel P. Berrange     ssize_t ret;
132704d2529dSDaniel P. Berrange     ret = qio_channel_write(
132804d2529dSDaniel P. Berrange         vs->ioc, (const char *)data, datalen, &err);
13293e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
133004d2529dSDaniel P. Berrange     return vnc_client_io_error(vs, ret, &err);
13313e230dd2SCorentin Chary }
13323e230dd2SCorentin Chary 
13333e230dd2SCorentin Chary 
13343e230dd2SCorentin Chary /*
13353e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
13363e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
13373e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
13383e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
13393e230dd2SCorentin Chary  *
13403e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13413e230dd2SCorentin Chary  * the buffered output data if the socket would block.  Returns
134230b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
13433e230dd2SCorentin Chary  */
134430b80fd5SDaniel P. Berrange static size_t vnc_client_write_plain(VncState *vs)
13453e230dd2SCorentin Chary {
13466aa22a29SDaniel P. Berrange     size_t offset;
134730b80fd5SDaniel P. Berrange     size_t ret;
13483e230dd2SCorentin Chary 
13493e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13503e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
13513e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
13523e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
13533e230dd2SCorentin Chary 
13543e230dd2SCorentin Chary     if (vs->sasl.conn &&
13553e230dd2SCorentin Chary         vs->sasl.runSSF &&
13563e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
13573e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
13583e230dd2SCorentin Chary         if (ret)
13593e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
13603e230dd2SCorentin Chary     } else
13613e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13623e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
13633e230dd2SCorentin Chary     if (!ret)
13643e230dd2SCorentin Chary         return 0;
13653e230dd2SCorentin Chary 
1366ada8d2e4SDaniel P. Berrange     if (ret >= vs->force_update_offset) {
13676aa22a29SDaniel P. Berrange         if (vs->force_update_offset != 0) {
13686aa22a29SDaniel P. Berrange             trace_vnc_client_unthrottle_forced(vs, vs->ioc);
13696aa22a29SDaniel P. Berrange         }
1370ada8d2e4SDaniel P. Berrange         vs->force_update_offset = 0;
1371ada8d2e4SDaniel P. Berrange     } else {
1372ada8d2e4SDaniel P. Berrange         vs->force_update_offset -= ret;
1373ada8d2e4SDaniel P. Berrange     }
13746aa22a29SDaniel P. Berrange     offset = vs->output.offset;
137532ed2680STim Hardeck     buffer_advance(&vs->output, ret);
13766aa22a29SDaniel P. Berrange     if (offset >= vs->throttle_output_offset &&
13776aa22a29SDaniel P. Berrange         vs->output.offset < vs->throttle_output_offset) {
13786aa22a29SDaniel P. Berrange         trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
13796aa22a29SDaniel P. Berrange     }
13803e230dd2SCorentin Chary 
13813e230dd2SCorentin Chary     if (vs->output.offset == 0) {
138204d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
138304d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
138404d2529dSDaniel P. Berrange         }
138504d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
138604d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
13873e230dd2SCorentin Chary     }
13883e230dd2SCorentin Chary 
13893e230dd2SCorentin Chary     return ret;
13903e230dd2SCorentin Chary }
13913e230dd2SCorentin Chary 
13923e230dd2SCorentin Chary 
13933e230dd2SCorentin Chary /*
13943e230dd2SCorentin Chary  * First function called whenever there is data to be written to
13953e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
13963e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
13973e230dd2SCorentin Chary  */
139804d2529dSDaniel P. Berrange static void vnc_client_write_locked(VncState *vs)
13993e230dd2SCorentin Chary {
14003e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14013e230dd2SCorentin Chary     if (vs->sasl.conn &&
14023e230dd2SCorentin Chary         vs->sasl.runSSF &&
14033e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
14043e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
14053e230dd2SCorentin Chary     } else
14063e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14077536ee4bSTim Hardeck     {
14083e230dd2SCorentin Chary         vnc_client_write_plain(vs);
14093e230dd2SCorentin Chary     }
14107536ee4bSTim Hardeck }
14113e230dd2SCorentin Chary 
141204d2529dSDaniel P. Berrange static void vnc_client_write(VncState *vs)
1413bd023f95SCorentin Chary {
1414bd023f95SCorentin Chary 
1415bd023f95SCorentin Chary     vnc_lock_output(vs);
1416d5f04223SDaniel P. Berrange     if (vs->output.offset) {
141704d2529dSDaniel P. Berrange         vnc_client_write_locked(vs);
141804d2529dSDaniel P. Berrange     } else if (vs->ioc != NULL) {
141904d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
142004d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
142104d2529dSDaniel P. Berrange         }
142204d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
142304d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1424bd023f95SCorentin Chary     }
1425bd023f95SCorentin Chary     vnc_unlock_output(vs);
1426bd023f95SCorentin Chary }
1427bd023f95SCorentin Chary 
14283e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
14293e230dd2SCorentin Chary {
14303e230dd2SCorentin Chary     vs->read_handler = func;
14313e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
14323e230dd2SCorentin Chary }
14333e230dd2SCorentin Chary 
14343e230dd2SCorentin Chary 
14353e230dd2SCorentin Chary /*
14363e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
14373e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
14383e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
14393e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
14403e230dd2SCorentin Chary  *
14413e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
14423e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
14433e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
14443e230dd2SCorentin Chary  * is active
14453e230dd2SCorentin Chary  *
14463e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
14473e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
144830b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
14493e230dd2SCorentin Chary  */
145030b80fd5SDaniel P. Berrange size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
14513e230dd2SCorentin Chary {
1452fdd1ab6aSDaniel P. Berrange     ssize_t ret;
145304d2529dSDaniel P. Berrange     Error *err = NULL;
145404d2529dSDaniel P. Berrange     ret = qio_channel_read(
145504d2529dSDaniel P. Berrange         vs->ioc, (char *)data, datalen, &err);
14563e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
145704d2529dSDaniel P. Berrange     return vnc_client_io_error(vs, ret, &err);
14583e230dd2SCorentin Chary }
14593e230dd2SCorentin Chary 
14603e230dd2SCorentin Chary 
14613e230dd2SCorentin Chary /*
14623e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
14633e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
14643e230dd2SCorentin Chary  * data as possible without blocking.
14653e230dd2SCorentin Chary  *
146630b80fd5SDaniel P. Berrange  * Returns the number of bytes read, which may be less than
146730b80fd5SDaniel P. Berrange  * the requested 'datalen' if the socket would block. Returns
146830b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
14693e230dd2SCorentin Chary  */
147030b80fd5SDaniel P. Berrange static size_t vnc_client_read_plain(VncState *vs)
14713e230dd2SCorentin Chary {
147230b80fd5SDaniel P. Berrange     size_t ret;
14733e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
14743e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
14753e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
14763e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
14773e230dd2SCorentin Chary     if (!ret)
14783e230dd2SCorentin Chary         return 0;
14793e230dd2SCorentin Chary     vs->input.offset += ret;
14803e230dd2SCorentin Chary     return ret;
14813e230dd2SCorentin Chary }
14823e230dd2SCorentin Chary 
1483175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1484175b2a6eSCorentin Chary {
1485175b2a6eSCorentin Chary     VncState *vs = opaque;
1486175b2a6eSCorentin Chary 
1487175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1488175b2a6eSCorentin Chary }
14893e230dd2SCorentin Chary 
14903e230dd2SCorentin Chary /*
14913e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
14923e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
14933e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
1494ea697449SDaniel P. Berrange  * Returns 0 on success, -1 if client disconnected
14953e230dd2SCorentin Chary  */
1496ea697449SDaniel P. Berrange static int vnc_client_read(VncState *vs)
14973e230dd2SCorentin Chary {
149830b80fd5SDaniel P. Berrange     size_t ret;
14993e230dd2SCorentin Chary 
15003e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
15013e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
15023e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
15033e230dd2SCorentin Chary     else
15043e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
15053e230dd2SCorentin Chary         ret = vnc_client_read_plain(vs);
15063e230dd2SCorentin Chary     if (!ret) {
150704d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15083e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1509ea697449SDaniel P. Berrange             return -1;
151004d2529dSDaniel P. Berrange         }
1511ea697449SDaniel P. Berrange         return 0;
15123e230dd2SCorentin Chary     }
15133e230dd2SCorentin Chary 
15143e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
15153e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
15163e230dd2SCorentin Chary         int ret;
15173e230dd2SCorentin Chary 
15183e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
151904d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15203e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1521ea697449SDaniel P. Berrange             return -1;
15223e230dd2SCorentin Chary         }
15233e230dd2SCorentin Chary 
15243e230dd2SCorentin Chary         if (!ret) {
152532ed2680STim Hardeck             buffer_advance(&vs->input, len);
15263e230dd2SCorentin Chary         } else {
15273e230dd2SCorentin Chary             vs->read_handler_expect = ret;
15283e230dd2SCorentin Chary         }
15293e230dd2SCorentin Chary     }
1530ea697449SDaniel P. Berrange     return 0;
15313e230dd2SCorentin Chary }
15323e230dd2SCorentin Chary 
153304d2529dSDaniel P. Berrange gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
153404d2529dSDaniel P. Berrange                        GIOCondition condition, void *opaque)
153504d2529dSDaniel P. Berrange {
153604d2529dSDaniel P. Berrange     VncState *vs = opaque;
153704d2529dSDaniel P. Berrange     if (condition & G_IO_IN) {
1538ea697449SDaniel P. Berrange         if (vnc_client_read(vs) < 0) {
1539*d49b87f0SKlim Kireev             goto end;
1540ea697449SDaniel P. Berrange         }
154104d2529dSDaniel P. Berrange     }
154204d2529dSDaniel P. Berrange     if (condition & G_IO_OUT) {
154304d2529dSDaniel P. Berrange         vnc_client_write(vs);
154404d2529dSDaniel P. Berrange     }
1545*d49b87f0SKlim Kireev end:
1546*d49b87f0SKlim Kireev     if (vs->disconnecting) {
1547*d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1548*d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1549*d49b87f0SKlim Kireev         }
1550*d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1551*d49b87f0SKlim Kireev     }
155204d2529dSDaniel P. Berrange     return TRUE;
155304d2529dSDaniel P. Berrange }
155404d2529dSDaniel P. Berrange 
155504d2529dSDaniel P. Berrange 
1556f887cf16SDaniel P. Berrange /*
1557f887cf16SDaniel P. Berrange  * Scale factor to apply to vs->throttle_output_offset when checking for
1558f887cf16SDaniel P. Berrange  * hard limit. Worst case normal usage could be x2, if we have a complete
1559f887cf16SDaniel P. Berrange  * incremental update and complete forced update in the output buffer.
1560f887cf16SDaniel P. Berrange  * So x3 should be good enough, but we pick x5 to be conservative and thus
1561f887cf16SDaniel P. Berrange  * (hopefully) never trigger incorrectly.
1562f887cf16SDaniel P. Berrange  */
1563f887cf16SDaniel P. Berrange #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1564f887cf16SDaniel P. Berrange 
15653e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
15663e230dd2SCorentin Chary {
1567f887cf16SDaniel P. Berrange     if (vs->disconnecting) {
1568f887cf16SDaniel P. Berrange         return;
1569f887cf16SDaniel P. Berrange     }
1570f887cf16SDaniel P. Berrange     /* Protection against malicious client/guest to prevent our output
1571f887cf16SDaniel P. Berrange      * buffer growing without bound if client stops reading data. This
1572f887cf16SDaniel P. Berrange      * should rarely trigger, because we have earlier throttling code
1573f887cf16SDaniel P. Berrange      * which stops issuing framebuffer updates and drops audio data
1574f887cf16SDaniel P. Berrange      * if the throttle_output_offset value is exceeded. So we only reach
1575f887cf16SDaniel P. Berrange      * this higher level if a huge number of pseudo-encodings get
1576f887cf16SDaniel P. Berrange      * triggered while data can't be sent on the socket.
1577f887cf16SDaniel P. Berrange      *
1578f887cf16SDaniel P. Berrange      * NB throttle_output_offset can be zero during early protocol
1579f887cf16SDaniel P. Berrange      * handshake, or from the job thread's VncState clone
1580f887cf16SDaniel P. Berrange      */
1581f887cf16SDaniel P. Berrange     if (vs->throttle_output_offset != 0 &&
1582f887cf16SDaniel P. Berrange         vs->output.offset > (vs->throttle_output_offset *
1583f887cf16SDaniel P. Berrange                              VNC_THROTTLE_OUTPUT_LIMIT_SCALE)) {
15846aa22a29SDaniel P. Berrange         trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
15856aa22a29SDaniel P. Berrange                                       vs->throttle_output_offset);
1586f887cf16SDaniel P. Berrange         vnc_disconnect_start(vs);
1587f887cf16SDaniel P. Berrange         return;
1588f887cf16SDaniel P. Berrange     }
15893e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
15903e230dd2SCorentin Chary 
159104d2529dSDaniel P. Berrange     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
159204d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
159304d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
159404d2529dSDaniel P. Berrange         }
159504d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
159604d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
15973e230dd2SCorentin Chary     }
15983e230dd2SCorentin Chary 
15993e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
16003e230dd2SCorentin Chary }
16013e230dd2SCorentin Chary 
16023e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
16033e230dd2SCorentin Chary {
16043e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
16053e230dd2SCorentin Chary }
16063e230dd2SCorentin Chary 
16073e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
16083e230dd2SCorentin Chary {
16093e230dd2SCorentin Chary     uint8_t buf[4];
16103e230dd2SCorentin Chary 
16113e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
16123e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
16133e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
16143e230dd2SCorentin Chary     buf[3] = value & 0xFF;
16153e230dd2SCorentin Chary 
16163e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
16173e230dd2SCorentin Chary }
16183e230dd2SCorentin Chary 
16193e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
16203e230dd2SCorentin Chary {
16213e230dd2SCorentin Chary     uint8_t buf[2];
16223e230dd2SCorentin Chary 
16233e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
16243e230dd2SCorentin Chary     buf[1] = value & 0xFF;
16253e230dd2SCorentin Chary 
16263e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
16273e230dd2SCorentin Chary }
16283e230dd2SCorentin Chary 
16293e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
16303e230dd2SCorentin Chary {
16313e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
16323e230dd2SCorentin Chary }
16333e230dd2SCorentin Chary 
16343e230dd2SCorentin Chary void vnc_flush(VncState *vs)
16353e230dd2SCorentin Chary {
1636bd023f95SCorentin Chary     vnc_lock_output(vs);
1637d5f04223SDaniel P. Berrange     if (vs->ioc != NULL && vs->output.offset) {
1638bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1639bd023f95SCorentin Chary     }
1640*d49b87f0SKlim Kireev     if (vs->disconnecting) {
1641*d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1642*d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1643*d49b87f0SKlim Kireev         }
1644*d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1645*d49b87f0SKlim Kireev     }
1646bd023f95SCorentin Chary     vnc_unlock_output(vs);
16473e230dd2SCorentin Chary }
16483e230dd2SCorentin Chary 
164971a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
16503e230dd2SCorentin Chary {
16513e230dd2SCorentin Chary     return data[offset];
16523e230dd2SCorentin Chary }
16533e230dd2SCorentin Chary 
165471a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
16553e230dd2SCorentin Chary {
16563e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
16573e230dd2SCorentin Chary }
16583e230dd2SCorentin Chary 
165971a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
16603e230dd2SCorentin Chary {
16613e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
16623e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
16633e230dd2SCorentin Chary }
16643e230dd2SCorentin Chary 
16653e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
16663e230dd2SCorentin Chary {
16673e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
16683e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
16693e230dd2SCorentin Chary }
16703e230dd2SCorentin Chary 
16713e230dd2SCorentin Chary static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
16723e230dd2SCorentin Chary {
16733e230dd2SCorentin Chary }
16743e230dd2SCorentin Chary 
16759e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
16763e230dd2SCorentin Chary {
16773e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
167814768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
16793e230dd2SCorentin Chary 
16803e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1681bd023f95SCorentin Chary         vnc_lock_output(vs);
16823e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
16833e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
16843e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
16853e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1686bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1687bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
16883e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1689bd023f95SCorentin Chary         vnc_unlock_output(vs);
16903e230dd2SCorentin Chary         vnc_flush(vs);
16913e230dd2SCorentin Chary     }
16923e230dd2SCorentin Chary     vs->absolute = absolute;
16933e230dd2SCorentin Chary }
16943e230dd2SCorentin Chary 
16953e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
16963e230dd2SCorentin Chary {
16977fb1cf16SEric Blake     static uint32_t bmap[INPUT_BUTTON__MAX] = {
169814768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
169914768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
170014768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
1701f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1702f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
170314768ebaSGerd Hoffmann     };
170414768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1705bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1706bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
17073e230dd2SCorentin Chary 
170814768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
170914768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
171014768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
171114768ebaSGerd Hoffmann     }
17123e230dd2SCorentin Chary 
17133e230dd2SCorentin Chary     if (vs->absolute) {
17149cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
17159cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
17163e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
171714768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
171814768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
17193e230dd2SCorentin Chary     } else {
172014768ebaSGerd Hoffmann         if (vs->last_x != -1) {
172114768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
172214768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
172314768ebaSGerd Hoffmann         }
17243e230dd2SCorentin Chary         vs->last_x = x;
17253e230dd2SCorentin Chary         vs->last_y = y;
17263e230dd2SCorentin Chary     }
172714768ebaSGerd Hoffmann     qemu_input_event_sync();
17283e230dd2SCorentin Chary }
17293e230dd2SCorentin Chary 
17303e230dd2SCorentin Chary static void reset_keys(VncState *vs)
17313e230dd2SCorentin Chary {
17323e230dd2SCorentin Chary     int i;
17333e230dd2SCorentin Chary     for(i = 0; i < 256; i++) {
17343e230dd2SCorentin Chary         if (vs->modifiers_state[i]) {
17358d447d10SGerd Hoffmann             qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1736c5ce8333SGerd Hoffmann             qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
17373e230dd2SCorentin Chary             vs->modifiers_state[i] = 0;
17383e230dd2SCorentin Chary         }
17393e230dd2SCorentin Chary     }
17403e230dd2SCorentin Chary }
17413e230dd2SCorentin Chary 
17423e230dd2SCorentin Chary static void press_key(VncState *vs, int keysym)
17433e230dd2SCorentin Chary {
17443e230dd2SCorentin Chary     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
17458d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1746c5ce8333SGerd Hoffmann     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
17478d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1748c5ce8333SGerd Hoffmann     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
17493e230dd2SCorentin Chary }
17503e230dd2SCorentin Chary 
1751ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1752ab99e5c1SLei Li {
1753ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1754ab99e5c1SLei Li         return;
1755ab99e5c1SLei Li     }
1756ab99e5c1SLei Li 
1757ab99e5c1SLei Li     vnc_lock_output(vs);
1758ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1759ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1760ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1761ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1762a54f0d2bSPierre Ossman     vnc_write_u8(vs, vs->vd->ledstate);
1763ab99e5c1SLei Li     vnc_unlock_output(vs);
1764ab99e5c1SLei Li     vnc_flush(vs);
1765ab99e5c1SLei Li }
1766ab99e5c1SLei Li 
17673e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
17683e230dd2SCorentin Chary {
1769a54f0d2bSPierre Ossman     VncDisplay *vd = opaque;
1770a54f0d2bSPierre Ossman     VncState *client;
17713e230dd2SCorentin Chary 
177240066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
177340066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
177440066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
177540066175SGerd Hoffmann 
1776a54f0d2bSPierre Ossman     if (ledstate == vd->ledstate) {
1777a54f0d2bSPierre Ossman         return;
177896f3d174SLei Li     }
1779ab99e5c1SLei Li 
1780a54f0d2bSPierre Ossman     vd->ledstate = ledstate;
1781a54f0d2bSPierre Ossman 
1782a54f0d2bSPierre Ossman     QTAILQ_FOREACH(client, &vd->clients, next) {
1783a54f0d2bSPierre Ossman         vnc_led_state_change(client);
1784ab99e5c1SLei Li     }
17853e230dd2SCorentin Chary }
17863e230dd2SCorentin Chary 
17873e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
17883e230dd2SCorentin Chary {
17893e230dd2SCorentin Chary     /* QEMU console switch */
17903e230dd2SCorentin Chary     switch(keycode) {
17913e230dd2SCorentin Chary     case 0x2a:                          /* Left Shift */
17923e230dd2SCorentin Chary     case 0x36:                          /* Right Shift */
17933e230dd2SCorentin Chary     case 0x1d:                          /* Left CTRL */
17943e230dd2SCorentin Chary     case 0x9d:                          /* Right CTRL */
17953e230dd2SCorentin Chary     case 0x38:                          /* Left ALT */
17963e230dd2SCorentin Chary     case 0xb8:                          /* Right ALT */
17973e230dd2SCorentin Chary         if (down)
17983e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 1;
17993e230dd2SCorentin Chary         else
18003e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 0;
18013e230dd2SCorentin Chary         break;
18023e230dd2SCorentin Chary     case 0x02 ... 0x0a: /* '1' to '9' keys */
18031d0d59feSGerd Hoffmann         if (vs->vd->dcl.con == NULL &&
18041d0d59feSGerd Hoffmann             down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
18053e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
18063e230dd2SCorentin Chary             reset_keys(vs);
18073e230dd2SCorentin Chary             console_select(keycode - 0x02);
18083e230dd2SCorentin Chary             return;
18093e230dd2SCorentin Chary         }
18103e230dd2SCorentin Chary         break;
18113e230dd2SCorentin Chary     case 0x3a:                        /* CapsLock */
18123e230dd2SCorentin Chary     case 0x45:                        /* NumLock */
18133e230dd2SCorentin Chary         if (down)
18143e230dd2SCorentin Chary             vs->modifiers_state[keycode] ^= 1;
18153e230dd2SCorentin Chary         break;
18163e230dd2SCorentin Chary     }
18173e230dd2SCorentin Chary 
1818e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1819e7b2aaccSLei Li        state extension.
1820e7b2aaccSLei Li     */
18219892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1822e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18233e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
18243e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
18253e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18263e230dd2SCorentin Chary            toggles numlock away from the VNC window.
18273e230dd2SCorentin Chary         */
18283e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
18293e230dd2SCorentin Chary             if (!vs->modifiers_state[0x45]) {
183040066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
18313e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 1;
18323e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
18333e230dd2SCorentin Chary             }
18343e230dd2SCorentin Chary         } else {
18353e230dd2SCorentin Chary             if (vs->modifiers_state[0x45]) {
183640066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
18373e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 0;
18383e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
18393e230dd2SCorentin Chary             }
18403e230dd2SCorentin Chary         }
18413e230dd2SCorentin Chary     }
18423e230dd2SCorentin Chary 
18439892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1844e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18453e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
18463e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
18473e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18483e230dd2SCorentin Chary            toggles capslock away from the VNC window.
18493e230dd2SCorentin Chary         */
18503e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
18513e230dd2SCorentin Chary         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
18523e230dd2SCorentin Chary         int capslock = !!(vs->modifiers_state[0x3a]);
18533e230dd2SCorentin Chary         if (capslock) {
18543e230dd2SCorentin Chary             if (uppercase == shift) {
185540066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
18563e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 0;
18573e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18583e230dd2SCorentin Chary             }
18593e230dd2SCorentin Chary         } else {
18603e230dd2SCorentin Chary             if (uppercase != shift) {
186140066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
18623e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 1;
18633e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18643e230dd2SCorentin Chary             }
18653e230dd2SCorentin Chary         }
18663e230dd2SCorentin Chary     }
18673e230dd2SCorentin Chary 
186881c0d5a6SGerd Hoffmann     if (qemu_console_is_graphic(NULL)) {
18698d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1870c5ce8333SGerd Hoffmann         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
18713e230dd2SCorentin Chary     } else {
1872e26437c2SGerd Hoffmann         bool numlock = vs->modifiers_state[0x45];
1873e26437c2SGerd Hoffmann         bool control = (vs->modifiers_state[0x1d] ||
1874e26437c2SGerd Hoffmann                         vs->modifiers_state[0x9d]);
18753e230dd2SCorentin Chary         /* QEMU console emulation */
18763e230dd2SCorentin Chary         if (down) {
18773e230dd2SCorentin Chary             switch (keycode) {
18783e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
18793e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
18803e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
18813e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
18823e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
18833e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
18843e230dd2SCorentin Chary                 break;
18853e230dd2SCorentin Chary             case 0xc8:
18863e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_UP);
18873e230dd2SCorentin Chary                 break;
18883e230dd2SCorentin Chary             case 0xd0:
18893e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DOWN);
18903e230dd2SCorentin Chary                 break;
18913e230dd2SCorentin Chary             case 0xcb:
18923e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_LEFT);
18933e230dd2SCorentin Chary                 break;
18943e230dd2SCorentin Chary             case 0xcd:
18953e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_RIGHT);
18963e230dd2SCorentin Chary                 break;
18973e230dd2SCorentin Chary             case 0xd3:
18983e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DELETE);
18993e230dd2SCorentin Chary                 break;
19003e230dd2SCorentin Chary             case 0xc7:
19013e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_HOME);
19023e230dd2SCorentin Chary                 break;
19033e230dd2SCorentin Chary             case 0xcf:
19043e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_END);
19053e230dd2SCorentin Chary                 break;
19063e230dd2SCorentin Chary             case 0xc9:
19073e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEUP);
19083e230dd2SCorentin Chary                 break;
19093e230dd2SCorentin Chary             case 0xd1:
19103e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
19113e230dd2SCorentin Chary                 break;
19123e230dd2SCorentin Chary 
19133e230dd2SCorentin Chary             case 0x47:
19143e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
19153e230dd2SCorentin Chary                 break;
19163e230dd2SCorentin Chary             case 0x48:
19173e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
19183e230dd2SCorentin Chary                 break;
19193e230dd2SCorentin Chary             case 0x49:
19203e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
19213e230dd2SCorentin Chary                 break;
19223e230dd2SCorentin Chary             case 0x4b:
19233e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
19243e230dd2SCorentin Chary                 break;
19253e230dd2SCorentin Chary             case 0x4c:
19263e230dd2SCorentin Chary                 kbd_put_keysym('5');
19273e230dd2SCorentin Chary                 break;
19283e230dd2SCorentin Chary             case 0x4d:
19293e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
19303e230dd2SCorentin Chary                 break;
19313e230dd2SCorentin Chary             case 0x4f:
19323e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
19333e230dd2SCorentin Chary                 break;
19343e230dd2SCorentin Chary             case 0x50:
19353e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
19363e230dd2SCorentin Chary                 break;
19373e230dd2SCorentin Chary             case 0x51:
19383e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
19393e230dd2SCorentin Chary                 break;
19403e230dd2SCorentin Chary             case 0x52:
19413e230dd2SCorentin Chary                 kbd_put_keysym('0');
19423e230dd2SCorentin Chary                 break;
19433e230dd2SCorentin Chary             case 0x53:
19443e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
19453e230dd2SCorentin Chary                 break;
19463e230dd2SCorentin Chary 
19473e230dd2SCorentin Chary             case 0xb5:
19483e230dd2SCorentin Chary                 kbd_put_keysym('/');
19493e230dd2SCorentin Chary                 break;
19503e230dd2SCorentin Chary             case 0x37:
19513e230dd2SCorentin Chary                 kbd_put_keysym('*');
19523e230dd2SCorentin Chary                 break;
19533e230dd2SCorentin Chary             case 0x4a:
19543e230dd2SCorentin Chary                 kbd_put_keysym('-');
19553e230dd2SCorentin Chary                 break;
19563e230dd2SCorentin Chary             case 0x4e:
19573e230dd2SCorentin Chary                 kbd_put_keysym('+');
19583e230dd2SCorentin Chary                 break;
19593e230dd2SCorentin Chary             case 0x9c:
19603e230dd2SCorentin Chary                 kbd_put_keysym('\n');
19613e230dd2SCorentin Chary                 break;
19623e230dd2SCorentin Chary 
19633e230dd2SCorentin Chary             default:
1964e26437c2SGerd Hoffmann                 if (control) {
1965e26437c2SGerd Hoffmann                     kbd_put_keysym(sym & 0x1f);
1966e26437c2SGerd Hoffmann                 } else {
19673e230dd2SCorentin Chary                     kbd_put_keysym(sym);
1968e26437c2SGerd Hoffmann                 }
19693e230dd2SCorentin Chary                 break;
19703e230dd2SCorentin Chary             }
19713e230dd2SCorentin Chary         }
19723e230dd2SCorentin Chary     }
19733e230dd2SCorentin Chary }
19743e230dd2SCorentin Chary 
19757bc9318bSGerd Hoffmann static void vnc_release_modifiers(VncState *vs)
19767bc9318bSGerd Hoffmann {
19777bc9318bSGerd Hoffmann     static const int keycodes[] = {
19787bc9318bSGerd Hoffmann         /* shift, control, alt keys, both left & right */
19797bc9318bSGerd Hoffmann         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
19807bc9318bSGerd Hoffmann     };
19817bc9318bSGerd Hoffmann     int i, keycode;
19827bc9318bSGerd Hoffmann 
198381c0d5a6SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
19847bc9318bSGerd Hoffmann         return;
19857bc9318bSGerd Hoffmann     }
19867bc9318bSGerd Hoffmann     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
19877bc9318bSGerd Hoffmann         keycode = keycodes[i];
19887bc9318bSGerd Hoffmann         if (!vs->modifiers_state[keycode]) {
19897bc9318bSGerd Hoffmann             continue;
19907bc9318bSGerd Hoffmann         }
19918d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1992c5ce8333SGerd Hoffmann         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
19937bc9318bSGerd Hoffmann     }
19947bc9318bSGerd Hoffmann }
19957bc9318bSGerd Hoffmann 
199640066175SGerd Hoffmann static const char *code2name(int keycode)
199740066175SGerd Hoffmann {
1998977c736fSMarkus Armbruster     return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
199940066175SGerd Hoffmann }
200040066175SGerd Hoffmann 
20013e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
20023e230dd2SCorentin Chary {
20033e230dd2SCorentin Chary     int keycode;
20043e230dd2SCorentin Chary     int lsym = sym;
20053e230dd2SCorentin Chary 
200681c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
20073e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
20083e230dd2SCorentin Chary     }
20093e230dd2SCorentin Chary 
20103e230dd2SCorentin Chary     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
201140066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
20123e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
20133e230dd2SCorentin Chary }
20143e230dd2SCorentin Chary 
20153e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
20163e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
20173e230dd2SCorentin Chary {
20183e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
201940066175SGerd Hoffmann     if (keyboard_layout) {
20203e230dd2SCorentin Chary         key_event(vs, down, sym);
202140066175SGerd Hoffmann     } else {
202240066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
20233e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
20243e230dd2SCorentin Chary     }
202540066175SGerd Hoffmann }
20263e230dd2SCorentin Chary 
20273e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
2028bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
20293e230dd2SCorentin Chary {
2030bea60dd7SPeter Lieven     if (incremental) {
2031fef1bbadSDaniel P. Berrange         if (vs->update != VNC_STATE_UPDATE_FORCE) {
2032fef1bbadSDaniel P. Berrange             vs->update = VNC_STATE_UPDATE_INCREMENTAL;
20333e230dd2SCorentin Chary         }
2034fef1bbadSDaniel P. Berrange     } else {
2035fef1bbadSDaniel P. Berrange         vs->update = VNC_STATE_UPDATE_FORCE;
2036f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
20373e230dd2SCorentin Chary     }
2038fef1bbadSDaniel P. Berrange }
20393e230dd2SCorentin Chary 
20403e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
20413e230dd2SCorentin Chary {
2042bd023f95SCorentin Chary     vnc_lock_output(vs);
20433e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20443e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20453e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2046d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2047bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2048bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20493e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
2050bd023f95SCorentin Chary     vnc_unlock_output(vs);
20513e230dd2SCorentin Chary     vnc_flush(vs);
20523e230dd2SCorentin Chary }
20533e230dd2SCorentin Chary 
20543e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
20553e230dd2SCorentin Chary {
2056bd023f95SCorentin Chary     vnc_lock_output(vs);
20573e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20583e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20593e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2060d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2061bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2062bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20633e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2064bd023f95SCorentin Chary     vnc_unlock_output(vs);
20653e230dd2SCorentin Chary     vnc_flush(vs);
20663e230dd2SCorentin Chary }
20673e230dd2SCorentin Chary 
20683e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
20693e230dd2SCorentin Chary {
20703e230dd2SCorentin Chary     int i;
20713e230dd2SCorentin Chary     unsigned int enc = 0;
20723e230dd2SCorentin Chary 
20733e230dd2SCorentin Chary     vs->features = 0;
20743e230dd2SCorentin Chary     vs->vnc_encoding = 0;
2075d1af0e05SCorentin Chary     vs->tight.compression = 9;
2076d1af0e05SCorentin Chary     vs->tight.quality = -1; /* Lossless by default */
20773e230dd2SCorentin Chary     vs->absolute = -1;
20783e230dd2SCorentin Chary 
20793e230dd2SCorentin Chary     /*
20803e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2081e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
20823e230dd2SCorentin Chary      * will be set at the end of the loop.
20833e230dd2SCorentin Chary      */
20843e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
20853e230dd2SCorentin Chary         enc = encodings[i];
20863e230dd2SCorentin Chary         switch (enc) {
20873e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
20883e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20893e230dd2SCorentin Chary             break;
20903e230dd2SCorentin Chary         case VNC_ENCODING_COPYRECT:
20913e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_COPYRECT_MASK;
20923e230dd2SCorentin Chary             break;
20933e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
20943e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
20953e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20963e230dd2SCorentin Chary             break;
20973e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
20983e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
20993e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21003e230dd2SCorentin Chary             break;
2101fe3e7f2dSJoel Martin #ifdef CONFIG_VNC_PNG
2102efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2103efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2104efe556adSCorentin Chary             vs->vnc_encoding = enc;
2105efe556adSCorentin Chary             break;
2106fe3e7f2dSJoel Martin #endif
21073e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
21083e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_ZLIB_MASK;
21093e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21103e230dd2SCorentin Chary             break;
2111148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2112148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2113148954faSCorentin Chary             vs->vnc_encoding = enc;
2114148954faSCorentin Chary             break;
2115148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2116148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2117148954faSCorentin Chary             vs->vnc_encoding = enc;
2118148954faSCorentin Chary             break;
21193e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
21203e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
21213e230dd2SCorentin Chary             break;
21223e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
21233e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
21243e230dd2SCorentin Chary             break;
21253e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
21263e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
212791ec41dcSFrediano Ziglio             if (vs->vd->cursor) {
212891ec41dcSFrediano Ziglio                 vnc_cursor_define(vs);
212991ec41dcSFrediano Ziglio             }
21303e230dd2SCorentin Chary             break;
21313e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
21323e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
21333e230dd2SCorentin Chary             break;
21343e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
21353e230dd2SCorentin Chary             send_ext_audio_ack(vs);
21363e230dd2SCorentin Chary             break;
21373e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
21383e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
21393e230dd2SCorentin Chary             break;
2140ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2141ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2142ab99e5c1SLei Li             break;
21433e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2144d1af0e05SCorentin Chary             vs->tight.compression = (enc & 0x0F);
21453e230dd2SCorentin Chary             break;
21463e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2147b31f519eSCorentin Chary             if (vs->vd->lossy) {
2148d1af0e05SCorentin Chary                 vs->tight.quality = (enc & 0x0F);
2149b31f519eSCorentin Chary             }
21503e230dd2SCorentin Chary             break;
21513e230dd2SCorentin Chary         default:
21523e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
21533e230dd2SCorentin Chary             break;
21543e230dd2SCorentin Chary         }
21553e230dd2SCorentin Chary     }
21563e230dd2SCorentin Chary     vnc_desktop_resize(vs);
21579e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2158ab99e5c1SLei Li     vnc_led_state_change(vs);
21593e230dd2SCorentin Chary }
21603e230dd2SCorentin Chary 
21613e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
21623e230dd2SCorentin Chary {
21639f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
21649f64916dSGerd Hoffmann 
21659f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
21663e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
21673e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
21683e230dd2SCorentin Chary     } else {
21693e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
21703e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
21713e230dd2SCorentin Chary     }
21723e230dd2SCorentin Chary }
21733e230dd2SCorentin Chary 
21740c426e45SAlexander Graf static void send_color_map(VncState *vs)
21750c426e45SAlexander Graf {
21760c426e45SAlexander Graf     int i;
21770c426e45SAlexander Graf 
21780c426e45SAlexander Graf     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
21790c426e45SAlexander Graf     vnc_write_u8(vs,  0);    /* padding     */
21800c426e45SAlexander Graf     vnc_write_u16(vs, 0);    /* first color */
21810c426e45SAlexander Graf     vnc_write_u16(vs, 256);  /* # of colors */
21820c426e45SAlexander Graf 
21830c426e45SAlexander Graf     for (i = 0; i < 256; i++) {
21840c426e45SAlexander Graf         PixelFormat *pf = &vs->client_pf;
21850c426e45SAlexander Graf 
21860c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
21870c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
21880c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
21890c426e45SAlexander Graf     }
21900c426e45SAlexander Graf }
21910c426e45SAlexander Graf 
2192ec9fb41aSGerd Hoffmann static void set_pixel_format(VncState *vs, int bits_per_pixel,
21933e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
21943e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
21953e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
21963e230dd2SCorentin Chary {
21973e230dd2SCorentin Chary     if (!true_color_flag) {
21980c426e45SAlexander Graf         /* Expose a reasonable default 256 color map */
21990c426e45SAlexander Graf         bits_per_pixel = 8;
22000c426e45SAlexander Graf         red_max = 7;
22010c426e45SAlexander Graf         green_max = 7;
22020c426e45SAlexander Graf         blue_max = 3;
22030c426e45SAlexander Graf         red_shift = 0;
22040c426e45SAlexander Graf         green_shift = 3;
22050c426e45SAlexander Graf         blue_shift = 6;
22063e230dd2SCorentin Chary     }
22073e230dd2SCorentin Chary 
2208e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2209e6908bfeSPetr Matousek     case 8:
2210e6908bfeSPetr Matousek     case 16:
2211e6908bfeSPetr Matousek     case 32:
2212e6908bfeSPetr Matousek         break;
2213e6908bfeSPetr Matousek     default:
2214e6908bfeSPetr Matousek         vnc_client_error(vs);
2215e6908bfeSPetr Matousek         return;
2216e6908bfeSPetr Matousek     }
2217e6908bfeSPetr Matousek 
22184c65fed8SPrasad J Pandit     vs->client_pf.rmax = red_max ? red_max : 0xFF;
22197c9209e7SCédric Le Goater     vs->client_pf.rbits = ctpopl(red_max);
22209f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
22219f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
22224c65fed8SPrasad J Pandit     vs->client_pf.gmax = green_max ? green_max : 0xFF;
22237c9209e7SCédric Le Goater     vs->client_pf.gbits = ctpopl(green_max);
22249f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
22259f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
22264c65fed8SPrasad J Pandit     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
22277c9209e7SCédric Le Goater     vs->client_pf.bbits = ctpopl(blue_max);
22289f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
22299f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
22309f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
22319f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
22329f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
22339f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
22343e230dd2SCorentin Chary 
22350c426e45SAlexander Graf     if (!true_color_flag) {
22360c426e45SAlexander Graf         send_color_map(vs);
22370c426e45SAlexander Graf     }
22380c426e45SAlexander Graf 
22393e230dd2SCorentin Chary     set_pixel_conversion(vs);
22403e230dd2SCorentin Chary 
22411d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
22421d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
22433e230dd2SCorentin Chary }
22443e230dd2SCorentin Chary 
22453e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
22463e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
22473e230dd2SCorentin Chary 
22489f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
22499f64916dSGerd Hoffmann 
22509f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
22519f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
22523e230dd2SCorentin Chary 
22533e230dd2SCorentin Chary #ifdef HOST_WORDS_BIGENDIAN
22543e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
22553e230dd2SCorentin Chary #else
22563e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
22573e230dd2SCorentin Chary #endif
22583e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
22599f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
22609f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
22619f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
22629f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
22639f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
22649f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
22659f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
22663e230dd2SCorentin Chary 
22673e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
22683e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
22693e230dd2SCorentin Chary }
22703e230dd2SCorentin Chary 
22713e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
22723e230dd2SCorentin Chary {
22733e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
22743e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2275bd023f95SCorentin Chary         vnc_lock_output(vs);
22763e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
22773e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
22783e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2279d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
2280bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
2281bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
2282d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
22833e230dd2SCorentin Chary         pixel_format_message(vs);
2284bd023f95SCorentin Chary         vnc_unlock_output(vs);
22853e230dd2SCorentin Chary         vnc_flush(vs);
22863e230dd2SCorentin Chary     } else {
22873e230dd2SCorentin Chary         set_pixel_conversion(vs);
22883e230dd2SCorentin Chary     }
22893e230dd2SCorentin Chary }
22903e230dd2SCorentin Chary 
22913e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
22923e230dd2SCorentin Chary {
22933e230dd2SCorentin Chary     int i;
22943e230dd2SCorentin Chary     uint16_t limit;
22953e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
22963e230dd2SCorentin Chary 
22973e230dd2SCorentin Chary     if (data[0] > 3) {
22980f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
22993e230dd2SCorentin Chary     }
23003e230dd2SCorentin Chary 
23013e230dd2SCorentin Chary     switch (data[0]) {
23023e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
23033e230dd2SCorentin Chary         if (len == 1)
23043e230dd2SCorentin Chary             return 20;
23053e230dd2SCorentin Chary 
2306ec9fb41aSGerd Hoffmann         set_pixel_format(vs, read_u8(data, 4),
23073e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
23083e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
23093e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
23103e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
23113e230dd2SCorentin Chary         break;
23123e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
23133e230dd2SCorentin Chary         if (len == 1)
23143e230dd2SCorentin Chary             return 4;
23153e230dd2SCorentin Chary 
23163e230dd2SCorentin Chary         if (len == 4) {
23173e230dd2SCorentin Chary             limit = read_u16(data, 2);
23183e230dd2SCorentin Chary             if (limit > 0)
23193e230dd2SCorentin Chary                 return 4 + (limit * 4);
23203e230dd2SCorentin Chary         } else
23213e230dd2SCorentin Chary             limit = read_u16(data, 2);
23223e230dd2SCorentin Chary 
23233e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
23243e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
23253e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
23263e230dd2SCorentin Chary         }
23273e230dd2SCorentin Chary 
23283e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
23293e230dd2SCorentin Chary         break;
23303e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
23313e230dd2SCorentin Chary         if (len == 1)
23323e230dd2SCorentin Chary             return 10;
23333e230dd2SCorentin Chary 
23343e230dd2SCorentin Chary         framebuffer_update_request(vs,
23353e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
23363e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
23373e230dd2SCorentin Chary         break;
23383e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
23393e230dd2SCorentin Chary         if (len == 1)
23403e230dd2SCorentin Chary             return 8;
23413e230dd2SCorentin Chary 
23423e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
23433e230dd2SCorentin Chary         break;
23443e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
23453e230dd2SCorentin Chary         if (len == 1)
23463e230dd2SCorentin Chary             return 6;
23473e230dd2SCorentin Chary 
23483e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
23493e230dd2SCorentin Chary         break;
23503e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2351f9a70e79SPeter Lieven         if (len == 1) {
23523e230dd2SCorentin Chary             return 8;
2353f9a70e79SPeter Lieven         }
23543e230dd2SCorentin Chary         if (len == 8) {
23553e230dd2SCorentin Chary             uint32_t dlen = read_u32(data, 4);
2356f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2357f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2358f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2359f9a70e79SPeter Lieven                 vnc_client_error(vs);
2360f9a70e79SPeter Lieven                 break;
2361f9a70e79SPeter Lieven             }
2362f9a70e79SPeter Lieven             if (dlen > 0) {
23633e230dd2SCorentin Chary                 return 8 + dlen;
23643e230dd2SCorentin Chary             }
2365f9a70e79SPeter Lieven         }
23663e230dd2SCorentin Chary 
23673e230dd2SCorentin Chary         client_cut_text(vs, read_u32(data, 4), data + 8);
23683e230dd2SCorentin Chary         break;
23693e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
23703e230dd2SCorentin Chary         if (len == 1)
23713e230dd2SCorentin Chary             return 2;
23723e230dd2SCorentin Chary 
23733e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
23743e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
23753e230dd2SCorentin Chary             if (len == 2)
23763e230dd2SCorentin Chary                 return 12;
23773e230dd2SCorentin Chary 
23783e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
23793e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
23803e230dd2SCorentin Chary             break;
23813e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
23823e230dd2SCorentin Chary             if (len == 2)
23833e230dd2SCorentin Chary                 return 4;
23843e230dd2SCorentin Chary 
23853e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
23863e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
23873e230dd2SCorentin Chary                 audio_add(vs);
23883e230dd2SCorentin Chary                 break;
23893e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
23903e230dd2SCorentin Chary                 audio_del(vs);
23913e230dd2SCorentin Chary                 break;
23923e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
23933e230dd2SCorentin Chary                 if (len == 4)
23943e230dd2SCorentin Chary                     return 10;
23953e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
23963e230dd2SCorentin Chary                 case 0: vs->as.fmt = AUD_FMT_U8; break;
23973e230dd2SCorentin Chary                 case 1: vs->as.fmt = AUD_FMT_S8; break;
23983e230dd2SCorentin Chary                 case 2: vs->as.fmt = AUD_FMT_U16; break;
23993e230dd2SCorentin Chary                 case 3: vs->as.fmt = AUD_FMT_S16; break;
24003e230dd2SCorentin Chary                 case 4: vs->as.fmt = AUD_FMT_U32; break;
24013e230dd2SCorentin Chary                 case 5: vs->as.fmt = AUD_FMT_S32; break;
24023e230dd2SCorentin Chary                 default:
2403153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
24043e230dd2SCorentin Chary                     vnc_client_error(vs);
24053e230dd2SCorentin Chary                     break;
24063e230dd2SCorentin Chary                 }
24073e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
24083e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2409090fdc83SMarc-André Lureau                     VNC_DEBUG("Invalid audio channel count %d\n",
24103e230dd2SCorentin Chary                               read_u8(data, 5));
24113e230dd2SCorentin Chary                     vnc_client_error(vs);
24123e230dd2SCorentin Chary                     break;
24133e230dd2SCorentin Chary                 }
24143e230dd2SCorentin Chary                 vs->as.freq = read_u32(data, 6);
24153e230dd2SCorentin Chary                 break;
24163e230dd2SCorentin Chary             default:
2417153130cdSDaniel P. Berrange                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
24183e230dd2SCorentin Chary                 vnc_client_error(vs);
24193e230dd2SCorentin Chary                 break;
24203e230dd2SCorentin Chary             }
24213e230dd2SCorentin Chary             break;
24223e230dd2SCorentin Chary 
24233e230dd2SCorentin Chary         default:
2424153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
24253e230dd2SCorentin Chary             vnc_client_error(vs);
24263e230dd2SCorentin Chary             break;
24273e230dd2SCorentin Chary         }
24283e230dd2SCorentin Chary         break;
24293e230dd2SCorentin Chary     default:
2430153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
24313e230dd2SCorentin Chary         vnc_client_error(vs);
24323e230dd2SCorentin Chary         break;
24333e230dd2SCorentin Chary     }
24343e230dd2SCorentin Chary 
2435e2b72cb6SDaniel P. Berrange     vnc_update_throttle_offset(vs);
24363e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
24373e230dd2SCorentin Chary     return 0;
24383e230dd2SCorentin Chary }
24393e230dd2SCorentin Chary 
24403e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
24413e230dd2SCorentin Chary {
24423e230dd2SCorentin Chary     char buf[1024];
24438cf36489SGerd Hoffmann     VncShareMode mode;
24443e230dd2SCorentin Chary     int size;
24453e230dd2SCorentin Chary 
24468cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
24478cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
24488cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
24498cf36489SGerd Hoffmann         /*
24508cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
24518cf36489SGerd Hoffmann          *
24528cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
24538cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
24548cf36489SGerd Hoffmann          * reasons.
24558cf36489SGerd Hoffmann          */
24568cf36489SGerd Hoffmann         break;
24578cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
24588cf36489SGerd Hoffmann         /*
24598cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
24608cf36489SGerd Hoffmann          *
24618cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
24628cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
24638cf36489SGerd Hoffmann          * as no exclusive connection exists.
24648cf36489SGerd Hoffmann          *
24658cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
24668cf36489SGerd Hoffmann          */
24678cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24688cf36489SGerd Hoffmann             VncState *client;
24698cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
24708cf36489SGerd Hoffmann                 if (vs == client) {
24718cf36489SGerd Hoffmann                     continue;
24728cf36489SGerd Hoffmann                 }
24738cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
24748cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
24758cf36489SGerd Hoffmann                     continue;
24768cf36489SGerd Hoffmann                 }
24778cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
24788cf36489SGerd Hoffmann             }
24798cf36489SGerd Hoffmann         }
24808cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
24818cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
24828cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
24838cf36489SGerd Hoffmann                 return 0;
24848cf36489SGerd Hoffmann             }
24858cf36489SGerd Hoffmann         }
24868cf36489SGerd Hoffmann         break;
24878cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
24888cf36489SGerd Hoffmann         /*
24898cf36489SGerd Hoffmann          * Policy: Shared connects only.
24908cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
24918cf36489SGerd Hoffmann          *
24928cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
24938cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
24948cf36489SGerd Hoffmann          * client disconnect everybody else.
24958cf36489SGerd Hoffmann          */
24968cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24978cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
24988cf36489SGerd Hoffmann             return 0;
24998cf36489SGerd Hoffmann         }
25008cf36489SGerd Hoffmann         break;
25018cf36489SGerd Hoffmann     }
25028cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
25038cf36489SGerd Hoffmann 
2504e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2505e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2506e5f34cddSGerd Hoffmann         return 0;
2507e5f34cddSGerd Hoffmann     }
2508e5f34cddSGerd Hoffmann 
25094c956bd8SDaniel P. Berrange     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
25104c956bd8SDaniel P. Berrange            pixman_image_get_width(vs->vd->server) >= 0);
25114c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
25124c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
2513bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2514bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
25153e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
25163e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
25173e230dd2SCorentin Chary 
25183e230dd2SCorentin Chary     pixel_format_message(vs);
25193e230dd2SCorentin Chary 
252097efe4f9SThomas Huth     if (qemu_name) {
25213e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
252297efe4f9SThomas Huth         if (size > sizeof(buf)) {
252397efe4f9SThomas Huth             size = sizeof(buf);
252497efe4f9SThomas Huth         }
252597efe4f9SThomas Huth     } else {
25263e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
252797efe4f9SThomas Huth     }
25283e230dd2SCorentin Chary 
25293e230dd2SCorentin Chary     vnc_write_u32(vs, size);
25303e230dd2SCorentin Chary     vnc_write(vs, buf, size);
25313e230dd2SCorentin Chary     vnc_flush(vs);
25323e230dd2SCorentin Chary 
25333e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2534fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
25353e230dd2SCorentin Chary 
25363e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
25373e230dd2SCorentin Chary 
25383e230dd2SCorentin Chary     return 0;
25393e230dd2SCorentin Chary }
25403e230dd2SCorentin Chary 
25413e230dd2SCorentin Chary void start_client_init(VncState *vs)
25423e230dd2SCorentin Chary {
25433e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
25443e230dd2SCorentin Chary }
25453e230dd2SCorentin Chary 
25463e230dd2SCorentin Chary static void make_challenge(VncState *vs)
25473e230dd2SCorentin Chary {
25483e230dd2SCorentin Chary     int i;
25493e230dd2SCorentin Chary 
25503e230dd2SCorentin Chary     srand(time(NULL)+getpid()+getpid()*987654+rand());
25513e230dd2SCorentin Chary 
25523e230dd2SCorentin Chary     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
25533e230dd2SCorentin Chary         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
25543e230dd2SCorentin Chary }
25553e230dd2SCorentin Chary 
25563e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
25573e230dd2SCorentin Chary {
25583e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2559800567a6SDaniel P. Berrange     size_t i, pwlen;
25603e230dd2SCorentin Chary     unsigned char key[8];
25613c9405a0SGerd Hoffmann     time_t now = time(NULL);
256260928458SGonglei     QCryptoCipher *cipher = NULL;
2563800567a6SDaniel P. Berrange     Error *err = NULL;
25643e230dd2SCorentin Chary 
25651cd20f8bSAnthony Liguori     if (!vs->vd->password) {
25667364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
25676bffdf0fSGerd Hoffmann         goto reject;
25683e230dd2SCorentin Chary     }
25693c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
25707364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
25713c9405a0SGerd Hoffmann         goto reject;
25723c9405a0SGerd Hoffmann     }
25733e230dd2SCorentin Chary 
25743e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
25753e230dd2SCorentin Chary 
25763e230dd2SCorentin Chary     /* Calculate the expected challenge response */
25773e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
25783e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
25793e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2580800567a6SDaniel P. Berrange 
2581800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
2582800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_DES_RFB,
2583800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2584800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2585800567a6SDaniel P. Berrange         &err);
2586800567a6SDaniel P. Berrange     if (!cipher) {
25877364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2588800567a6SDaniel P. Berrange                             error_get_pretty(err));
2589800567a6SDaniel P. Berrange         error_free(err);
2590800567a6SDaniel P. Berrange         goto reject;
2591800567a6SDaniel P. Berrange     }
2592800567a6SDaniel P. Berrange 
2593a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2594800567a6SDaniel P. Berrange                                vs->challenge,
2595800567a6SDaniel P. Berrange                                response,
2596800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2597800567a6SDaniel P. Berrange                                &err) < 0) {
25987364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2599800567a6SDaniel P. Berrange                             error_get_pretty(err));
2600800567a6SDaniel P. Berrange         error_free(err);
2601800567a6SDaniel P. Berrange         goto reject;
2602800567a6SDaniel P. Berrange     }
26033e230dd2SCorentin Chary 
26043e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
26053e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
26067364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
26076bffdf0fSGerd Hoffmann         goto reject;
26086bffdf0fSGerd Hoffmann     } else {
26097364dbdaSDaniel P. Berrange         trace_vnc_auth_pass(vs, vs->auth);
26106bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
26116bffdf0fSGerd Hoffmann         vnc_flush(vs);
26126bffdf0fSGerd Hoffmann 
26136bffdf0fSGerd Hoffmann         start_client_init(vs);
26146bffdf0fSGerd Hoffmann     }
261560928458SGonglei 
261660928458SGonglei     qcrypto_cipher_free(cipher);
26176bffdf0fSGerd Hoffmann     return 0;
26186bffdf0fSGerd Hoffmann 
26196bffdf0fSGerd Hoffmann reject:
26203e230dd2SCorentin Chary     vnc_write_u32(vs, 1); /* Reject auth */
26213e230dd2SCorentin Chary     if (vs->minor >= 8) {
26223e230dd2SCorentin Chary         static const char err[] = "Authentication failed";
26233e230dd2SCorentin Chary         vnc_write_u32(vs, sizeof(err));
26243e230dd2SCorentin Chary         vnc_write(vs, err, sizeof(err));
26253e230dd2SCorentin Chary     }
26263e230dd2SCorentin Chary     vnc_flush(vs);
26273e230dd2SCorentin Chary     vnc_client_error(vs);
262860928458SGonglei     qcrypto_cipher_free(cipher);
26293e230dd2SCorentin Chary     return 0;
26303e230dd2SCorentin Chary }
26313e230dd2SCorentin Chary 
26323e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
26333e230dd2SCorentin Chary {
26343e230dd2SCorentin Chary     make_challenge(vs);
26353e230dd2SCorentin Chary     /* Send client a 'random' challenge */
26363e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
26373e230dd2SCorentin Chary     vnc_flush(vs);
26383e230dd2SCorentin Chary 
26393e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
26403e230dd2SCorentin Chary }
26413e230dd2SCorentin Chary 
26423e230dd2SCorentin Chary 
26433e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
26443e230dd2SCorentin Chary {
26453e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
26463e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
26477e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
26487364dbdaSDaniel P. Berrange        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
26493e230dd2SCorentin Chary        vnc_write_u32(vs, 1);
26503e230dd2SCorentin Chary        if (vs->minor >= 8) {
26513e230dd2SCorentin Chary            static const char err[] = "Authentication failed";
26523e230dd2SCorentin Chary            vnc_write_u32(vs, sizeof(err));
26533e230dd2SCorentin Chary            vnc_write(vs, err, sizeof(err));
26543e230dd2SCorentin Chary        }
26553e230dd2SCorentin Chary        vnc_client_error(vs);
26563e230dd2SCorentin Chary     } else { /* Accept requested auth */
26577364dbdaSDaniel P. Berrange        trace_vnc_auth_start(vs, vs->auth);
26587e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
26593e230dd2SCorentin Chary        case VNC_AUTH_NONE:
26603e230dd2SCorentin Chary            if (vs->minor >= 8) {
26613e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
26623e230dd2SCorentin Chary                vnc_flush(vs);
26633e230dd2SCorentin Chary            }
26647364dbdaSDaniel P. Berrange            trace_vnc_auth_pass(vs, vs->auth);
26653e230dd2SCorentin Chary            start_client_init(vs);
26663e230dd2SCorentin Chary            break;
26673e230dd2SCorentin Chary 
26683e230dd2SCorentin Chary        case VNC_AUTH_VNC:
26693e230dd2SCorentin Chary            start_auth_vnc(vs);
26703e230dd2SCorentin Chary            break;
26713e230dd2SCorentin Chary 
26723e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
26733e230dd2SCorentin Chary            start_auth_vencrypt(vs);
26743e230dd2SCorentin Chary            break;
26753e230dd2SCorentin Chary 
26763e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
26773e230dd2SCorentin Chary        case VNC_AUTH_SASL:
26783e230dd2SCorentin Chary            start_auth_sasl(vs);
26793e230dd2SCorentin Chary            break;
26803e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
26813e230dd2SCorentin Chary 
26823e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
26837364dbdaSDaniel P. Berrange            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
26843e230dd2SCorentin Chary            vnc_write_u8(vs, 1);
26853e230dd2SCorentin Chary            if (vs->minor >= 8) {
26863e230dd2SCorentin Chary                static const char err[] = "Authentication failed";
26873e230dd2SCorentin Chary                vnc_write_u32(vs, sizeof(err));
26883e230dd2SCorentin Chary                vnc_write(vs, err, sizeof(err));
26893e230dd2SCorentin Chary            }
26903e230dd2SCorentin Chary            vnc_client_error(vs);
26913e230dd2SCorentin Chary        }
26923e230dd2SCorentin Chary     }
26933e230dd2SCorentin Chary     return 0;
26943e230dd2SCorentin Chary }
26953e230dd2SCorentin Chary 
26963e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
26973e230dd2SCorentin Chary {
26983e230dd2SCorentin Chary     char local[13];
26993e230dd2SCorentin Chary 
27003e230dd2SCorentin Chary     memcpy(local, version, 12);
27013e230dd2SCorentin Chary     local[12] = 0;
27023e230dd2SCorentin Chary 
27033e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
27043e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
27053e230dd2SCorentin Chary         vnc_client_error(vs);
27063e230dd2SCorentin Chary         return 0;
27073e230dd2SCorentin Chary     }
27083e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
27093e230dd2SCorentin Chary     if (vs->major != 3 ||
27103e230dd2SCorentin Chary         (vs->minor != 3 &&
27113e230dd2SCorentin Chary          vs->minor != 4 &&
27123e230dd2SCorentin Chary          vs->minor != 5 &&
27133e230dd2SCorentin Chary          vs->minor != 7 &&
27143e230dd2SCorentin Chary          vs->minor != 8)) {
27153e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
27163e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
27173e230dd2SCorentin Chary         vnc_flush(vs);
27183e230dd2SCorentin Chary         vnc_client_error(vs);
27193e230dd2SCorentin Chary         return 0;
27203e230dd2SCorentin Chary     }
27213e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
27223e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
27233e230dd2SCorentin Chary      */
27243e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
27253e230dd2SCorentin Chary         vs->minor = 3;
27263e230dd2SCorentin Chary 
27273e230dd2SCorentin Chary     if (vs->minor == 3) {
27287364dbdaSDaniel P. Berrange         trace_vnc_auth_start(vs, vs->auth);
27297e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
27307e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
27313e230dd2SCorentin Chary             vnc_flush(vs);
27327364dbdaSDaniel P. Berrange             trace_vnc_auth_pass(vs, vs->auth);
27333e230dd2SCorentin Chary             start_client_init(vs);
27347e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
27353e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
27367e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
27373e230dd2SCorentin Chary             vnc_flush(vs);
27383e230dd2SCorentin Chary             start_auth_vnc(vs);
27393e230dd2SCorentin Chary        } else {
27407364dbdaSDaniel P. Berrange             trace_vnc_auth_fail(vs, vs->auth,
27417364dbdaSDaniel P. Berrange                                 "Unsupported auth method for v3.3", "");
27423e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
27433e230dd2SCorentin Chary             vnc_flush(vs);
27443e230dd2SCorentin Chary             vnc_client_error(vs);
27453e230dd2SCorentin Chary        }
27463e230dd2SCorentin Chary     } else {
27473e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
27487e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
27493e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
27503e230dd2SCorentin Chary         vnc_flush(vs);
27513e230dd2SCorentin Chary     }
27523e230dd2SCorentin Chary 
27533e230dd2SCorentin Chary     return 0;
27543e230dd2SCorentin Chary }
27553e230dd2SCorentin Chary 
2756999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2757999342a0SCorentin Chary {
2758999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2759999342a0SCorentin Chary 
2760999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2761999342a0SCorentin Chary }
2762999342a0SCorentin Chary 
27637d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
27647d964c9dSCorentin Chary {
27657d964c9dSCorentin Chary     int i, j;
27667d964c9dSCorentin Chary 
27677d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
27687d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
27697d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
27707d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
27717d964c9dSCorentin Chary 
2772207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2773207f328aSCorentin Chary         for (i = x; i <= w; i++) {
27747d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
27757d964c9dSCorentin Chary         }
27767d964c9dSCorentin Chary     }
27777d964c9dSCorentin Chary }
27787d964c9dSCorentin Chary 
27797d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
27807d964c9dSCorentin Chary {
27817d964c9dSCorentin Chary     VncState *vs;
27827d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
27837d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
27847d964c9dSCorentin Chary     int has_dirty = 0;
27857d964c9dSCorentin Chary 
27865a3804dbSMarc-André Lureau     y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
27875a3804dbSMarc-André Lureau     x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
27887d964c9dSCorentin Chary 
27897d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2790bc2429b9SCorentin Chary         int j;
27917d964c9dSCorentin Chary 
27927d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
27937d964c9dSCorentin Chary         if (vs->output.offset) {
27947d964c9dSCorentin Chary             continue;
27957d964c9dSCorentin Chary         }
27967d964c9dSCorentin Chary 
27977d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
27987d964c9dSCorentin Chary             continue;
27997d964c9dSCorentin Chary         }
2800207f328aSCorentin Chary 
28017d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
28027d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2803b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2804b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2805b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
28067d964c9dSCorentin Chary         }
28077d964c9dSCorentin Chary         has_dirty++;
28087d964c9dSCorentin Chary     }
2809207f328aSCorentin Chary 
28107d964c9dSCorentin Chary     return has_dirty;
28117d964c9dSCorentin Chary }
28127d964c9dSCorentin Chary 
28137d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2814999342a0SCorentin Chary {
2815eebe0b79SGerd Hoffmann     int width = MIN(pixman_image_get_width(vd->guest.fb),
2816eebe0b79SGerd Hoffmann                     pixman_image_get_width(vd->server));
2817eebe0b79SGerd Hoffmann     int height = MIN(pixman_image_get_height(vd->guest.fb),
2818eebe0b79SGerd Hoffmann                      pixman_image_get_height(vd->server));
2819999342a0SCorentin Chary     int x, y;
2820999342a0SCorentin Chary     struct timeval res;
28217d964c9dSCorentin Chary     int has_dirty = 0;
2822999342a0SCorentin Chary 
28239f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
28249f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2825999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2826999342a0SCorentin Chary 
2827999342a0SCorentin Chary             rect->updated = false;
2828999342a0SCorentin Chary         }
2829999342a0SCorentin Chary     }
2830999342a0SCorentin Chary 
2831ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2832999342a0SCorentin Chary 
2833999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
28347d964c9dSCorentin Chary         return has_dirty;
2835999342a0SCorentin Chary     }
2836999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
2837999342a0SCorentin Chary 
28389f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
28399f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2840999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2841999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
2842999342a0SCorentin Chary             struct timeval min, max;
2843999342a0SCorentin Chary 
2844999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
2845999342a0SCorentin Chary                 continue ;
2846999342a0SCorentin Chary             }
2847999342a0SCorentin Chary 
2848999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2849ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
2850999342a0SCorentin Chary 
2851999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2852999342a0SCorentin Chary                 rect->freq = 0;
28537d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2854999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
2855999342a0SCorentin Chary                 continue ;
2856999342a0SCorentin Chary             }
2857999342a0SCorentin Chary 
2858999342a0SCorentin Chary             min = rect->times[rect->idx];
2859999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2860ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
2861999342a0SCorentin Chary 
2862999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2863999342a0SCorentin Chary             rect->freq /= count;
2864999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
2865999342a0SCorentin Chary         }
2866999342a0SCorentin Chary     }
28677d964c9dSCorentin Chary     return has_dirty;
2868999342a0SCorentin Chary }
2869999342a0SCorentin Chary 
2870999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2871999342a0SCorentin Chary {
2872999342a0SCorentin Chary     int i, j;
2873999342a0SCorentin Chary     double total = 0;
2874999342a0SCorentin Chary     int num = 0;
2875999342a0SCorentin Chary 
28765a3804dbSMarc-André Lureau     x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
28775a3804dbSMarc-André Lureau     y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2878999342a0SCorentin Chary 
2879999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2880999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2881999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
2882999342a0SCorentin Chary             num++;
2883999342a0SCorentin Chary         }
2884999342a0SCorentin Chary     }
2885999342a0SCorentin Chary 
2886999342a0SCorentin Chary     if (num) {
2887999342a0SCorentin Chary         return total / num;
2888999342a0SCorentin Chary     } else {
2889999342a0SCorentin Chary         return 0;
2890999342a0SCorentin Chary     }
2891999342a0SCorentin Chary }
2892999342a0SCorentin Chary 
2893999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2894999342a0SCorentin Chary {
2895999342a0SCorentin Chary     VncRectStat *rect;
2896999342a0SCorentin Chary 
2897999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
2898999342a0SCorentin Chary     if (rect->updated) {
2899999342a0SCorentin Chary         return ;
2900999342a0SCorentin Chary     }
2901999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
2902999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2903999342a0SCorentin Chary     rect->updated = true;
2904999342a0SCorentin Chary }
2905999342a0SCorentin Chary 
29063e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
29073e230dd2SCorentin Chary {
2908bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
2909bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
2910bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
2911bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
2912eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
291312b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
29143e230dd2SCorentin Chary     VncState *vs;
29153e230dd2SCorentin Chary     int has_dirty = 0;
29169f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
29173e230dd2SCorentin Chary 
291880e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
2919999342a0SCorentin Chary 
292080e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
2921999342a0SCorentin Chary         gettimeofday(&tv, NULL);
29227d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
292380e0c8c3SCorentin Chary     }
2924999342a0SCorentin Chary 
29253e230dd2SCorentin Chary     /*
29263e230dd2SCorentin Chary      * Walk through the guest dirty map.
29273e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
29283e230dd2SCorentin Chary      * Update server dirty map.
29293e230dd2SCorentin Chary      */
2930bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2931eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
2932eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
2933bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2934bea60dd7SPeter Lieven                     server_stride);
29359f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
29369f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
29379f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
293812b316d4SPeter Lieven     } else {
2939eb8934b0SGerd Hoffmann         int guest_bpp =
2940eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
294112b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
294212b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
2943659c90eeSMarc-André Lureau         guest_ll = pixman_image_get_width(vd->guest.fb) * (DIV_ROUND_UP(guest_bpp, 8));
29449f64916dSGerd Hoffmann     }
2945eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
294612b316d4SPeter Lieven 
294712b316d4SPeter Lieven     for (;;) {
29483e230dd2SCorentin Chary         int x;
294912b316d4SPeter Lieven         uint8_t *guest_ptr, *server_ptr;
295012b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
295112b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(&vd->guest),
295212b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(&vd->guest));
295312b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
295412b316d4SPeter Lieven             /* no more dirty bits */
295512b316d4SPeter Lieven             break;
295612b316d4SPeter Lieven         }
295712b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
295812b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
295912b316d4SPeter Lieven 
296012b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
29613e230dd2SCorentin Chary 
29629f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2963bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
29649f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
29659f64916dSGerd Hoffmann         } else {
296612b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
29679f64916dSGerd Hoffmann         }
296812b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
29693e230dd2SCorentin Chary 
297012b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
297112b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2972bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
297312b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
29743e230dd2SCorentin Chary                 continue;
2975b4c85ddcSPeter Lieven             }
2976eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
2977eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
2978bea60dd7SPeter Lieven             }
2979eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
2980bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
29813e230dd2SCorentin Chary                 continue;
2982b4c85ddcSPeter Lieven             }
2983bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
298412b316d4SPeter Lieven             if (!vd->non_adaptive) {
298512b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
298612b316d4SPeter Lieven                                  y, &tv);
298712b316d4SPeter Lieven             }
29883e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
298912b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
29903e230dd2SCorentin Chary             }
29913e230dd2SCorentin Chary             has_dirty++;
29923e230dd2SCorentin Chary         }
299312b316d4SPeter Lieven 
299412b316d4SPeter Lieven         y++;
29953e230dd2SCorentin Chary     }
29969f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
29973e230dd2SCorentin Chary     return has_dirty;
29983e230dd2SCorentin Chary }
29993e230dd2SCorentin Chary 
30000f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
30013e230dd2SCorentin Chary {
30020f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
30033e230dd2SCorentin Chary     VncState *vs, *vn;
30043e230dd2SCorentin Chary     int has_dirty, rects = 0;
30053e230dd2SCorentin Chary 
30069d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
30079d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
30089d6b2070SChenLiang         return;
30099d6b2070SChenLiang     }
30109d6b2070SChenLiang 
30111d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
30123e230dd2SCorentin Chary 
3013bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
30140f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3015bd023f95SCorentin Chary         return;
3016bd023f95SCorentin Chary     }
3017bd023f95SCorentin Chary 
30183e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
3019bd023f95SCorentin Chary     vnc_unlock_display(vd);
30203e230dd2SCorentin Chary 
30213e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
30226af998dbSDaniel P. Berrange         rects += vnc_update_client(vs, has_dirty);
30233e230dd2SCorentin Chary         /* vs might be free()ed here */
30243e230dd2SCorentin Chary     }
3025bd023f95SCorentin Chary 
30263e230dd2SCorentin Chary     if (has_dirty && rects) {
30270f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
30280f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
30290f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
30300f7b2864SGerd Hoffmann         }
30313e230dd2SCorentin Chary     } else {
30320f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
30330f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
30340f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
30353e230dd2SCorentin Chary         }
30363e230dd2SCorentin Chary     }
30373e230dd2SCorentin Chary }
30383e230dd2SCorentin Chary 
303904d2529dSDaniel P. Berrange static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
30402c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
30413e230dd2SCorentin Chary {
3042fedf0d35SMarkus Armbruster     VncState *vs = g_new0(VncState, 1);
304390cd03a3SDaniel P. Berrange     bool first_client = QTAILQ_EMPTY(&vd->clients);
30447d964c9dSCorentin Chary     int i;
30457d964c9dSCorentin Chary 
3046ad6374c4SDaniel P. Berrange     trace_vnc_client_connect(vs, sioc);
304704d2529dSDaniel P. Berrange     vs->sioc = sioc;
304804d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->sioc));
304904d2529dSDaniel P. Berrange     vs->ioc = QIO_CHANNEL(sioc);
305004d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->ioc));
3051d616ccc5SGerd Hoffmann     vs->vd = vd;
30527e7e2ebcSDaniel P. Berrange 
305304d2529dSDaniel P. Berrange     buffer_init(&vs->input,          "vnc-input/%p", sioc);
305404d2529dSDaniel P. Berrange     buffer_init(&vs->output,         "vnc-output/%p", sioc);
305504d2529dSDaniel P. Berrange     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3056543b9580SGerd Hoffmann 
305704d2529dSDaniel P. Berrange     buffer_init(&vs->tight.tight,    "vnc-tight/%p", sioc);
305804d2529dSDaniel P. Berrange     buffer_init(&vs->tight.zlib,     "vnc-tight-zlib/%p", sioc);
305904d2529dSDaniel P. Berrange     buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
3060543b9580SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
306104d2529dSDaniel P. Berrange     buffer_init(&vs->tight.jpeg,     "vnc-tight-jpeg/%p", sioc);
3062543b9580SGerd Hoffmann #endif
3063543b9580SGerd Hoffmann #ifdef CONFIG_VNC_PNG
306404d2529dSDaniel P. Berrange     buffer_init(&vs->tight.png,      "vnc-tight-png/%p", sioc);
3065543b9580SGerd Hoffmann #endif
306604d2529dSDaniel P. Berrange     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
306704d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.zrle,      "vnc-zrle/%p", sioc);
306804d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.fb,        "vnc-zrle-fb/%p", sioc);
306904d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.zlib,      "vnc-zrle-zlib/%p", sioc);
3070543b9580SGerd Hoffmann 
30717e7e2ebcSDaniel P. Berrange     if (skipauth) {
30727e7e2ebcSDaniel P. Berrange 	vs->auth = VNC_AUTH_NONE;
30737e7e2ebcSDaniel P. Berrange 	vs->subauth = VNC_AUTH_INVALID;
30747e7e2ebcSDaniel P. Berrange     } else {
3075f9148c8aSDaniel P. Berrange         if (websocket) {
3076f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
3077f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
3078f9148c8aSDaniel P. Berrange         } else {
30797e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
30807e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
30817e7e2ebcSDaniel P. Berrange         }
3082f9148c8aSDaniel P. Berrange     }
308304d2529dSDaniel P. Berrange     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
308404d2529dSDaniel P. Berrange               sioc, websocket, vs->auth, vs->subauth);
30857e7e2ebcSDaniel P. Berrange 
30867267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
30877d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3088fedf0d35SMarkus Armbruster         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
30897d964c9dSCorentin Chary     }
30903e230dd2SCorentin Chary 
309104d2529dSDaniel P. Berrange     VNC_DEBUG("New client on socket %p\n", vs->sioc);
30920f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
309304d2529dSDaniel P. Berrange     qio_channel_set_blocking(vs->ioc, false, NULL);
3094a75d6f07SBrandon Carpenter     if (vs->ioc_tag) {
3095a75d6f07SBrandon Carpenter         g_source_remove(vs->ioc_tag);
3096a75d6f07SBrandon Carpenter     }
30977536ee4bSTim Hardeck     if (websocket) {
30987536ee4bSTim Hardeck         vs->websocket = 1;
309938e5756aSDaniel P. Berrange         if (vd->tlscreds) {
310004d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
310104d2529dSDaniel P. Berrange                 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
31023e305e4aSDaniel P. Berrange         } else {
310304d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
310404d2529dSDaniel P. Berrange                 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
31050057a0d5STim Hardeck         }
310604d2529dSDaniel P. Berrange     } else {
310704d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
310804d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
31097536ee4bSTim Hardeck     }
31103e230dd2SCorentin Chary 
31113e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3112fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
31138cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
31143e230dd2SCorentin Chary 
31153e230dd2SCorentin Chary     vs->last_x = -1;
31163e230dd2SCorentin Chary     vs->last_y = -1;
31173e230dd2SCorentin Chary 
31183e230dd2SCorentin Chary     vs->as.freq = 44100;
31193e230dd2SCorentin Chary     vs->as.nchannels = 2;
31203e230dd2SCorentin Chary     vs->as.fmt = AUD_FMT_S16;
31213e230dd2SCorentin Chary     vs->as.endianness = 0;
31223e230dd2SCorentin Chary 
3123bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3124175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3125bd023f95SCorentin Chary 
3126e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3127c7628bffSGerd Hoffmann     if (first_client) {
3128c7628bffSGerd Hoffmann         vnc_update_server_surface(vd);
3129c7628bffSGerd Hoffmann     }
31303e230dd2SCorentin Chary 
31311d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
31323e230dd2SCorentin Chary 
313390cd03a3SDaniel P. Berrange     if (!vs->websocket) {
3134dbee9897SDaniel P. Berrange         vnc_start_protocol(vs);
313590cd03a3SDaniel P. Berrange     }
313690cd03a3SDaniel P. Berrange 
313790cd03a3SDaniel P. Berrange     if (vd->num_connecting > vd->connections_limit) {
313890cd03a3SDaniel P. Berrange         QTAILQ_FOREACH(vs, &vd->clients, next) {
313990cd03a3SDaniel P. Berrange             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
314090cd03a3SDaniel P. Berrange                 vnc_disconnect_start(vs);
314190cd03a3SDaniel P. Berrange                 return;
314290cd03a3SDaniel P. Berrange             }
314390cd03a3SDaniel P. Berrange         }
314490cd03a3SDaniel P. Berrange     }
314590cd03a3SDaniel P. Berrange }
314690cd03a3SDaniel P. Berrange 
3147dbee9897SDaniel P. Berrange void vnc_start_protocol(VncState *vs)
314890cd03a3SDaniel P. Berrange {
31493e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
31503e230dd2SCorentin Chary     vnc_flush(vs);
31513e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
31523e230dd2SCorentin Chary 
31533e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
31543e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
31553e230dd2SCorentin Chary }
31563e230dd2SCorentin Chary 
315713e1d0e7SDaniel P. Berrange static void vnc_listen_io(QIONetListener *listener,
315813e1d0e7SDaniel P. Berrange                           QIOChannelSocket *cioc,
315904d2529dSDaniel P. Berrange                           void *opaque)
31603e230dd2SCorentin Chary {
3161bf01c179SDaniel P. Berrange     VncDisplay *vd = opaque;
316213e1d0e7SDaniel P. Berrange     bool isWebsock = listener == vd->wslistener;
31634ee74fa7SDaniel P. Berrange 
316413e1d0e7SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(cioc),
31654ee74fa7SDaniel P. Berrange                          isWebsock ? "vnc-ws-server" : "vnc-server");
316613e1d0e7SDaniel P. Berrange     qio_channel_set_delay(QIO_CHANNEL(cioc), false);
316713e1d0e7SDaniel P. Berrange     vnc_connect(vd, cioc, false, isWebsock);
31687536ee4bSTim Hardeck }
31697536ee4bSTim Hardeck 
31707c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
31717c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
31720f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
31737c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3174c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
317534da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
31767c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
31777c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
31787c20b4a3SGerd Hoffmann };
31797c20b4a3SGerd Hoffmann 
318014f7143eSGerd Hoffmann void vnc_display_init(const char *id)
31813e230dd2SCorentin Chary {
3182bf01c179SDaniel P. Berrange     VncDisplay *vd;
31834db14629SGerd Hoffmann 
31844db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
31854db14629SGerd Hoffmann         return;
31864db14629SGerd Hoffmann     }
3187bf01c179SDaniel P. Berrange     vd = g_malloc0(sizeof(*vd));
31883e230dd2SCorentin Chary 
3189bf01c179SDaniel P. Berrange     vd->id = strdup(id);
3190bf01c179SDaniel P. Berrange     QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
31913e230dd2SCorentin Chary 
3192bf01c179SDaniel P. Berrange     QTAILQ_INIT(&vd->clients);
3193bf01c179SDaniel P. Berrange     vd->expires = TIME_MAX;
31943e230dd2SCorentin Chary 
319540066175SGerd Hoffmann     if (keyboard_layout) {
319640066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
3197bf01c179SDaniel P. Berrange         vd->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
319840066175SGerd Hoffmann     } else {
3199bf01c179SDaniel P. Berrange         vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
320040066175SGerd Hoffmann     }
32013e230dd2SCorentin Chary 
3202bf01c179SDaniel P. Berrange     if (!vd->kbd_layout) {
32033e230dd2SCorentin Chary         exit(1);
3204bf01c179SDaniel P. Berrange     }
32053e230dd2SCorentin Chary 
3206bf01c179SDaniel P. Berrange     vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3207bf01c179SDaniel P. Berrange     vd->connections_limit = 32;
320812e29b16SDaniel P. Berrange 
3209bf01c179SDaniel P. Berrange     qemu_mutex_init(&vd->mutex);
3210bd023f95SCorentin Chary     vnc_start_worker_thread();
3211bd023f95SCorentin Chary 
3212bf01c179SDaniel P. Berrange     vd->dcl.ops = &dcl_ops;
3213bf01c179SDaniel P. Berrange     register_displaychangelistener(&vd->dcl);
32143e230dd2SCorentin Chary }
32153e230dd2SCorentin Chary 
32163e230dd2SCorentin Chary 
3217bf01c179SDaniel P. Berrange static void vnc_display_close(VncDisplay *vd)
32183e230dd2SCorentin Chary {
3219bf01c179SDaniel P. Berrange     if (!vd) {
32203e230dd2SCorentin Chary         return;
322104d2529dSDaniel P. Berrange     }
3222bf01c179SDaniel P. Berrange     vd->is_unix = false;
32234ee74fa7SDaniel P. Berrange 
322413e1d0e7SDaniel P. Berrange     if (vd->listener) {
322513e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->listener);
322613e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->listener));
322704d2529dSDaniel P. Berrange     }
322813e1d0e7SDaniel P. Berrange     vd->listener = NULL;
322913e1d0e7SDaniel P. Berrange 
323013e1d0e7SDaniel P. Berrange     if (vd->wslistener) {
323113e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->wslistener);
323213e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->wslistener));
32337536ee4bSTim Hardeck     }
323413e1d0e7SDaniel P. Berrange     vd->wslistener = NULL;
32354ee74fa7SDaniel P. Berrange 
3236bf01c179SDaniel P. Berrange     vd->auth = VNC_AUTH_INVALID;
3237bf01c179SDaniel P. Berrange     vd->subauth = VNC_AUTH_INVALID;
3238bf01c179SDaniel P. Berrange     if (vd->tlscreds) {
3239bf01c179SDaniel P. Berrange         object_unparent(OBJECT(vd->tlscreds));
3240bf01c179SDaniel P. Berrange         vd->tlscreds = NULL;
3241bf01c179SDaniel P. Berrange     }
3242bf01c179SDaniel P. Berrange     g_free(vd->tlsaclname);
3243bf01c179SDaniel P. Berrange     vd->tlsaclname = NULL;
3244a54f0d2bSPierre Ossman     if (vd->lock_key_sync) {
3245a54f0d2bSPierre Ossman         qemu_remove_led_event_handler(vd->led);
32462dc120beSGerd Hoffmann         vd->led = NULL;
3247a54f0d2bSPierre Ossman     }
32483e230dd2SCorentin Chary }
32493e230dd2SCorentin Chary 
325014f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
32511cd20f8bSAnthony Liguori {
3252bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
32531cd20f8bSAnthony Liguori 
3254bf01c179SDaniel P. Berrange     if (!vd) {
3255a6aa9d3eSLuiz Capitulino         return -EINVAL;
32561cd20f8bSAnthony Liguori     }
3257bf01c179SDaniel P. Berrange     if (vd->auth == VNC_AUTH_NONE) {
3258cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
32597ea7d36eSMarkus Armbruster                                 "password auth using '-vnc ${dpy},password'.\n");
3260cf864569SGerd Hoffmann         return -EINVAL;
32611cd20f8bSAnthony Liguori     }
32621cd20f8bSAnthony Liguori 
3263bf01c179SDaniel P. Berrange     g_free(vd->password);
3264bf01c179SDaniel P. Berrange     vd->password = g_strdup(password);
3265a6aa9d3eSLuiz Capitulino 
3266a6aa9d3eSLuiz Capitulino     return 0;
32673e230dd2SCorentin Chary }
32683e230dd2SCorentin Chary 
326914f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
32703c9405a0SGerd Hoffmann {
3271bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
32723c9405a0SGerd Hoffmann 
3273bf01c179SDaniel P. Berrange     if (!vd) {
32741643f2b2SGerd Hoffmann         return -EINVAL;
32751643f2b2SGerd Hoffmann     }
32761643f2b2SGerd Hoffmann 
3277bf01c179SDaniel P. Berrange     vd->expires = expires;
32783c9405a0SGerd Hoffmann     return 0;
32793c9405a0SGerd Hoffmann }
32803c9405a0SGerd Hoffmann 
3281bf01c179SDaniel P. Berrange static void vnc_display_print_local_addr(VncDisplay *vd)
32823e230dd2SCorentin Chary {
3283bd269ebcSMarkus Armbruster     SocketAddress *addr;
328404d2529dSDaniel P. Berrange     Error *err = NULL;
32853e230dd2SCorentin Chary 
328613e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
32874ee74fa7SDaniel P. Berrange         return;
32884ee74fa7SDaniel P. Berrange     }
32894ee74fa7SDaniel P. Berrange 
329013e1d0e7SDaniel P. Berrange     addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], &err);
329104d2529dSDaniel P. Berrange     if (!addr) {
329233df7bf3SPaolo Bonzini         return;
329304d2529dSDaniel P. Berrange     }
329404d2529dSDaniel P. Berrange 
3295bd269ebcSMarkus Armbruster     if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3296bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
329733df7bf3SPaolo Bonzini         return;
329804d2529dSDaniel P. Berrange     }
329933df7bf3SPaolo Bonzini     error_printf_unless_qmp("VNC server running on %s:%s\n",
3300bd269ebcSMarkus Armbruster                             addr->u.inet.host,
3301bd269ebcSMarkus Armbruster                             addr->u.inet.port);
3302bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
33033e230dd2SCorentin Chary }
33043e230dd2SCorentin Chary 
33054db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
33064db14629SGerd Hoffmann     .name = "vnc",
33074db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
33084db14629SGerd Hoffmann     .implied_opt_name = "vnc",
33094db14629SGerd Hoffmann     .desc = {
33104db14629SGerd Hoffmann         {
33114db14629SGerd Hoffmann             .name = "vnc",
33124db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33134db14629SGerd Hoffmann         },{
33144db14629SGerd Hoffmann             .name = "websocket",
33154db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33164db14629SGerd Hoffmann         },{
33173e305e4aSDaniel P. Berrange             .name = "tls-creds",
33183e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
33193e305e4aSDaniel P. Berrange         },{
33203e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33214db14629SGerd Hoffmann             .name = "x509",
33224db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33234db14629SGerd Hoffmann         },{
33244db14629SGerd Hoffmann             .name = "share",
33254db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
33264db14629SGerd Hoffmann         },{
33271d0d59feSGerd Hoffmann             .name = "display",
33281d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
33291d0d59feSGerd Hoffmann         },{
33301d0d59feSGerd Hoffmann             .name = "head",
33311d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
33321d0d59feSGerd Hoffmann         },{
3333e5f34cddSGerd Hoffmann             .name = "connections",
3334e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3335e5f34cddSGerd Hoffmann         },{
333688428b7aSGonglei             .name = "to",
333788428b7aSGonglei             .type = QEMU_OPT_NUMBER,
333888428b7aSGonglei         },{
333988428b7aSGonglei             .name = "ipv4",
334088428b7aSGonglei             .type = QEMU_OPT_BOOL,
334188428b7aSGonglei         },{
334288428b7aSGonglei             .name = "ipv6",
334388428b7aSGonglei             .type = QEMU_OPT_BOOL,
334488428b7aSGonglei         },{
33454db14629SGerd Hoffmann             .name = "password",
33464db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33474db14629SGerd Hoffmann         },{
33484db14629SGerd Hoffmann             .name = "reverse",
33494db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33504db14629SGerd Hoffmann         },{
33514db14629SGerd Hoffmann             .name = "lock-key-sync",
33524db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33534db14629SGerd Hoffmann         },{
3354c5ce8333SGerd Hoffmann             .name = "key-delay-ms",
3355c5ce8333SGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3356c5ce8333SGerd Hoffmann         },{
33574db14629SGerd Hoffmann             .name = "sasl",
33584db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33594db14629SGerd Hoffmann         },{
33603e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33614db14629SGerd Hoffmann             .name = "tls",
33624db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33634db14629SGerd Hoffmann         },{
33643e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33654db14629SGerd Hoffmann             .name = "x509verify",
33668c7d0645SDaniel P. Berrange             .type = QEMU_OPT_STRING,
33674db14629SGerd Hoffmann         },{
33684db14629SGerd Hoffmann             .name = "acl",
33694db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33704db14629SGerd Hoffmann         },{
33714db14629SGerd Hoffmann             .name = "lossy",
33724db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33734db14629SGerd Hoffmann         },{
33744db14629SGerd Hoffmann             .name = "non-adaptive",
33754db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33764db14629SGerd Hoffmann         },
33774db14629SGerd Hoffmann         { /* end of list */ }
33784db14629SGerd Hoffmann     },
33794db14629SGerd Hoffmann };
33804db14629SGerd Hoffmann 
33810dd72e15SDaniel P. Berrange 
33823e305e4aSDaniel P. Berrange static int
3383eda24e18SDaniel P. Berrange vnc_display_setup_auth(int *auth,
3384eda24e18SDaniel P. Berrange                        int *subauth,
3385eda24e18SDaniel P. Berrange                        QCryptoTLSCreds *tlscreds,
33860dd72e15SDaniel P. Berrange                        bool password,
33870dd72e15SDaniel P. Berrange                        bool sasl,
33883e305e4aSDaniel P. Berrange                        bool websocket,
33893e305e4aSDaniel P. Berrange                        Error **errp)
33900dd72e15SDaniel P. Berrange {
33910dd72e15SDaniel P. Berrange     /*
33920dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
33930dd72e15SDaniel P. Berrange      *
33940dd72e15SDaniel P. Berrange      *   1. none
33950dd72e15SDaniel P. Berrange      *   2. vnc
33960dd72e15SDaniel P. Berrange      *   3. sasl
33970dd72e15SDaniel P. Berrange      *
33980dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
33990dd72e15SDaniel P. Berrange      *
34000dd72e15SDaniel P. Berrange      *   1. clear
34010dd72e15SDaniel P. Berrange      *   2. tls
34020dd72e15SDaniel P. Berrange      *
34030dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
34040dd72e15SDaniel P. Berrange      *
34050dd72e15SDaniel P. Berrange      *   1. anon
34060dd72e15SDaniel P. Berrange      *   2. x509
34070dd72e15SDaniel P. Berrange      *
34080dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
34090dd72e15SDaniel P. Berrange      *
34100dd72e15SDaniel P. Berrange      *   1. clear + none
34110dd72e15SDaniel P. Berrange      *   2. clear + vnc
34120dd72e15SDaniel P. Berrange      *   3. clear + sasl
34130dd72e15SDaniel P. Berrange      *   4. tls + anon + none
34140dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
34150dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
34160dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
34170dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
34180dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
34190dd72e15SDaniel P. Berrange      *
34200dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
34210dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
34220dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
34230dd72e15SDaniel P. Berrange      * sub-auth types.
3424f9148c8aSDaniel P. Berrange      *
3425f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3426f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3427f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3428f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3429f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3430f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3431f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3432f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3433f9148c8aSDaniel P. Berrange      *
3434f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3435f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3436f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
34370dd72e15SDaniel P. Berrange      */
3438eda24e18SDaniel P. Berrange     if (websocket || !tlscreds) {
34390dd72e15SDaniel P. Berrange         if (password) {
34400dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
3441eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_VNC;
34420dd72e15SDaniel P. Berrange         } else if (sasl) {
34430dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3444eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_SASL;
34450dd72e15SDaniel P. Berrange         } else {
34460dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
3447eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_NONE;
34480dd72e15SDaniel P. Berrange         }
3449eda24e18SDaniel P. Berrange         *subauth = VNC_AUTH_INVALID;
3450f9148c8aSDaniel P. Berrange     } else {
3451eda24e18SDaniel P. Berrange         bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3452eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3453eda24e18SDaniel P. Berrange         bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3454eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3455eda24e18SDaniel P. Berrange 
3456eda24e18SDaniel P. Berrange         if (!is_x509 && !is_anon) {
3457eda24e18SDaniel P. Berrange             error_setg(errp,
3458eda24e18SDaniel P. Berrange                        "Unsupported TLS cred type %s",
3459eda24e18SDaniel P. Berrange                        object_get_typename(OBJECT(tlscreds)));
3460eda24e18SDaniel P. Berrange             return -1;
3461eda24e18SDaniel P. Berrange         }
3462eda24e18SDaniel P. Berrange         *auth = VNC_AUTH_VENCRYPT;
3463eda24e18SDaniel P. Berrange         if (password) {
3464eda24e18SDaniel P. Berrange             if (is_x509) {
3465eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3466eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3467eda24e18SDaniel P. Berrange             } else {
3468eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3469eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3470eda24e18SDaniel P. Berrange             }
3471eda24e18SDaniel P. Berrange 
3472eda24e18SDaniel P. Berrange         } else if (sasl) {
3473eda24e18SDaniel P. Berrange             if (is_x509) {
3474eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3475eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3476eda24e18SDaniel P. Berrange             } else {
3477eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3478eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3479eda24e18SDaniel P. Berrange             }
3480eda24e18SDaniel P. Berrange         } else {
3481eda24e18SDaniel P. Berrange             if (is_x509) {
3482eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3483eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3484eda24e18SDaniel P. Berrange             } else {
3485eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3486eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3487eda24e18SDaniel P. Berrange             }
3488f9148c8aSDaniel P. Berrange         }
34890dd72e15SDaniel P. Berrange     }
34903e305e4aSDaniel P. Berrange     return 0;
34910dd72e15SDaniel P. Berrange }
34920dd72e15SDaniel P. Berrange 
34933e305e4aSDaniel P. Berrange 
34943e305e4aSDaniel P. Berrange /*
34953e305e4aSDaniel P. Berrange  * Handle back compat with old CLI syntax by creating some
34963e305e4aSDaniel P. Berrange  * suitable QCryptoTLSCreds objects
34973e305e4aSDaniel P. Berrange  */
34983e305e4aSDaniel P. Berrange static QCryptoTLSCreds *
34993e305e4aSDaniel P. Berrange vnc_display_create_creds(bool x509,
35003e305e4aSDaniel P. Berrange                          bool x509verify,
35013e305e4aSDaniel P. Berrange                          const char *dir,
35023e305e4aSDaniel P. Berrange                          const char *id,
35033e305e4aSDaniel P. Berrange                          Error **errp)
35043e305e4aSDaniel P. Berrange {
35053e305e4aSDaniel P. Berrange     gchar *credsid = g_strdup_printf("tlsvnc%s", id);
35063e305e4aSDaniel P. Berrange     Object *parent = object_get_objects_root();
35073e305e4aSDaniel P. Berrange     Object *creds;
35083e305e4aSDaniel P. Berrange     Error *err = NULL;
35093e305e4aSDaniel P. Berrange 
35103e305e4aSDaniel P. Berrange     if (x509) {
35113e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
35123e305e4aSDaniel P. Berrange                                       parent,
35133e305e4aSDaniel P. Berrange                                       credsid,
35143e305e4aSDaniel P. Berrange                                       &err,
35153e305e4aSDaniel P. Berrange                                       "endpoint", "server",
35163e305e4aSDaniel P. Berrange                                       "dir", dir,
35173e305e4aSDaniel P. Berrange                                       "verify-peer", x509verify ? "yes" : "no",
35183e305e4aSDaniel P. Berrange                                       NULL);
35193e305e4aSDaniel P. Berrange     } else {
35203e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
35213e305e4aSDaniel P. Berrange                                       parent,
35223e305e4aSDaniel P. Berrange                                       credsid,
35233e305e4aSDaniel P. Berrange                                       &err,
35243e305e4aSDaniel P. Berrange                                       "endpoint", "server",
35253e305e4aSDaniel P. Berrange                                       NULL);
35263e305e4aSDaniel P. Berrange     }
35273e305e4aSDaniel P. Berrange 
35283e305e4aSDaniel P. Berrange     g_free(credsid);
35293e305e4aSDaniel P. Berrange 
35303e305e4aSDaniel P. Berrange     if (err) {
35313e305e4aSDaniel P. Berrange         error_propagate(errp, err);
35323e305e4aSDaniel P. Berrange         return NULL;
35333e305e4aSDaniel P. Berrange     }
35343e305e4aSDaniel P. Berrange 
35353e305e4aSDaniel P. Berrange     return QCRYPTO_TLS_CREDS(creds);
35363e305e4aSDaniel P. Berrange }
35373e305e4aSDaniel P. Berrange 
35383e305e4aSDaniel P. Berrange 
3539275e0d61SDaniel P. Berrange static int vnc_display_get_address(const char *addrstr,
3540275e0d61SDaniel P. Berrange                                    bool websocket,
3541e5766eb4SGerd Hoffmann                                    bool reverse,
3542275e0d61SDaniel P. Berrange                                    int displaynum,
3543275e0d61SDaniel P. Berrange                                    int to,
3544275e0d61SDaniel P. Berrange                                    bool has_ipv4,
3545275e0d61SDaniel P. Berrange                                    bool has_ipv6,
3546275e0d61SDaniel P. Berrange                                    bool ipv4,
3547275e0d61SDaniel P. Berrange                                    bool ipv6,
3548bd269ebcSMarkus Armbruster                                    SocketAddress **retaddr,
3549275e0d61SDaniel P. Berrange                                    Error **errp)
3550275e0d61SDaniel P. Berrange {
3551275e0d61SDaniel P. Berrange     int ret = -1;
3552bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3553275e0d61SDaniel P. Berrange 
3554bd269ebcSMarkus Armbruster     addr = g_new0(SocketAddress, 1);
3555275e0d61SDaniel P. Berrange 
3556275e0d61SDaniel P. Berrange     if (strncmp(addrstr, "unix:", 5) == 0) {
3557bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3558bd269ebcSMarkus Armbruster         addr->u.q_unix.path = g_strdup(addrstr + 5);
3559275e0d61SDaniel P. Berrange 
3560275e0d61SDaniel P. Berrange         if (websocket) {
3561275e0d61SDaniel P. Berrange             error_setg(errp, "UNIX sockets not supported with websock");
3562275e0d61SDaniel P. Berrange             goto cleanup;
3563275e0d61SDaniel P. Berrange         }
3564275e0d61SDaniel P. Berrange 
3565275e0d61SDaniel P. Berrange         if (to) {
3566275e0d61SDaniel P. Berrange             error_setg(errp, "Port range not support with UNIX socket");
3567275e0d61SDaniel P. Berrange             goto cleanup;
3568275e0d61SDaniel P. Berrange         }
3569275e0d61SDaniel P. Berrange         ret = 0;
3570275e0d61SDaniel P. Berrange     } else {
3571275e0d61SDaniel P. Berrange         const char *port;
3572275e0d61SDaniel P. Berrange         size_t hostlen;
3573275e0d61SDaniel P. Berrange         unsigned long long baseport = 0;
3574275e0d61SDaniel P. Berrange         InetSocketAddress *inet;
3575275e0d61SDaniel P. Berrange 
3576275e0d61SDaniel P. Berrange         port = strrchr(addrstr, ':');
3577275e0d61SDaniel P. Berrange         if (!port) {
3578275e0d61SDaniel P. Berrange             if (websocket) {
3579275e0d61SDaniel P. Berrange                 hostlen = 0;
3580275e0d61SDaniel P. Berrange                 port = addrstr;
3581275e0d61SDaniel P. Berrange             } else {
3582275e0d61SDaniel P. Berrange                 error_setg(errp, "no vnc port specified");
3583275e0d61SDaniel P. Berrange                 goto cleanup;
3584275e0d61SDaniel P. Berrange             }
3585275e0d61SDaniel P. Berrange         } else {
3586275e0d61SDaniel P. Berrange             hostlen = port - addrstr;
3587275e0d61SDaniel P. Berrange             port++;
3588275e0d61SDaniel P. Berrange             if (*port == '\0') {
3589275e0d61SDaniel P. Berrange                 error_setg(errp, "vnc port cannot be empty");
3590275e0d61SDaniel P. Berrange                 goto cleanup;
3591275e0d61SDaniel P. Berrange             }
3592275e0d61SDaniel P. Berrange         }
3593275e0d61SDaniel P. Berrange 
3594bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_INET;
3595bd269ebcSMarkus Armbruster         inet = &addr->u.inet;
3596275e0d61SDaniel P. Berrange         if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3597275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr + 1, hostlen - 2);
3598275e0d61SDaniel P. Berrange         } else {
3599275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr, hostlen);
3600275e0d61SDaniel P. Berrange         }
3601275e0d61SDaniel P. Berrange         /* plain VNC port is just an offset, for websocket
3602275e0d61SDaniel P. Berrange          * port is absolute */
3603275e0d61SDaniel P. Berrange         if (websocket) {
3604275e0d61SDaniel P. Berrange             if (g_str_equal(addrstr, "") ||
3605275e0d61SDaniel P. Berrange                 g_str_equal(addrstr, "on")) {
3606396f935aSDaniel P. Berrange                 if (displaynum == -1) {
3607396f935aSDaniel P. Berrange                     error_setg(errp, "explicit websocket port is required");
3608396f935aSDaniel P. Berrange                     goto cleanup;
3609396f935aSDaniel P. Berrange                 }
3610275e0d61SDaniel P. Berrange                 inet->port = g_strdup_printf(
3611275e0d61SDaniel P. Berrange                     "%d", displaynum + 5700);
3612275e0d61SDaniel P. Berrange                 if (to) {
3613275e0d61SDaniel P. Berrange                     inet->has_to = true;
3614275e0d61SDaniel P. Berrange                     inet->to = to + 5700;
3615275e0d61SDaniel P. Berrange                 }
3616275e0d61SDaniel P. Berrange             } else {
3617275e0d61SDaniel P. Berrange                 inet->port = g_strdup(port);
3618275e0d61SDaniel P. Berrange             }
3619275e0d61SDaniel P. Berrange         } else {
3620e5766eb4SGerd Hoffmann             int offset = reverse ? 0 : 5900;
3621275e0d61SDaniel P. Berrange             if (parse_uint_full(port, &baseport, 10) < 0) {
3622275e0d61SDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", port);
3623275e0d61SDaniel P. Berrange                 goto cleanup;
3624275e0d61SDaniel P. Berrange             }
3625275e0d61SDaniel P. Berrange             if (baseport > 65535 ||
3626e5766eb4SGerd Hoffmann                 baseport + offset > 65535) {
3627275e0d61SDaniel P. Berrange                 error_setg(errp, "port %s out of range", port);
3628275e0d61SDaniel P. Berrange                 goto cleanup;
3629275e0d61SDaniel P. Berrange             }
3630275e0d61SDaniel P. Berrange             inet->port = g_strdup_printf(
3631e5766eb4SGerd Hoffmann                 "%d", (int)baseport + offset);
3632275e0d61SDaniel P. Berrange 
3633275e0d61SDaniel P. Berrange             if (to) {
3634275e0d61SDaniel P. Berrange                 inet->has_to = true;
3635e5766eb4SGerd Hoffmann                 inet->to = to + offset;
3636275e0d61SDaniel P. Berrange             }
3637275e0d61SDaniel P. Berrange         }
3638275e0d61SDaniel P. Berrange 
3639275e0d61SDaniel P. Berrange         inet->ipv4 = ipv4;
3640275e0d61SDaniel P. Berrange         inet->has_ipv4 = has_ipv4;
3641275e0d61SDaniel P. Berrange         inet->ipv6 = ipv6;
3642275e0d61SDaniel P. Berrange         inet->has_ipv6 = has_ipv6;
3643275e0d61SDaniel P. Berrange 
3644275e0d61SDaniel P. Berrange         ret = baseport;
3645275e0d61SDaniel P. Berrange     }
3646275e0d61SDaniel P. Berrange 
3647275e0d61SDaniel P. Berrange     *retaddr = addr;
3648275e0d61SDaniel P. Berrange 
3649275e0d61SDaniel P. Berrange  cleanup:
3650275e0d61SDaniel P. Berrange     if (ret < 0) {
3651bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
3652275e0d61SDaniel P. Berrange     }
3653275e0d61SDaniel P. Berrange     return ret;
3654275e0d61SDaniel P. Berrange }
3655275e0d61SDaniel P. Berrange 
36569f26f325SPhilippe Mathieu-Daudé static void vnc_free_addresses(SocketAddress ***retsaddr,
36579f26f325SPhilippe Mathieu-Daudé                                size_t *retnsaddr)
36589f26f325SPhilippe Mathieu-Daudé {
36599f26f325SPhilippe Mathieu-Daudé     size_t i;
36609f26f325SPhilippe Mathieu-Daudé 
36619f26f325SPhilippe Mathieu-Daudé     for (i = 0; i < *retnsaddr; i++) {
36629f26f325SPhilippe Mathieu-Daudé         qapi_free_SocketAddress((*retsaddr)[i]);
36639f26f325SPhilippe Mathieu-Daudé     }
36649f26f325SPhilippe Mathieu-Daudé     g_free(*retsaddr);
36659f26f325SPhilippe Mathieu-Daudé 
36669f26f325SPhilippe Mathieu-Daudé     *retsaddr = NULL;
36679f26f325SPhilippe Mathieu-Daudé     *retnsaddr = 0;
36689f26f325SPhilippe Mathieu-Daudé }
36699f26f325SPhilippe Mathieu-Daudé 
3670275e0d61SDaniel P. Berrange static int vnc_display_get_addresses(QemuOpts *opts,
3671e5766eb4SGerd Hoffmann                                      bool reverse,
3672bd269ebcSMarkus Armbruster                                      SocketAddress ***retsaddr,
3673396f935aSDaniel P. Berrange                                      size_t *retnsaddr,
3674bd269ebcSMarkus Armbruster                                      SocketAddress ***retwsaddr,
3675396f935aSDaniel P. Berrange                                      size_t *retnwsaddr,
3676275e0d61SDaniel P. Berrange                                      Error **errp)
3677275e0d61SDaniel P. Berrange {
3678bd269ebcSMarkus Armbruster     SocketAddress *saddr = NULL;
3679bd269ebcSMarkus Armbruster     SocketAddress *wsaddr = NULL;
3680396f935aSDaniel P. Berrange     QemuOptsIter addriter;
3681396f935aSDaniel P. Berrange     const char *addr;
3682275e0d61SDaniel P. Berrange     int to = qemu_opt_get_number(opts, "to", 0);
3683275e0d61SDaniel P. Berrange     bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3684275e0d61SDaniel P. Berrange     bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3685275e0d61SDaniel P. Berrange     bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3686275e0d61SDaniel P. Berrange     bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3687396f935aSDaniel P. Berrange     int displaynum = -1;
3688396f935aSDaniel P. Berrange     int ret = -1;
3689275e0d61SDaniel P. Berrange 
3690275e0d61SDaniel P. Berrange     *retsaddr = NULL;
3691396f935aSDaniel P. Berrange     *retnsaddr = 0;
3692275e0d61SDaniel P. Berrange     *retwsaddr = NULL;
3693396f935aSDaniel P. Berrange     *retnwsaddr = 0;
3694275e0d61SDaniel P. Berrange 
3695396f935aSDaniel P. Berrange     addr = qemu_opt_get(opts, "vnc");
3696396f935aSDaniel P. Berrange     if (addr == NULL || g_str_equal(addr, "none")) {
3697396f935aSDaniel P. Berrange         ret = 0;
3698396f935aSDaniel P. Berrange         goto cleanup;
3699396f935aSDaniel P. Berrange     }
3700396f935aSDaniel P. Berrange     if (qemu_opt_get(opts, "websocket") &&
3701275e0d61SDaniel P. Berrange         !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3702275e0d61SDaniel P. Berrange         error_setg(errp,
3703275e0d61SDaniel P. Berrange                    "SHA1 hash support is required for websockets");
3704396f935aSDaniel P. Berrange         goto cleanup;
3705275e0d61SDaniel P. Berrange     }
3706275e0d61SDaniel P. Berrange 
3707396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "vnc");
3708396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3709396f935aSDaniel P. Berrange         int rv;
3710e5766eb4SGerd Hoffmann         rv = vnc_display_get_address(addr, false, reverse, 0, to,
3711275e0d61SDaniel P. Berrange                                      has_ipv4, has_ipv6,
3712275e0d61SDaniel P. Berrange                                      ipv4, ipv6,
3713275e0d61SDaniel P. Berrange                                      &saddr, errp);
3714396f935aSDaniel P. Berrange         if (rv < 0) {
3715396f935aSDaniel P. Berrange             goto cleanup;
3716275e0d61SDaniel P. Berrange         }
3717396f935aSDaniel P. Berrange         /* Historical compat - first listen address can be used
3718396f935aSDaniel P. Berrange          * to set the default websocket port
3719396f935aSDaniel P. Berrange          */
3720396f935aSDaniel P. Berrange         if (displaynum == -1) {
3721396f935aSDaniel P. Berrange             displaynum = rv;
3722396f935aSDaniel P. Berrange         }
3723bd269ebcSMarkus Armbruster         *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3724396f935aSDaniel P. Berrange         (*retsaddr)[(*retnsaddr)++] = saddr;
3725396f935aSDaniel P. Berrange     }
3726396f935aSDaniel P. Berrange 
3727396f935aSDaniel P. Berrange     /* If we had multiple primary displays, we don't do defaults
3728396f935aSDaniel P. Berrange      * for websocket, and require explicit config instead. */
3729396f935aSDaniel P. Berrange     if (*retnsaddr > 1) {
3730396f935aSDaniel P. Berrange         displaynum = -1;
3731396f935aSDaniel P. Berrange     }
3732396f935aSDaniel P. Berrange 
3733396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "websocket");
3734396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3735e5766eb4SGerd Hoffmann         if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3736275e0d61SDaniel P. Berrange                                     has_ipv4, has_ipv6,
3737275e0d61SDaniel P. Berrange                                     ipv4, ipv6,
3738275e0d61SDaniel P. Berrange                                     &wsaddr, errp) < 0) {
3739396f935aSDaniel P. Berrange             goto cleanup;
3740275e0d61SDaniel P. Berrange         }
3741396f935aSDaniel P. Berrange 
3742396f935aSDaniel P. Berrange         /* Historical compat - if only a single listen address was
3743396f935aSDaniel P. Berrange          * provided, then this is used to set the default listen
3744396f935aSDaniel P. Berrange          * address for websocket too
3745396f935aSDaniel P. Berrange          */
3746396f935aSDaniel P. Berrange         if (*retnsaddr == 1 &&
3747bd269ebcSMarkus Armbruster             (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3748bd269ebcSMarkus Armbruster             wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3749bd269ebcSMarkus Armbruster             g_str_equal(wsaddr->u.inet.host, "") &&
3750bd269ebcSMarkus Armbruster             !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3751bd269ebcSMarkus Armbruster             g_free(wsaddr->u.inet.host);
3752bd269ebcSMarkus Armbruster             wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3753275e0d61SDaniel P. Berrange         }
3754275e0d61SDaniel P. Berrange 
3755bd269ebcSMarkus Armbruster         *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3756396f935aSDaniel P. Berrange         (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3757396f935aSDaniel P. Berrange     }
3758396f935aSDaniel P. Berrange 
3759396f935aSDaniel P. Berrange     ret = 0;
3760396f935aSDaniel P. Berrange  cleanup:
3761396f935aSDaniel P. Berrange     if (ret < 0) {
37629f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retsaddr, retnsaddr);
37639f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retwsaddr, retnwsaddr);
3764396f935aSDaniel P. Berrange     }
3765396f935aSDaniel P. Berrange     return ret;
3766275e0d61SDaniel P. Berrange }
3767275e0d61SDaniel P. Berrange 
37688bd22f47SDaniel P. Berrange static int vnc_display_connect(VncDisplay *vd,
3769bd269ebcSMarkus Armbruster                                SocketAddress **saddr,
3770396f935aSDaniel P. Berrange                                size_t nsaddr,
3771bd269ebcSMarkus Armbruster                                SocketAddress **wsaddr,
3772396f935aSDaniel P. Berrange                                size_t nwsaddr,
37738bd22f47SDaniel P. Berrange                                Error **errp)
37748bd22f47SDaniel P. Berrange {
37758bd22f47SDaniel P. Berrange     /* connect to viewer */
37768bd22f47SDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
3777396f935aSDaniel P. Berrange     if (nwsaddr != 0) {
37788bd22f47SDaniel P. Berrange         error_setg(errp, "Cannot use websockets in reverse mode");
37798bd22f47SDaniel P. Berrange         return -1;
37808bd22f47SDaniel P. Berrange     }
3781396f935aSDaniel P. Berrange     if (nsaddr != 1) {
3782396f935aSDaniel P. Berrange         error_setg(errp, "Expected a single address in reverse mode");
3783396f935aSDaniel P. Berrange         return -1;
3784396f935aSDaniel P. Berrange     }
3785bd269ebcSMarkus Armbruster     /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3786bd269ebcSMarkus Armbruster     vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
37878bd22f47SDaniel P. Berrange     sioc = qio_channel_socket_new();
37888bd22f47SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3789396f935aSDaniel P. Berrange     if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
37908bd22f47SDaniel P. Berrange         return -1;
37918bd22f47SDaniel P. Berrange     }
37928bd22f47SDaniel P. Berrange     vnc_connect(vd, sioc, false, false);
37938bd22f47SDaniel P. Berrange     object_unref(OBJECT(sioc));
37948bd22f47SDaniel P. Berrange     return 0;
37958bd22f47SDaniel P. Berrange }
37968bd22f47SDaniel P. Berrange 
37978bd22f47SDaniel P. Berrange 
37988bd22f47SDaniel P. Berrange static int vnc_display_listen(VncDisplay *vd,
3799bd269ebcSMarkus Armbruster                               SocketAddress **saddr,
3800396f935aSDaniel P. Berrange                               size_t nsaddr,
3801bd269ebcSMarkus Armbruster                               SocketAddress **wsaddr,
3802396f935aSDaniel P. Berrange                               size_t nwsaddr,
38038bd22f47SDaniel P. Berrange                               Error **errp)
38048bd22f47SDaniel P. Berrange {
3805396f935aSDaniel P. Berrange     size_t i;
38068bd22f47SDaniel P. Berrange 
380713e1d0e7SDaniel P. Berrange     if (nsaddr) {
380813e1d0e7SDaniel P. Berrange         vd->listener = qio_net_listener_new();
380913e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->listener, "vnc-listen");
3810396f935aSDaniel P. Berrange         for (i = 0; i < nsaddr; i++) {
381113e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->listener,
381213e1d0e7SDaniel P. Berrange                                            saddr[i],
38138bd22f47SDaniel P. Berrange                                            errp) < 0)  {
38148bd22f47SDaniel P. Berrange                 return -1;
38158bd22f47SDaniel P. Berrange             }
3816396f935aSDaniel P. Berrange         }
381713e1d0e7SDaniel P. Berrange 
381813e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->listener,
381913e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
382013e1d0e7SDaniel P. Berrange     }
382113e1d0e7SDaniel P. Berrange 
382213e1d0e7SDaniel P. Berrange     if (nwsaddr) {
382313e1d0e7SDaniel P. Berrange         vd->wslistener = qio_net_listener_new();
382413e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3825396f935aSDaniel P. Berrange         for (i = 0; i < nwsaddr; i++) {
382613e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->wslistener,
382713e1d0e7SDaniel P. Berrange                                            wsaddr[i],
38288bd22f47SDaniel P. Berrange                                            errp) < 0)  {
38298bd22f47SDaniel P. Berrange                 return -1;
38308bd22f47SDaniel P. Berrange             }
3831396f935aSDaniel P. Berrange         }
38328bd22f47SDaniel P. Berrange 
383313e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->wslistener,
383413e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
383513e1d0e7SDaniel P. Berrange     }
383613e1d0e7SDaniel P. Berrange 
38378bd22f47SDaniel P. Berrange     return 0;
38388bd22f47SDaniel P. Berrange }
38398bd22f47SDaniel P. Berrange 
38408bd22f47SDaniel P. Berrange 
38414db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
38423e230dd2SCorentin Chary {
3843bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
38444db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3845bd269ebcSMarkus Armbruster     SocketAddress **saddr = NULL, **wsaddr = NULL;
3846396f935aSDaniel P. Berrange     size_t nsaddr, nwsaddr;
3847e2a11d9dSGonglei     const char *share, *device_id;
38481d0d59feSGerd Hoffmann     QemuConsole *con;
3849a2c72de0SGonglei     bool password = false;
3850a2c72de0SGonglei     bool reverse = false;
38513e305e4aSDaniel P. Berrange     const char *credid;
3852a2c72de0SGonglei     bool sasl = false;
3853d169f04bSDaniel P. Berrange #ifdef CONFIG_VNC_SASL
38543e230dd2SCorentin Chary     int saslErr;
38553e230dd2SCorentin Chary #endif
38563e230dd2SCorentin Chary     int acl = 0;
38573e230dd2SCorentin Chary     int lock_key_sync = 1;
3858c5ce8333SGerd Hoffmann     int key_delay_ms;
38593e230dd2SCorentin Chary 
3860bf01c179SDaniel P. Berrange     if (!vd) {
38612d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
38622d55f0e8SPaolo Bonzini         return;
38632d55f0e8SPaolo Bonzini     }
3864bf01c179SDaniel P. Berrange     vnc_display_close(vd);
38654db14629SGerd Hoffmann 
38664db14629SGerd Hoffmann     if (!opts) {
38672d55f0e8SPaolo Bonzini         return;
38684db14629SGerd Hoffmann     }
3869275e0d61SDaniel P. Berrange 
3870e5766eb4SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
3871e5766eb4SGerd Hoffmann     if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3872396f935aSDaniel P. Berrange                                   &wsaddr, &nwsaddr, errp) < 0) {
3873275e0d61SDaniel P. Berrange         goto fail;
3874275e0d61SDaniel P. Berrange     }
3875275e0d61SDaniel P. Berrange 
38764db14629SGerd Hoffmann     password = qemu_opt_get_bool(opts, "password", false);
3877800567a6SDaniel P. Berrange     if (password) {
3878800567a6SDaniel P. Berrange         if (fips_get_state()) {
38792d55f0e8SPaolo Bonzini             error_setg(errp,
38800f66998fSPaul Moore                        "VNC password auth disabled due to FIPS mode, "
38810f66998fSPaul Moore                        "consider using the VeNCrypt or SASL authentication "
38822d55f0e8SPaolo Bonzini                        "methods as an alternative");
38831ce52c78SPaolo Bonzini             goto fail;
38840f66998fSPaul Moore         }
3885800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
3886f844836dSGonglei                 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3887800567a6SDaniel P. Berrange             error_setg(errp,
3888800567a6SDaniel P. Berrange                        "Cipher backend does not support DES RFB algorithm");
3889800567a6SDaniel P. Berrange             goto fail;
3890800567a6SDaniel P. Berrange         }
3891800567a6SDaniel P. Berrange     }
38924db14629SGerd Hoffmann 
38934db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3894d3b0db6dSAlexander Graf     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
38954db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
3896d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
3897d169f04bSDaniel P. Berrange     if (sasl) {
3898d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3899d169f04bSDaniel P. Berrange         goto fail;
3900d169f04bSDaniel P. Berrange     }
3901d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
39023e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
39033e305e4aSDaniel P. Berrange     if (credid) {
39043e305e4aSDaniel P. Berrange         Object *creds;
39053e305e4aSDaniel P. Berrange         if (qemu_opt_get(opts, "tls") ||
39063e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509") ||
39073e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509verify")) {
39083e305e4aSDaniel P. Berrange             error_setg(errp,
3909c62e90afSWolfgang Bumiller                        "'tls-creds' parameter is mutually exclusive with "
39103e305e4aSDaniel P. Berrange                        "'tls', 'x509' and 'x509verify' parameters");
39113e305e4aSDaniel P. Berrange             goto fail;
39123e305e4aSDaniel P. Berrange         }
39133e305e4aSDaniel P. Berrange 
39143e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
39153e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
39163e305e4aSDaniel P. Berrange         if (!creds) {
39173e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
39183e305e4aSDaniel P. Berrange                        credid);
39193e305e4aSDaniel P. Berrange             goto fail;
39203e305e4aSDaniel P. Berrange         }
3921bf01c179SDaniel P. Berrange         vd->tlscreds = (QCryptoTLSCreds *)
39223e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
39233e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
3924bf01c179SDaniel P. Berrange         if (!vd->tlscreds) {
39253e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
39263e305e4aSDaniel P. Berrange                        credid);
39273e305e4aSDaniel P. Berrange             goto fail;
39283e305e4aSDaniel P. Berrange         }
3929bf01c179SDaniel P. Berrange         object_ref(OBJECT(vd->tlscreds));
39303e305e4aSDaniel P. Berrange 
3931bf01c179SDaniel P. Berrange         if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
39323e305e4aSDaniel P. Berrange             error_setg(errp,
39333e305e4aSDaniel P. Berrange                        "Expecting TLS credentials with a server endpoint");
39343e305e4aSDaniel P. Berrange             goto fail;
39353e305e4aSDaniel P. Berrange         }
39363e305e4aSDaniel P. Berrange     } else {
39373e305e4aSDaniel P. Berrange         const char *path;
39383e305e4aSDaniel P. Berrange         bool tls = false, x509 = false, x509verify = false;
39394db14629SGerd Hoffmann         tls  = qemu_opt_get_bool(opts, "tls", false);
39403e305e4aSDaniel P. Berrange         if (tls) {
39414db14629SGerd Hoffmann             path = qemu_opt_get(opts, "x509");
39423e305e4aSDaniel P. Berrange 
39434db14629SGerd Hoffmann             if (path) {
3944a2c72de0SGonglei                 x509 = true;
39453e305e4aSDaniel P. Berrange             } else {
39463e305e4aSDaniel P. Berrange                 path = qemu_opt_get(opts, "x509verify");
39473e305e4aSDaniel P. Berrange                 if (path) {
39483e305e4aSDaniel P. Berrange                     x509 = true;
39493e305e4aSDaniel P. Berrange                     x509verify = true;
39503e305e4aSDaniel P. Berrange                 }
39513e305e4aSDaniel P. Berrange             }
3952bf01c179SDaniel P. Berrange             vd->tlscreds = vnc_display_create_creds(x509,
39533e305e4aSDaniel P. Berrange                                                     x509verify,
39543e305e4aSDaniel P. Berrange                                                     path,
3955bf01c179SDaniel P. Berrange                                                     vd->id,
39563e305e4aSDaniel P. Berrange                                                     errp);
3957bf01c179SDaniel P. Berrange             if (!vd->tlscreds) {
39581ce52c78SPaolo Bonzini                 goto fail;
39593e230dd2SCorentin Chary             }
39603e230dd2SCorentin Chary         }
3961d169f04bSDaniel P. Berrange     }
39624db14629SGerd Hoffmann     acl = qemu_opt_get_bool(opts, "acl", false);
39634db14629SGerd Hoffmann 
39644db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
39654db14629SGerd Hoffmann     if (share) {
39664db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
3967bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_IGNORE;
39684db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
3969bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
39704db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
3971bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
39728cf36489SGerd Hoffmann         } else {
39732d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
39741ce52c78SPaolo Bonzini             goto fail;
39758cf36489SGerd Hoffmann         }
39764db14629SGerd Hoffmann     } else {
3977bf01c179SDaniel P. Berrange         vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
39783e230dd2SCorentin Chary     }
3979bf01c179SDaniel P. Berrange     vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
39803e230dd2SCorentin Chary 
39814db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
3982bf01c179SDaniel P. Berrange     vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
39834db14629SGerd Hoffmann #endif
3984bf01c179SDaniel P. Berrange     vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3985e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
3986e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
3987e22492d3SPeter Lieven      * calculations otherwise */
3988bf01c179SDaniel P. Berrange     if (!vd->lossy) {
3989bf01c179SDaniel P. Berrange         vd->non_adaptive = true;
3990e22492d3SPeter Lieven     }
3991e22492d3SPeter Lieven 
39923e305e4aSDaniel P. Berrange     if (acl) {
3993bf01c179SDaniel P. Berrange         if (strcmp(vd->id, "default") == 0) {
3994bf01c179SDaniel P. Berrange             vd->tlsaclname = g_strdup("vnc.x509dname");
3995c8496408SGerd Hoffmann         } else {
3996bf01c179SDaniel P. Berrange             vd->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vd->id);
3997c8496408SGerd Hoffmann         }
3998bf01c179SDaniel P. Berrange         qemu_acl_init(vd->tlsaclname);
39993e230dd2SCorentin Chary     }
40003e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
40013e230dd2SCorentin Chary     if (acl && sasl) {
4002c8496408SGerd Hoffmann         char *aclname;
4003c8496408SGerd Hoffmann 
4004bf01c179SDaniel P. Berrange         if (strcmp(vd->id, "default") == 0) {
4005c8496408SGerd Hoffmann             aclname = g_strdup("vnc.username");
4006c8496408SGerd Hoffmann         } else {
4007bf01c179SDaniel P. Berrange             aclname = g_strdup_printf("vnc.%s.username", vd->id);
4008c8496408SGerd Hoffmann         }
4009bf01c179SDaniel P. Berrange         vd->sasl.acl = qemu_acl_init(aclname);
4010c8496408SGerd Hoffmann         g_free(aclname);
40113e230dd2SCorentin Chary     }
40123e230dd2SCorentin Chary #endif
40133e230dd2SCorentin Chary 
4014eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4015eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4016eda24e18SDaniel P. Berrange                                sasl, false, errp) < 0) {
4017eda24e18SDaniel P. Berrange         goto fail;
4018eda24e18SDaniel P. Berrange     }
40197364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4020eda24e18SDaniel P. Berrange 
4021eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4022eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4023eda24e18SDaniel P. Berrange                                sasl, true, errp) < 0) {
40243e305e4aSDaniel P. Berrange         goto fail;
40253e305e4aSDaniel P. Berrange     }
40267364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
40273e230dd2SCorentin Chary 
40283e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
40293e230dd2SCorentin Chary     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
40302d55f0e8SPaolo Bonzini         error_setg(errp, "Failed to initialize SASL auth: %s",
40313e230dd2SCorentin Chary                    sasl_errstring(saslErr, NULL, NULL));
40321ce52c78SPaolo Bonzini         goto fail;
40333e230dd2SCorentin Chary     }
40343e230dd2SCorentin Chary #endif
4035bf01c179SDaniel P. Berrange     vd->lock_key_sync = lock_key_sync;
4036a54f0d2bSPierre Ossman     if (lock_key_sync) {
4037a54f0d2bSPierre Ossman         vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4038a54f0d2bSPierre Ossman     }
4039a54f0d2bSPierre Ossman     vd->ledstate = 0;
4040bf01c179SDaniel P. Berrange     vd->key_delay_ms = key_delay_ms;
40413e230dd2SCorentin Chary 
40421d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
40431d0d59feSGerd Hoffmann     if (device_id) {
40441d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
4045f2c1d54cSGerd Hoffmann         Error *err = NULL;
40461d0d59feSGerd Hoffmann 
4047f2c1d54cSGerd Hoffmann         con = qemu_console_lookup_by_device_name(device_id, head, &err);
4048f2c1d54cSGerd Hoffmann         if (err) {
4049f2c1d54cSGerd Hoffmann             error_propagate(errp, err);
40501d0d59feSGerd Hoffmann             goto fail;
40511d0d59feSGerd Hoffmann         }
40521d0d59feSGerd Hoffmann     } else {
40531d0d59feSGerd Hoffmann         con = NULL;
40541d0d59feSGerd Hoffmann     }
40551d0d59feSGerd Hoffmann 
4056bf01c179SDaniel P. Berrange     if (con != vd->dcl.con) {
4057bf01c179SDaniel P. Berrange         unregister_displaychangelistener(&vd->dcl);
4058bf01c179SDaniel P. Berrange         vd->dcl.con = con;
4059bf01c179SDaniel P. Berrange         register_displaychangelistener(&vd->dcl);
40601d0d59feSGerd Hoffmann     }
40611d0d59feSGerd Hoffmann 
4062fa03cb7fSMarc-André Lureau     if (saddr == NULL) {
4063fa03cb7fSMarc-André Lureau         goto cleanup;
4064fa03cb7fSMarc-André Lureau     }
4065fa03cb7fSMarc-André Lureau 
40663e230dd2SCorentin Chary     if (reverse) {
4067396f935aSDaniel P. Berrange         if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4068e0d03b8cSDaniel P. Berrange             goto fail;
40693e230dd2SCorentin Chary         }
40703e230dd2SCorentin Chary     } else {
4071396f935aSDaniel P. Berrange         if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
40723d00ac1aSCole Robinson             goto fail;
40733d00ac1aSCole Robinson         }
40743e230dd2SCorentin Chary     }
4075e0d03b8cSDaniel P. Berrange 
4076275e0d61SDaniel P. Berrange     if (qemu_opt_get(opts, "to")) {
4077bf01c179SDaniel P. Berrange         vnc_display_print_local_addr(vd);
407833df7bf3SPaolo Bonzini     }
407933df7bf3SPaolo Bonzini 
4080396f935aSDaniel P. Berrange  cleanup:
40819f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&saddr, &nsaddr);
40829f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&wsaddr, &nwsaddr);
40832d55f0e8SPaolo Bonzini     return;
40841ce52c78SPaolo Bonzini 
40851ce52c78SPaolo Bonzini fail:
40864ee74fa7SDaniel P. Berrange     vnc_display_close(vd);
4087396f935aSDaniel P. Berrange     goto cleanup;
40883e230dd2SCorentin Chary }
408913661089SDaniel P. Berrange 
409014f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
409113661089SDaniel P. Berrange {
4092bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
409304d2529dSDaniel P. Berrange     QIOChannelSocket *sioc;
409413661089SDaniel P. Berrange 
4095bf01c179SDaniel P. Berrange     if (!vd) {
4096d616ccc5SGerd Hoffmann         return;
4097d616ccc5SGerd Hoffmann     }
409804d2529dSDaniel P. Berrange 
409904d2529dSDaniel P. Berrange     sioc = qio_channel_socket_new_fd(csock, NULL);
410004d2529dSDaniel P. Berrange     if (sioc) {
410110bcfe58SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4102bf01c179SDaniel P. Berrange         vnc_connect(vd, sioc, skipauth, false);
410304d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
410404d2529dSDaniel P. Berrange     }
410513661089SDaniel P. Berrange }
41064db14629SGerd Hoffmann 
41079634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
41082779672fSGonglei {
41092779672fSGonglei     int i = 2;
41102779672fSGonglei     char *id;
41112779672fSGonglei 
41122779672fSGonglei     id = g_strdup("default");
41132779672fSGonglei     while (qemu_opts_find(olist, id)) {
41142779672fSGonglei         g_free(id);
41152779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
41162779672fSGonglei     }
41172779672fSGonglei     qemu_opts_set_id(opts, id);
41182779672fSGonglei }
41192779672fSGonglei 
412070b94331SMarkus Armbruster QemuOpts *vnc_parse(const char *str, Error **errp)
41214db14629SGerd Hoffmann {
41224db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
412370b94331SMarkus Armbruster     QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
412481607cbfSGonglei     const char *id;
41254db14629SGerd Hoffmann 
412681607cbfSGonglei     if (!opts) {
412781607cbfSGonglei         return NULL;
412881607cbfSGonglei     }
412981607cbfSGonglei 
413081607cbfSGonglei     id = qemu_opts_id(opts);
41314db14629SGerd Hoffmann     if (!id) {
41324db14629SGerd Hoffmann         /* auto-assign id if not present */
41332779672fSGonglei         vnc_auto_assign_id(olist, opts);
41349634f4e3SGerd Hoffmann     }
41359634f4e3SGerd Hoffmann     return opts;
41364db14629SGerd Hoffmann }
41374db14629SGerd Hoffmann 
413828d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
41399634f4e3SGerd Hoffmann {
41409634f4e3SGerd Hoffmann     Error *local_err = NULL;
41419634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
41429634f4e3SGerd Hoffmann 
41439634f4e3SGerd Hoffmann     assert(id);
41444db14629SGerd Hoffmann     vnc_display_init(id);
41454db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
41464db14629SGerd Hoffmann     if (local_err != NULL) {
4147c29b77f9SMarkus Armbruster         error_reportf_err(local_err, "Failed to start VNC server: ");
41484db14629SGerd Hoffmann         exit(1);
41494db14629SGerd Hoffmann     }
41504db14629SGerd Hoffmann     return 0;
41514db14629SGerd Hoffmann }
41524db14629SGerd Hoffmann 
41534db14629SGerd Hoffmann static void vnc_register_config(void)
41544db14629SGerd Hoffmann {
41554db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
41564db14629SGerd Hoffmann }
415734294e2fSEduardo Habkost opts_init(vnc_register_config);
4158