xref: /openbmc/qemu/ui/vnc.c (revision 6c08964b415a7bfd3b3ed65e7309cc3ffdb096b8)
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"
280bf41cabSGerd Hoffmann #include "qemu-common.h"
293e230dd2SCorentin Chary #include "vnc.h"
30bd023f95SCorentin Chary #include "vnc-jobs.h"
3140066175SGerd Hoffmann #include "trace.h"
3213d4ff07SMarkus Armbruster #include "hw/qdev-core.h"
339c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
347b5fa0b5SDaniel P. Berrangé #include "sysemu/runstate.h"
35d49b6836SMarkus Armbruster #include "qemu/error-report.h"
36db725815SMarkus Armbruster #include "qemu/main-loop.h"
370b8fa32fSMarkus Armbruster #include "qemu/module.h"
38922a01a0SMarkus Armbruster #include "qemu/option.h"
391de7afc9SPaolo Bonzini #include "qemu/sockets.h"
401de7afc9SPaolo Bonzini #include "qemu/timer.h"
41b76806d4SDaniel P. Berrange #include "authz/list.h"
424db14629SGerd Hoffmann #include "qemu/config-file.h"
435d75648bSMarkus Armbruster #include "qapi/qapi-emit-events.h"
445d75648bSMarkus Armbruster #include "qapi/qapi-events-ui.h"
45e688df6bSMarkus Armbruster #include "qapi/error.h"
469af23989SMarkus Armbruster #include "qapi/qapi-commands-ui.h"
478d447d10SGerd Hoffmann #include "ui/input.h"
488e9b0d24SDaniel P. Berrange #include "crypto/hash.h"
493c52bf0cSPhilippe Mathieu-Daudé #include "crypto/tlscreds.h"
503e305e4aSDaniel P. Berrange #include "crypto/tlscredsanon.h"
513e305e4aSDaniel P. Berrange #include "crypto/tlscredsx509.h"
52f7b2502cSRichard Henderson #include "crypto/random.h"
536c6840e9SDaniel P. Berrangé #include "crypto/secret_common.h"
543e305e4aSDaniel P. Berrange #include "qom/object_interfaces.h"
55f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
56653c9747SPaolo Bonzini #include "qemu/help_option.h"
5757a6d6d5SDaniel P. Berrange #include "io/dns-resolver.h"
583e230dd2SCorentin Chary 
590f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
603e230dd2SCorentin Chary #define VNC_REFRESH_INTERVAL_INC  50
610f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
62999342a0SCorentin Chary static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
63999342a0SCorentin Chary static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
643e230dd2SCorentin Chary 
653e230dd2SCorentin Chary #include "vnc_keysym.h"
66800567a6SDaniel P. Berrange #include "crypto/cipher.h"
673e230dd2SCorentin Chary 
68d616ccc5SGerd Hoffmann static QTAILQ_HEAD(, VncDisplay) vnc_displays =
69d616ccc5SGerd Hoffmann     QTAILQ_HEAD_INITIALIZER(vnc_displays);
703e230dd2SCorentin Chary 
713e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs);
72e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs);
733e230dd2SCorentin Chary 
748cf36489SGerd Hoffmann static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
758cf36489SGerd Hoffmann {
768cf36489SGerd Hoffmann #ifdef _VNC_DEBUG
778cf36489SGerd Hoffmann     static const char *mn[] = {
788cf36489SGerd Hoffmann         [0]                           = "undefined",
798cf36489SGerd Hoffmann         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
808cf36489SGerd Hoffmann         [VNC_SHARE_MODE_SHARED]       = "shared",
818cf36489SGerd Hoffmann         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
828cf36489SGerd Hoffmann         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
838cf36489SGerd Hoffmann     };
8404d2529dSDaniel P. Berrange     fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
8504d2529dSDaniel P. Berrange             vs->ioc, mn[vs->share_mode], mn[mode]);
868cf36489SGerd Hoffmann #endif
878cf36489SGerd Hoffmann 
88e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
89e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
90e5f34cddSGerd Hoffmann         vs->vd->num_connecting--;
91e5f34cddSGerd Hoffmann         break;
92e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
93e5f34cddSGerd Hoffmann         vs->vd->num_shared--;
94e5f34cddSGerd Hoffmann         break;
95e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
968cf36489SGerd Hoffmann         vs->vd->num_exclusive--;
97e5f34cddSGerd Hoffmann         break;
98e5f34cddSGerd Hoffmann     default:
99e5f34cddSGerd Hoffmann         break;
1008cf36489SGerd Hoffmann     }
101e5f34cddSGerd Hoffmann 
1028cf36489SGerd Hoffmann     vs->share_mode = mode;
103e5f34cddSGerd Hoffmann 
104e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
105e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
106e5f34cddSGerd Hoffmann         vs->vd->num_connecting++;
107e5f34cddSGerd Hoffmann         break;
108e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
109e5f34cddSGerd Hoffmann         vs->vd->num_shared++;
110e5f34cddSGerd Hoffmann         break;
111e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
1128cf36489SGerd Hoffmann         vs->vd->num_exclusive++;
113e5f34cddSGerd Hoffmann         break;
114e5f34cddSGerd Hoffmann     default:
115e5f34cddSGerd Hoffmann         break;
1168cf36489SGerd Hoffmann     }
1178cf36489SGerd Hoffmann }
1188cf36489SGerd Hoffmann 
1193e230dd2SCorentin Chary 
120bd269ebcSMarkus Armbruster static void vnc_init_basic_info(SocketAddress *addr,
12198481bfcSEric Blake                                 VncBasicInfo *info,
12298481bfcSEric Blake                                 Error **errp)
1233e230dd2SCorentin Chary {
12404d2529dSDaniel P. Berrange     switch (addr->type) {
125bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_INET:
126bd269ebcSMarkus Armbruster         info->host = g_strdup(addr->u.inet.host);
127bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.inet.port);
128bd269ebcSMarkus Armbruster         if (addr->u.inet.ipv6) {
12904d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
13004d2529dSDaniel P. Berrange         } else {
13104d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
13204d2529dSDaniel P. Berrange         }
13304d2529dSDaniel P. Berrange         break;
1343e230dd2SCorentin Chary 
135bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_UNIX:
13604d2529dSDaniel P. Berrange         info->host = g_strdup("");
137bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.q_unix.path);
13804d2529dSDaniel P. Berrange         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
13904d2529dSDaniel P. Berrange         break;
14004d2529dSDaniel P. Berrange 
141bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_VSOCK:
142bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_FD:
143a6c76285SMarkus Armbruster         error_setg(errp, "Unsupported socket address type %s",
144977c736fSMarkus Armbruster                    SocketAddressType_str(addr->type));
14504d2529dSDaniel P. Berrange         break;
146a6c76285SMarkus Armbruster     default:
147a6c76285SMarkus Armbruster         abort();
14804d2529dSDaniel P. Berrange     }
14904d2529dSDaniel P. Berrange 
15098481bfcSEric Blake     return;
1513e230dd2SCorentin Chary }
1523e230dd2SCorentin Chary 
15304d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
15404d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
15598481bfcSEric Blake                                                  Error **errp)
1563e230dd2SCorentin Chary {
157bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1583e230dd2SCorentin Chary 
159624cdd46SDaniel P. Berrange     if (!ioc) {
160624cdd46SDaniel P. Berrange         error_setg(errp, "No listener socket available");
161624cdd46SDaniel P. Berrange         return;
162624cdd46SDaniel P. Berrange     }
163624cdd46SDaniel P. Berrange 
16404d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, errp);
16504d2529dSDaniel P. Berrange     if (!addr) {
16698481bfcSEric Blake         return;
1673e230dd2SCorentin Chary     }
1683e230dd2SCorentin Chary 
16904d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
170bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1713e230dd2SCorentin Chary }
1723e230dd2SCorentin Chary 
17304d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
17404d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
17598481bfcSEric Blake                                                  Error **errp)
1763e230dd2SCorentin Chary {
177bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1783e230dd2SCorentin Chary 
17904d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_remote_address(ioc, errp);
18004d2529dSDaniel P. Berrange     if (!addr) {
18198481bfcSEric Blake         return;
1823e230dd2SCorentin Chary     }
1833e230dd2SCorentin Chary 
18404d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
185bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1863e230dd2SCorentin Chary }
1873e230dd2SCorentin Chary 
1883e230dd2SCorentin Chary static const char *vnc_auth_name(VncDisplay *vd) {
1893e230dd2SCorentin Chary     switch (vd->auth) {
1903e230dd2SCorentin Chary     case VNC_AUTH_INVALID:
1913e230dd2SCorentin Chary         return "invalid";
1923e230dd2SCorentin Chary     case VNC_AUTH_NONE:
1933e230dd2SCorentin Chary         return "none";
1943e230dd2SCorentin Chary     case VNC_AUTH_VNC:
1953e230dd2SCorentin Chary         return "vnc";
1963e230dd2SCorentin Chary     case VNC_AUTH_RA2:
1973e230dd2SCorentin Chary         return "ra2";
1983e230dd2SCorentin Chary     case VNC_AUTH_RA2NE:
1993e230dd2SCorentin Chary         return "ra2ne";
2003e230dd2SCorentin Chary     case VNC_AUTH_TIGHT:
2013e230dd2SCorentin Chary         return "tight";
2023e230dd2SCorentin Chary     case VNC_AUTH_ULTRA:
2033e230dd2SCorentin Chary         return "ultra";
2043e230dd2SCorentin Chary     case VNC_AUTH_TLS:
2053e230dd2SCorentin Chary         return "tls";
2063e230dd2SCorentin Chary     case VNC_AUTH_VENCRYPT:
2073e230dd2SCorentin Chary         switch (vd->subauth) {
2083e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_PLAIN:
2093e230dd2SCorentin Chary             return "vencrypt+plain";
2103e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSNONE:
2113e230dd2SCorentin Chary             return "vencrypt+tls+none";
2123e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSVNC:
2133e230dd2SCorentin Chary             return "vencrypt+tls+vnc";
2143e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSPLAIN:
2153e230dd2SCorentin Chary             return "vencrypt+tls+plain";
2163e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509NONE:
2173e230dd2SCorentin Chary             return "vencrypt+x509+none";
2183e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509VNC:
2193e230dd2SCorentin Chary             return "vencrypt+x509+vnc";
2203e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509PLAIN:
2213e230dd2SCorentin Chary             return "vencrypt+x509+plain";
2223e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSSASL:
2233e230dd2SCorentin Chary             return "vencrypt+tls+sasl";
2243e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509SASL:
2253e230dd2SCorentin Chary             return "vencrypt+x509+sasl";
2263e230dd2SCorentin Chary         default:
2273e230dd2SCorentin Chary             return "vencrypt";
2283e230dd2SCorentin Chary         }
2293e230dd2SCorentin Chary     case VNC_AUTH_SASL:
2303e230dd2SCorentin Chary         return "sasl";
2313e230dd2SCorentin Chary     }
2323e230dd2SCorentin Chary     return "unknown";
2333e230dd2SCorentin Chary }
2343e230dd2SCorentin Chary 
235d616ccc5SGerd Hoffmann static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
2363e230dd2SCorentin Chary {
237fb6ba0d5SWenchao Xia     VncServerInfo *info;
23898481bfcSEric Blake     Error *err = NULL;
2393e230dd2SCorentin Chary 
24013e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
2414ee74fa7SDaniel P. Berrange         return NULL;
2424ee74fa7SDaniel P. Berrange     }
2434ee74fa7SDaniel P. Berrange 
2443e7f136dSDaniel P. Berrange     info = g_malloc0(sizeof(*info));
24513e1d0e7SDaniel P. Berrange     vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
246ddf21908SEric Blake                                          qapi_VncServerInfo_base(info), &err);
247fb6ba0d5SWenchao Xia     info->has_auth = true;
248d616ccc5SGerd Hoffmann     info->auth = g_strdup(vnc_auth_name(vd));
24998481bfcSEric Blake     if (err) {
25098481bfcSEric Blake         qapi_free_VncServerInfo(info);
25198481bfcSEric Blake         info = NULL;
25298481bfcSEric Blake         error_free(err);
25398481bfcSEric Blake     }
254fb6ba0d5SWenchao Xia     return info;
2553e230dd2SCorentin Chary }
2563e230dd2SCorentin Chary 
2573e230dd2SCorentin Chary static void vnc_client_cache_auth(VncState *client)
2583e230dd2SCorentin Chary {
2593e230dd2SCorentin Chary     if (!client->info) {
2603e230dd2SCorentin Chary         return;
2613e230dd2SCorentin Chary     }
2623e230dd2SCorentin Chary 
2633e305e4aSDaniel P. Berrange     if (client->tls) {
2643e305e4aSDaniel P. Berrange         client->info->x509_dname =
2653e305e4aSDaniel P. Berrange             qcrypto_tls_session_get_peer_name(client->tls);
2663e305e4aSDaniel P. Berrange         client->info->has_x509_dname =
2673e305e4aSDaniel P. Berrange             client->info->x509_dname != NULL;
2683e230dd2SCorentin Chary     }
2693e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
2703e230dd2SCorentin Chary     if (client->sasl.conn &&
2713e230dd2SCorentin Chary         client->sasl.username) {
272fb6ba0d5SWenchao Xia         client->info->has_sasl_username = true;
273fb6ba0d5SWenchao Xia         client->info->sasl_username = g_strdup(client->sasl.username);
2743e230dd2SCorentin Chary     }
2753e230dd2SCorentin Chary #endif
2763e230dd2SCorentin Chary }
2773e230dd2SCorentin Chary 
2783e230dd2SCorentin Chary static void vnc_client_cache_addr(VncState *client)
2793e230dd2SCorentin Chary {
28098481bfcSEric Blake     Error *err = NULL;
2813e230dd2SCorentin Chary 
282fb6ba0d5SWenchao Xia     client->info = g_malloc0(sizeof(*client->info));
28304d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
284ddf21908SEric Blake                                          qapi_VncClientInfo_base(client->info),
28598481bfcSEric Blake                                          &err);
286e1b3d477SGerd Hoffmann     client->info->websocket = client->websocket;
28798481bfcSEric Blake     if (err) {
28898481bfcSEric Blake         qapi_free_VncClientInfo(client->info);
28998481bfcSEric Blake         client->info = NULL;
29098481bfcSEric Blake         error_free(err);
291fb6ba0d5SWenchao Xia     }
2923e230dd2SCorentin Chary }
2933e230dd2SCorentin Chary 
294fb6ba0d5SWenchao Xia static void vnc_qmp_event(VncState *vs, QAPIEvent event)
2953e230dd2SCorentin Chary {
296fb6ba0d5SWenchao Xia     VncServerInfo *si;
2973e230dd2SCorentin Chary 
2983e230dd2SCorentin Chary     if (!vs->info) {
2993e230dd2SCorentin Chary         return;
3003e230dd2SCorentin Chary     }
3013e230dd2SCorentin Chary 
302d616ccc5SGerd Hoffmann     si = vnc_server_info_get(vs->vd);
303fb6ba0d5SWenchao Xia     if (!si) {
3043e230dd2SCorentin Chary         return;
3053e230dd2SCorentin Chary     }
3063e230dd2SCorentin Chary 
307fb6ba0d5SWenchao Xia     switch (event) {
308fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_CONNECTED:
3093ab72385SPeter Xu         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
310fb6ba0d5SWenchao Xia         break;
311fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_INITIALIZED:
3123ab72385SPeter Xu         qapi_event_send_vnc_initialized(si, vs->info);
313fb6ba0d5SWenchao Xia         break;
314fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_DISCONNECTED:
3153ab72385SPeter Xu         qapi_event_send_vnc_disconnected(si, vs->info);
316fb6ba0d5SWenchao Xia         break;
317fb6ba0d5SWenchao Xia     default:
318fb6ba0d5SWenchao Xia         break;
319fb6ba0d5SWenchao Xia     }
3203e230dd2SCorentin Chary 
321fb6ba0d5SWenchao Xia     qapi_free_VncServerInfo(si);
3223e230dd2SCorentin Chary }
3233e230dd2SCorentin Chary 
3242b54aa87SLuiz Capitulino static VncClientInfo *qmp_query_vnc_client(const VncState *client)
3253e230dd2SCorentin Chary {
3262b54aa87SLuiz Capitulino     VncClientInfo *info;
32704d2529dSDaniel P. Berrange     Error *err = NULL;
3282b54aa87SLuiz Capitulino 
3292b54aa87SLuiz Capitulino     info = g_malloc0(sizeof(*info));
33004d2529dSDaniel P. Berrange 
33104d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
33204d2529dSDaniel P. Berrange                                          qapi_VncClientInfo_base(info),
33304d2529dSDaniel P. Berrange                                          &err);
33404d2529dSDaniel P. Berrange     if (err) {
33504d2529dSDaniel P. Berrange         error_free(err);
33604d2529dSDaniel P. Berrange         qapi_free_VncClientInfo(info);
33704d2529dSDaniel P. Berrange         return NULL;
33804d2529dSDaniel P. Berrange     }
33904d2529dSDaniel P. Berrange 
340ddf21908SEric Blake     info->websocket = client->websocket;
3413e230dd2SCorentin Chary 
3423e305e4aSDaniel P. Berrange     if (client->tls) {
3433e305e4aSDaniel P. Berrange         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
3443e305e4aSDaniel P. Berrange         info->has_x509_dname = info->x509_dname != NULL;
3452b54aa87SLuiz Capitulino     }
3463e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
3472b54aa87SLuiz Capitulino     if (client->sasl.conn && client->sasl.username) {
3482b54aa87SLuiz Capitulino         info->has_sasl_username = true;
3492b54aa87SLuiz Capitulino         info->sasl_username = g_strdup(client->sasl.username);
3502b54aa87SLuiz Capitulino     }
3513e230dd2SCorentin Chary #endif
3522b54aa87SLuiz Capitulino 
3532b54aa87SLuiz Capitulino     return info;
3543e230dd2SCorentin Chary }
3553e230dd2SCorentin Chary 
356d616ccc5SGerd Hoffmann static VncDisplay *vnc_display_find(const char *id)
357d616ccc5SGerd Hoffmann {
358d616ccc5SGerd Hoffmann     VncDisplay *vd;
359d616ccc5SGerd Hoffmann 
360d616ccc5SGerd Hoffmann     if (id == NULL) {
361d616ccc5SGerd Hoffmann         return QTAILQ_FIRST(&vnc_displays);
362d616ccc5SGerd Hoffmann     }
363d616ccc5SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
364d616ccc5SGerd Hoffmann         if (strcmp(id, vd->id) == 0) {
365d616ccc5SGerd Hoffmann             return vd;
366d616ccc5SGerd Hoffmann         }
367d616ccc5SGerd Hoffmann     }
368d616ccc5SGerd Hoffmann     return NULL;
369d616ccc5SGerd Hoffmann }
370d616ccc5SGerd Hoffmann 
3712d29a436SGerd Hoffmann static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
3722d29a436SGerd Hoffmann {
37354aa3de7SEric Blake     VncClientInfoList *prev = NULL;
3742d29a436SGerd Hoffmann     VncState *client;
3752d29a436SGerd Hoffmann 
3762d29a436SGerd Hoffmann     QTAILQ_FOREACH(client, &vd->clients, next) {
37754aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, qmp_query_vnc_client(client));
3782d29a436SGerd Hoffmann     }
3792d29a436SGerd Hoffmann     return prev;
3802d29a436SGerd Hoffmann }
3812d29a436SGerd Hoffmann 
3822b54aa87SLuiz Capitulino VncInfo *qmp_query_vnc(Error **errp)
3833e230dd2SCorentin Chary {
3842b54aa87SLuiz Capitulino     VncInfo *info = g_malloc0(sizeof(*info));
385d616ccc5SGerd Hoffmann     VncDisplay *vd = vnc_display_find(NULL);
386bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3873e230dd2SCorentin Chary 
38813e1d0e7SDaniel P. Berrange     if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
3892b54aa87SLuiz Capitulino         info->enabled = false;
3903e230dd2SCorentin Chary     } else {
3912b54aa87SLuiz Capitulino         info->enabled = true;
3922b54aa87SLuiz Capitulino 
3932b54aa87SLuiz Capitulino         /* for compatibility with the original command */
3942b54aa87SLuiz Capitulino         info->has_clients = true;
3952d29a436SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
3963e230dd2SCorentin Chary 
39713e1d0e7SDaniel P. Berrange         addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
39813e1d0e7SDaniel P. Berrange                                                     errp);
39904d2529dSDaniel P. Berrange         if (!addr) {
4002b54aa87SLuiz Capitulino             goto out_error;
4012b54aa87SLuiz Capitulino         }
4023e230dd2SCorentin Chary 
40304d2529dSDaniel P. Berrange         switch (addr->type) {
404bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_INET:
405bd269ebcSMarkus Armbruster             info->host = g_strdup(addr->u.inet.host);
406bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.inet.port);
407bd269ebcSMarkus Armbruster             if (addr->u.inet.ipv6) {
40804d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
40904d2529dSDaniel P. Berrange             } else {
41004d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
41104d2529dSDaniel P. Berrange             }
41204d2529dSDaniel P. Berrange             break;
41304d2529dSDaniel P. Berrange 
414bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_UNIX:
41504d2529dSDaniel P. Berrange             info->host = g_strdup("");
416bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.q_unix.path);
41704d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
41804d2529dSDaniel P. Berrange             break;
41904d2529dSDaniel P. Berrange 
420bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_VSOCK:
421bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_FD:
422a6c76285SMarkus Armbruster             error_setg(errp, "Unsupported socket address type %s",
423977c736fSMarkus Armbruster                        SocketAddressType_str(addr->type));
4242b54aa87SLuiz Capitulino             goto out_error;
425a6c76285SMarkus Armbruster         default:
426a6c76285SMarkus Armbruster             abort();
4273e230dd2SCorentin Chary         }
4282b54aa87SLuiz Capitulino 
4292b54aa87SLuiz Capitulino         info->has_host = true;
4302b54aa87SLuiz Capitulino         info->has_service = true;
4312b54aa87SLuiz Capitulino         info->has_family = true;
4322b54aa87SLuiz Capitulino 
4332b54aa87SLuiz Capitulino         info->has_auth = true;
434d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4353e230dd2SCorentin Chary     }
4362b54aa87SLuiz Capitulino 
437bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4382b54aa87SLuiz Capitulino     return info;
4392b54aa87SLuiz Capitulino 
4402b54aa87SLuiz Capitulino out_error:
441bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4422b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4432b54aa87SLuiz Capitulino     return NULL;
4443e230dd2SCorentin Chary }
4453e230dd2SCorentin Chary 
4462a7e6857SDaniel P. Berrange 
4472a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4482a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4492a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4502a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt);
4512a7e6857SDaniel P. Berrange 
4522a7e6857SDaniel P. Berrange static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
4534478aa76SGerd Hoffmann                                                   bool websocket,
4542a7e6857SDaniel P. Berrange                                                   int auth,
4552a7e6857SDaniel P. Berrange                                                   int subauth,
4562a7e6857SDaniel P. Berrange                                                   VncServerInfo2List *prev)
457df887684SGerd Hoffmann {
4582a7e6857SDaniel P. Berrange     VncServerInfo2 *info;
45904d2529dSDaniel P. Berrange     Error *err = NULL;
460bd269ebcSMarkus Armbruster     SocketAddress *addr;
461df887684SGerd Hoffmann 
4629261ef5eSMarkus Armbruster     addr = qio_channel_socket_get_local_address(ioc, NULL);
46304d2529dSDaniel P. Berrange     if (!addr) {
464df887684SGerd Hoffmann         return prev;
465df887684SGerd Hoffmann     }
466df887684SGerd Hoffmann 
4672a7e6857SDaniel P. Berrange     info = g_new0(VncServerInfo2, 1);
4682a7e6857SDaniel P. Berrange     vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
469bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
47004d2529dSDaniel P. Berrange     if (err) {
4712a7e6857SDaniel P. Berrange         qapi_free_VncServerInfo2(info);
47204d2529dSDaniel P. Berrange         error_free(err);
47304d2529dSDaniel P. Berrange         return prev;
47404d2529dSDaniel P. Berrange     }
4754478aa76SGerd Hoffmann     info->websocket = websocket;
476df887684SGerd Hoffmann 
4772a7e6857SDaniel P. Berrange     qmp_query_auth(auth, subauth, &info->auth,
4782a7e6857SDaniel P. Berrange                    &info->vencrypt, &info->has_vencrypt);
4792a7e6857SDaniel P. Berrange 
48054aa3de7SEric Blake     QAPI_LIST_PREPEND(prev, info);
48154aa3de7SEric Blake     return prev;
482df887684SGerd Hoffmann }
483df887684SGerd Hoffmann 
4842a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4852a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4862a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4872a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt)
488df887684SGerd Hoffmann {
4892a7e6857SDaniel P. Berrange     switch (auth) {
490df887684SGerd Hoffmann     case VNC_AUTH_VNC:
4912a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VNC;
492df887684SGerd Hoffmann         break;
493df887684SGerd Hoffmann     case VNC_AUTH_RA2:
4942a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2;
495df887684SGerd Hoffmann         break;
496df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
4972a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
498df887684SGerd Hoffmann         break;
499df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
5002a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
501df887684SGerd Hoffmann         break;
502df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
5032a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
504df887684SGerd Hoffmann         break;
505df887684SGerd Hoffmann     case VNC_AUTH_TLS:
5062a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TLS;
507df887684SGerd Hoffmann         break;
508df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
5092a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
5102a7e6857SDaniel P. Berrange         *qmp_has_vencrypt = true;
5112a7e6857SDaniel P. Berrange         switch (subauth) {
512df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
5132a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
514df887684SGerd Hoffmann             break;
515df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
5162a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
517df887684SGerd Hoffmann             break;
518df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
5192a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
520df887684SGerd Hoffmann             break;
521df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
5222a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
523df887684SGerd Hoffmann             break;
524df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
5252a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
526df887684SGerd Hoffmann             break;
527df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
5282a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
529df887684SGerd Hoffmann             break;
530df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
5312a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
532df887684SGerd Hoffmann             break;
533df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
5342a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
535df887684SGerd Hoffmann             break;
536df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
5372a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
538df887684SGerd Hoffmann             break;
539df887684SGerd Hoffmann         default:
5402a7e6857SDaniel P. Berrange             *qmp_has_vencrypt = false;
541df887684SGerd Hoffmann             break;
542df887684SGerd Hoffmann         }
543df887684SGerd Hoffmann         break;
544df887684SGerd Hoffmann     case VNC_AUTH_SASL:
5452a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_SASL;
546df887684SGerd Hoffmann         break;
547df887684SGerd Hoffmann     case VNC_AUTH_NONE:
548df887684SGerd Hoffmann     default:
5492a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_NONE;
550df887684SGerd Hoffmann         break;
551df887684SGerd Hoffmann     }
552df887684SGerd Hoffmann }
553df887684SGerd Hoffmann 
554df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
555df887684SGerd Hoffmann {
55654aa3de7SEric Blake     VncInfo2List *prev = NULL;
557df887684SGerd Hoffmann     VncInfo2 *info;
558df887684SGerd Hoffmann     VncDisplay *vd;
559df887684SGerd Hoffmann     DeviceState *dev;
5604ee74fa7SDaniel P. Berrange     size_t i;
561df887684SGerd Hoffmann 
562df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
563df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
564df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
565df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
5662a7e6857SDaniel P. Berrange         qmp_query_auth(vd->auth, vd->subauth, &info->auth,
5672a7e6857SDaniel P. Berrange                        &info->vencrypt, &info->has_vencrypt);
568df887684SGerd Hoffmann         if (vd->dcl.con) {
569df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
570552d7f49SMarkus Armbruster                                                   "device", &error_abort));
571df887684SGerd Hoffmann             info->has_display = true;
572df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
573df887684SGerd Hoffmann         }
57413e1d0e7SDaniel P. Berrange         for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
57504d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57613e1d0e7SDaniel P. Berrange                 vd->listener->sioc[i], false, vd->auth, vd->subauth,
57713e1d0e7SDaniel P. Berrange                 info->server);
578df887684SGerd Hoffmann         }
57913e1d0e7SDaniel P. Berrange         for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
58004d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
58113e1d0e7SDaniel P. Berrange                 vd->wslistener->sioc[i], true, vd->ws_auth,
5824ee74fa7SDaniel P. Berrange                 vd->ws_subauth, info->server);
583df887684SGerd Hoffmann         }
584df887684SGerd Hoffmann 
58554aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, info);
586df887684SGerd Hoffmann     }
587df887684SGerd Hoffmann     return prev;
588df887684SGerd Hoffmann }
589df887684SGerd Hoffmann 
5901f08e341SZihao Chang bool vnc_display_reload_certs(const char *id, Error **errp)
5911f08e341SZihao Chang {
5921f08e341SZihao Chang     VncDisplay *vd = vnc_display_find(id);
5931f08e341SZihao Chang     QCryptoTLSCredsClass *creds = NULL;
5941f08e341SZihao Chang 
5951f08e341SZihao Chang     if (!vd) {
5961f08e341SZihao Chang         error_setg(errp, "Can not find vnc display");
5971f08e341SZihao Chang         return false;
5981f08e341SZihao Chang     }
5991f08e341SZihao Chang 
6001f08e341SZihao Chang     if (!vd->tlscreds) {
6014087ecb8SMichael Tokarev         error_setg(errp, "vnc tls is not enabled");
6021f08e341SZihao Chang         return false;
6031f08e341SZihao Chang     }
6041f08e341SZihao Chang 
6051f08e341SZihao Chang     creds = QCRYPTO_TLS_CREDS_GET_CLASS(OBJECT(vd->tlscreds));
6061f08e341SZihao Chang     if (creds->reload == NULL) {
6071f08e341SZihao Chang         error_setg(errp, "%s doesn't support to reload TLS credential",
6081f08e341SZihao Chang                    object_get_typename(OBJECT(vd->tlscreds)));
6091f08e341SZihao Chang         return false;
6101f08e341SZihao Chang     }
6111f08e341SZihao Chang     if (!creds->reload(vd->tlscreds, errp)) {
6121f08e341SZihao Chang         return false;
6131f08e341SZihao Chang     }
6141f08e341SZihao Chang 
6151f08e341SZihao Chang     return true;
6161f08e341SZihao Chang }
6171f08e341SZihao Chang 
6183e230dd2SCorentin Chary /* TODO
6193e230dd2SCorentin Chary    1) Get the queue working for IO.
6203e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
6213e230dd2SCorentin Chary       and not totally invalidated
6223e230dd2SCorentin Chary    3) resolutions > 1024
6233e230dd2SCorentin Chary */
6243e230dd2SCorentin Chary 
6256af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty);
6263e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
6273e230dd2SCorentin Chary 
6283e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
6293e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
6303e230dd2SCorentin Chary                                        int x_position, int y_position,
6313e230dd2SCorentin Chary                                        int w, int h);
6320f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
6333e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
6343e230dd2SCorentin Chary 
635d05959c2SGerd Hoffmann static int vnc_width(VncDisplay *vd)
636d05959c2SGerd Hoffmann {
637d05959c2SGerd Hoffmann     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
638d05959c2SGerd Hoffmann                                        VNC_DIRTY_PIXELS_PER_BIT));
639d05959c2SGerd Hoffmann }
640d05959c2SGerd Hoffmann 
64169cc8db4SDaniel P. Berrangé static int vnc_true_width(VncDisplay *vd)
64269cc8db4SDaniel P. Berrangé {
64369cc8db4SDaniel P. Berrangé     return MIN(VNC_MAX_WIDTH, surface_width(vd->ds));
64469cc8db4SDaniel P. Berrangé }
64569cc8db4SDaniel P. Berrangé 
646d05959c2SGerd Hoffmann static int vnc_height(VncDisplay *vd)
647d05959c2SGerd Hoffmann {
648d05959c2SGerd Hoffmann     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
649d05959c2SGerd Hoffmann }
650d05959c2SGerd Hoffmann 
651bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
652bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
653f7b3d68cSGerd Hoffmann                                VncDisplay *vd,
654f7b3d68cSGerd Hoffmann                                int x, int y, int w, int h)
655f7b3d68cSGerd Hoffmann {
656f7b3d68cSGerd Hoffmann     int width = vnc_width(vd);
657f7b3d68cSGerd Hoffmann     int height = vnc_height(vd);
658f7b3d68cSGerd Hoffmann 
65991937225SPeter Lieven     /* this is needed this to ensure we updated all affected
66091937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
661b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
662b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6633e230dd2SCorentin Chary 
6649f64916dSGerd Hoffmann     x = MIN(x, width);
6659f64916dSGerd Hoffmann     y = MIN(y, height);
6669f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
66791937225SPeter Lieven     h = MIN(y + h, height);
6683e230dd2SCorentin Chary 
669b4c85ddcSPeter Lieven     for (; y < h; y++) {
670bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
67191937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
672b4c85ddcSPeter Lieven     }
6733e230dd2SCorentin Chary }
6743e230dd2SCorentin Chary 
675bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
676bea60dd7SPeter Lieven                            int x, int y, int w, int h)
677bea60dd7SPeter Lieven {
678bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
679bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
680bea60dd7SPeter Lieven 
681f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
682bea60dd7SPeter Lieven }
683bea60dd7SPeter Lieven 
6843e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6853e230dd2SCorentin Chary                             int32_t encoding)
6863e230dd2SCorentin Chary {
6873e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6883e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6893e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6903e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6913e230dd2SCorentin Chary 
6923e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6933e230dd2SCorentin Chary }
6943e230dd2SCorentin Chary 
695763deea7SGerd Hoffmann static void vnc_desktop_resize_ext(VncState *vs, int reject_reason)
696763deea7SGerd Hoffmann {
697adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_ext_desktop_resize(
698adc8fce8SDaniel P. Berrangé         vs, vs->ioc, vs->client_width, vs->client_height, reject_reason);
699adc8fce8SDaniel P. Berrangé 
700763deea7SGerd Hoffmann     vnc_lock_output(vs);
701763deea7SGerd Hoffmann     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
702763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);
703763deea7SGerd Hoffmann     vnc_write_u16(vs, 1); /* number of rects */
704763deea7SGerd Hoffmann     vnc_framebuffer_update(vs,
705763deea7SGerd Hoffmann                            reject_reason ? 1 : 0,
706763deea7SGerd Hoffmann                            reject_reason,
707763deea7SGerd Hoffmann                            vs->client_width, vs->client_height,
708763deea7SGerd Hoffmann                            VNC_ENCODING_DESKTOP_RESIZE_EXT);
709763deea7SGerd Hoffmann     vnc_write_u8(vs, 1);  /* number of screens */
710763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
711763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
712763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
713763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen id */
714763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen x-pos */
715763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen y-pos */
716763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_width);
717763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_height);
718763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen flags */
719763deea7SGerd Hoffmann     vnc_unlock_output(vs);
720763deea7SGerd Hoffmann     vnc_flush(vs);
721763deea7SGerd Hoffmann }
72232ed2680STim Hardeck 
7233e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
7243e230dd2SCorentin Chary {
725763deea7SGerd Hoffmann     if (vs->ioc == NULL || (!vnc_has_feature(vs, VNC_FEATURE_RESIZE) &&
726763deea7SGerd Hoffmann                             !vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT))) {
7273e230dd2SCorentin Chary         return;
7283e230dd2SCorentin Chary     }
72969cc8db4SDaniel P. Berrangé     if (vs->client_width == vs->vd->true_width &&
730d239726cSGerd Hoffmann         vs->client_height == pixman_image_get_height(vs->vd->server)) {
731d239726cSGerd Hoffmann         return;
732d239726cSGerd Hoffmann     }
7334c956bd8SDaniel P. Berrange 
73469cc8db4SDaniel P. Berrangé     assert(vs->vd->true_width < 65536 &&
73569cc8db4SDaniel P. Berrangé            vs->vd->true_width >= 0);
7364c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
7374c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
73869cc8db4SDaniel P. Berrangé     vs->client_width = vs->vd->true_width;
739bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
740763deea7SGerd Hoffmann 
741763deea7SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
742763deea7SGerd Hoffmann         vnc_desktop_resize_ext(vs, 0);
743763deea7SGerd Hoffmann         return;
744763deea7SGerd Hoffmann     }
745763deea7SGerd Hoffmann 
746adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_desktop_resize(
747adc8fce8SDaniel P. Berrangé         vs, vs->ioc, vs->client_width, vs->client_height);
748adc8fce8SDaniel P. Berrangé 
749bd023f95SCorentin Chary     vnc_lock_output(vs);
7503e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
7513e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
7523e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
7533e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
7543e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
755bd023f95SCorentin Chary     vnc_unlock_output(vs);
7563e230dd2SCorentin Chary     vnc_flush(vs);
7573e230dd2SCorentin Chary }
7583e230dd2SCorentin Chary 
759bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
760bd023f95SCorentin Chary {
761bd023f95SCorentin Chary     VncState *vs;
762bd023f95SCorentin Chary 
763bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
764bd023f95SCorentin Chary         vnc_lock_output(vs);
765bd023f95SCorentin Chary         vs->abort = true;
766bd023f95SCorentin Chary         vnc_unlock_output(vs);
767bd023f95SCorentin Chary     }
768bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
769bd023f95SCorentin Chary         vnc_jobs_join(vs);
770bd023f95SCorentin Chary     }
771bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
772bd023f95SCorentin Chary         vnc_lock_output(vs);
773bbcdeb62SGerd Hoffmann         if (vs->update == VNC_STATE_UPDATE_NONE &&
774bbcdeb62SGerd Hoffmann             vs->job_update != VNC_STATE_UPDATE_NONE) {
775bbcdeb62SGerd Hoffmann             /* job aborted before completion */
776bbcdeb62SGerd Hoffmann             vs->update = vs->job_update;
777bbcdeb62SGerd Hoffmann             vs->job_update = VNC_STATE_UPDATE_NONE;
778bbcdeb62SGerd Hoffmann         }
779bd023f95SCorentin Chary         vs->abort = false;
780bd023f95SCorentin Chary         vnc_unlock_output(vs);
781bd023f95SCorentin Chary     }
782bd023f95SCorentin Chary }
783bd023f95SCorentin Chary 
7849f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
7859f64916dSGerd Hoffmann {
7869f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
7879f64916dSGerd Hoffmann }
7889f64916dSGerd Hoffmann 
7899f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
7909f64916dSGerd Hoffmann {
7919f64916dSGerd Hoffmann     uint8_t *ptr;
7929f64916dSGerd Hoffmann 
7939f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
7949f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
7959f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
7969f64916dSGerd Hoffmann     return ptr;
7979f64916dSGerd Hoffmann }
7989f64916dSGerd Hoffmann 
799453f842bSGerd Hoffmann static void vnc_update_server_surface(VncDisplay *vd)
800453f842bSGerd Hoffmann {
801b69a553bSDaniel P. Berrange     int width, height;
802b69a553bSDaniel P. Berrange 
803453f842bSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
804453f842bSGerd Hoffmann     vd->server = NULL;
805453f842bSGerd Hoffmann 
806c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vd->clients)) {
807c7628bffSGerd Hoffmann         return;
808c7628bffSGerd Hoffmann     }
809c7628bffSGerd Hoffmann 
810b69a553bSDaniel P. Berrange     width = vnc_width(vd);
811b69a553bSDaniel P. Berrange     height = vnc_height(vd);
81269cc8db4SDaniel P. Berrangé     vd->true_width = vnc_true_width(vd);
813453f842bSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
814b69a553bSDaniel P. Berrange                                           width, height,
815453f842bSGerd Hoffmann                                           NULL, 0);
816b69a553bSDaniel P. Berrange 
817b69a553bSDaniel P. Berrange     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
818b69a553bSDaniel P. Berrange     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
819b69a553bSDaniel P. Berrange                        width, height);
820453f842bSGerd Hoffmann }
821453f842bSGerd Hoffmann 
82261e77a5fSGerd Hoffmann static bool vnc_check_pageflip(DisplaySurface *s1,
82361e77a5fSGerd Hoffmann                                DisplaySurface *s2)
82461e77a5fSGerd Hoffmann {
82561e77a5fSGerd Hoffmann     return (s1 != NULL &&
82661e77a5fSGerd Hoffmann             s2 != NULL &&
82761e77a5fSGerd Hoffmann             surface_width(s1) == surface_width(s2) &&
82861e77a5fSGerd Hoffmann             surface_height(s1) == surface_height(s2) &&
82961e77a5fSGerd Hoffmann             surface_format(s1) == surface_format(s2));
83061e77a5fSGerd Hoffmann 
83161e77a5fSGerd Hoffmann }
83261e77a5fSGerd Hoffmann 
833c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
834c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
8353e230dd2SCorentin Chary {
83621ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
83761e77a5fSGerd Hoffmann     bool pageflip = vnc_check_pageflip(vd->ds, surface);
8383e230dd2SCorentin Chary     VncState *vs;
8393e230dd2SCorentin Chary 
840bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
841453f842bSGerd Hoffmann     vd->ds = surface;
842bd023f95SCorentin Chary 
8433e230dd2SCorentin Chary     /* guest surface */
8449f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
845d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
846d39fa6d8SGerd Hoffmann     vd->guest.format = surface->format;
8473e230dd2SCorentin Chary 
84869cc8db4SDaniel P. Berrangé 
84961e77a5fSGerd Hoffmann     if (pageflip) {
85069cc8db4SDaniel P. Berrangé         trace_vnc_server_dpy_pageflip(vd,
85169cc8db4SDaniel P. Berrangé                                       surface_width(surface),
85269cc8db4SDaniel P. Berrangé                                       surface_height(surface),
85369cc8db4SDaniel P. Berrangé                                       surface_format(surface));
85461e77a5fSGerd Hoffmann         vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
85561e77a5fSGerd Hoffmann                            surface_width(surface),
85661e77a5fSGerd Hoffmann                            surface_height(surface));
85761e77a5fSGerd Hoffmann         return;
85861e77a5fSGerd Hoffmann     }
85961e77a5fSGerd Hoffmann 
86069cc8db4SDaniel P. Berrangé     trace_vnc_server_dpy_recreate(vd,
86169cc8db4SDaniel P. Berrangé                                   surface_width(surface),
86269cc8db4SDaniel P. Berrangé                                   surface_height(surface),
86369cc8db4SDaniel P. Berrangé                                   surface_format(surface));
86461e77a5fSGerd Hoffmann     /* server surface */
86561e77a5fSGerd Hoffmann     vnc_update_server_surface(vd);
86661e77a5fSGerd Hoffmann 
8673e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
8683e230dd2SCorentin Chary         vnc_colordepth(vs);
8693e230dd2SCorentin Chary         vnc_desktop_resize(vs);
8703e230dd2SCorentin Chary         vnc_cursor_define(vs);
871bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
872f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
873b69a553bSDaniel P. Berrange                            vnc_width(vd),
874b69a553bSDaniel P. Berrange                            vnc_height(vd));
875e2b72cb6SDaniel P. Berrange         vnc_update_throttle_offset(vs);
8763e230dd2SCorentin Chary     }
8773e230dd2SCorentin Chary }
8783e230dd2SCorentin Chary 
8793e230dd2SCorentin Chary /* fastest code */
8809f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
8813e230dd2SCorentin Chary                                   void *pixels, int size)
8823e230dd2SCorentin Chary {
8833e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
8843e230dd2SCorentin Chary }
8853e230dd2SCorentin Chary 
8863e230dd2SCorentin Chary /* slowest but generic code. */
8873e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
8883e230dd2SCorentin Chary {
8893e230dd2SCorentin Chary     uint8_t r, g, b;
8903e230dd2SCorentin Chary 
8919f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
8929f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
8939f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
8949f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
8959f64916dSGerd Hoffmann #else
8969f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
8979f64916dSGerd Hoffmann #endif
8989f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
8999f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
9009f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
9019f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
9023e230dd2SCorentin Chary     case 1:
9033e230dd2SCorentin Chary         buf[0] = v;
9043e230dd2SCorentin Chary         break;
9053e230dd2SCorentin Chary     case 2:
9069f64916dSGerd Hoffmann         if (vs->client_be) {
9073e230dd2SCorentin Chary             buf[0] = v >> 8;
9083e230dd2SCorentin Chary             buf[1] = v;
9093e230dd2SCorentin Chary         } else {
9103e230dd2SCorentin Chary             buf[1] = v >> 8;
9113e230dd2SCorentin Chary             buf[0] = v;
9123e230dd2SCorentin Chary         }
9133e230dd2SCorentin Chary         break;
9143e230dd2SCorentin Chary     default:
9153e230dd2SCorentin Chary     case 4:
9169f64916dSGerd Hoffmann         if (vs->client_be) {
9173e230dd2SCorentin Chary             buf[0] = v >> 24;
9183e230dd2SCorentin Chary             buf[1] = v >> 16;
9193e230dd2SCorentin Chary             buf[2] = v >> 8;
9203e230dd2SCorentin Chary             buf[3] = v;
9213e230dd2SCorentin Chary         } else {
9223e230dd2SCorentin Chary             buf[3] = v >> 24;
9233e230dd2SCorentin Chary             buf[2] = v >> 16;
9243e230dd2SCorentin Chary             buf[1] = v >> 8;
9253e230dd2SCorentin Chary             buf[0] = v;
9263e230dd2SCorentin Chary         }
9273e230dd2SCorentin Chary         break;
9283e230dd2SCorentin Chary     }
9293e230dd2SCorentin Chary }
9303e230dd2SCorentin Chary 
9319f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
9323e230dd2SCorentin Chary                                      void *pixels1, int size)
9333e230dd2SCorentin Chary {
9343e230dd2SCorentin Chary     uint8_t buf[4];
9353e230dd2SCorentin Chary 
9369f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
9373e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
9383e230dd2SCorentin Chary         int n, i;
9393e230dd2SCorentin Chary         n = size >> 2;
9403e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
9413e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
9429f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
9433e230dd2SCorentin Chary         }
9443e230dd2SCorentin Chary     }
9453e230dd2SCorentin Chary }
9463e230dd2SCorentin Chary 
9473e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9483e230dd2SCorentin Chary {
9493e230dd2SCorentin Chary     int i;
9503e230dd2SCorentin Chary     uint8_t *row;
9513e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
9523e230dd2SCorentin Chary 
9539f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
9543e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
9559f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
9569f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
9573e230dd2SCorentin Chary     }
9583e230dd2SCorentin Chary     return 1;
9593e230dd2SCorentin Chary }
9603e230dd2SCorentin Chary 
961bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9623e230dd2SCorentin Chary {
9633e230dd2SCorentin Chary     int n = 0;
9643e230dd2SCorentin Chary 
9653e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
9663e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
9673e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
9683e230dd2SCorentin Chary             break;
9693e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
9703e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
9713e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
9723e230dd2SCorentin Chary             break;
9733e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
9743e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
9753e230dd2SCorentin Chary             break;
976efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
977efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
978efe556adSCorentin Chary             break;
979148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
980148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
981148954faSCorentin Chary             break;
982148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
983148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
984148954faSCorentin Chary             break;
9853e230dd2SCorentin Chary         default:
986de3f7de7SPeter Lieven             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
987de3f7de7SPeter Lieven             n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
9880780ec7bSGerd Hoffmann             break;
989de3f7de7SPeter Lieven     }
9903e230dd2SCorentin Chary     return n;
9913e230dd2SCorentin Chary }
9923e230dd2SCorentin Chary 
9937c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9947c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9953e230dd2SCorentin Chary {
9963e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9973e230dd2SCorentin Chary }
9983e230dd2SCorentin Chary 
9993e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
10003e230dd2SCorentin Chary {
10013e230dd2SCorentin Chary     QEMUCursor *c = vs->vd->cursor;
10023e230dd2SCorentin Chary     int isize;
10033e230dd2SCorentin Chary 
1004b3c2de9cSGerd Hoffmann     if (!vs->vd->cursor) {
1005b3c2de9cSGerd Hoffmann         return -1;
1006b3c2de9cSGerd Hoffmann     }
1007b3c2de9cSGerd Hoffmann 
1008074a86d0SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
1009074a86d0SGerd Hoffmann         vnc_lock_output(vs);
1010074a86d0SGerd Hoffmann         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1011074a86d0SGerd Hoffmann         vnc_write_u8(vs,  0);  /*  padding     */
1012074a86d0SGerd Hoffmann         vnc_write_u16(vs, 1);  /*  # of rects  */
1013074a86d0SGerd Hoffmann         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
1014074a86d0SGerd Hoffmann                                VNC_ENCODING_ALPHA_CURSOR);
1015074a86d0SGerd Hoffmann         vnc_write_s32(vs, VNC_ENCODING_RAW);
1016074a86d0SGerd Hoffmann         vnc_write(vs, c->data, c->width * c->height * 4);
1017074a86d0SGerd Hoffmann         vnc_unlock_output(vs);
1018074a86d0SGerd Hoffmann         return 0;
1019074a86d0SGerd Hoffmann     }
10203e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
1021d01f9595SCorentin Chary         vnc_lock_output(vs);
10223e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
10233e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
10243e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
10253e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
10263e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
10279f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
10289f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
10293e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
1030d01f9595SCorentin Chary         vnc_unlock_output(vs);
10313e230dd2SCorentin Chary         return 0;
10323e230dd2SCorentin Chary     }
10333e230dd2SCorentin Chary     return -1;
10343e230dd2SCorentin Chary }
10353e230dd2SCorentin Chary 
10367c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
10377c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
10383e230dd2SCorentin Chary {
1039d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
10403e230dd2SCorentin Chary     VncState *vs;
10413e230dd2SCorentin Chary 
10423e230dd2SCorentin Chary     cursor_put(vd->cursor);
10437267c094SAnthony Liguori     g_free(vd->cursor_mask);
10443e230dd2SCorentin Chary 
10453e230dd2SCorentin Chary     vd->cursor = c;
10463e230dd2SCorentin Chary     cursor_get(vd->cursor);
10473e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
10487267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
10493e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
10503e230dd2SCorentin Chary 
10513e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
10523e230dd2SCorentin Chary         vnc_cursor_define(vs);
10533e230dd2SCorentin Chary     }
10543e230dd2SCorentin Chary }
10553e230dd2SCorentin Chary 
10564769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
10576c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
10583e230dd2SCorentin Chary {
10593e230dd2SCorentin Chary     int h;
10603e230dd2SCorentin Chary 
10616c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
1062bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
10633e230dd2SCorentin Chary             break;
1064bc2429b9SCorentin Chary         }
1065863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
10663e230dd2SCorentin Chary     }
10673e230dd2SCorentin Chary 
10683e230dd2SCorentin Chary     return h;
10693e230dd2SCorentin Chary }
10703e230dd2SCorentin Chary 
1071e2b72cb6SDaniel P. Berrange /*
1072e2b72cb6SDaniel P. Berrange  * Figure out how much pending data we should allow in the output
1073e2b72cb6SDaniel P. Berrange  * buffer before we throttle incremental display updates, and/or
1074e2b72cb6SDaniel P. Berrange  * drop audio samples.
1075e2b72cb6SDaniel P. Berrange  *
1076e2b72cb6SDaniel P. Berrange  * We allow for equiv of 1 full display's worth of FB updates,
1077e2b72cb6SDaniel P. Berrange  * and 1 second of audio samples. If audio backlog was larger
1078e2b72cb6SDaniel P. Berrange  * than that the client would already suffering awful audio
1079e2b72cb6SDaniel P. Berrange  * glitches, so dropping samples is no worse really).
1080e2b72cb6SDaniel P. Berrange  */
1081e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs)
1082e2b72cb6SDaniel P. Berrange {
1083e2b72cb6SDaniel P. Berrange     size_t offset =
1084e2b72cb6SDaniel P. Berrange         vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1085e2b72cb6SDaniel P. Berrange 
1086e2b72cb6SDaniel P. Berrange     if (vs->audio_cap) {
1087e2b72cb6SDaniel P. Berrange         int bps;
1088e2b72cb6SDaniel P. Berrange         switch (vs->as.fmt) {
1089e2b72cb6SDaniel P. Berrange         default:
109085bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U8:
109185bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S8:
1092e2b72cb6SDaniel P. Berrange             bps = 1;
1093e2b72cb6SDaniel P. Berrange             break;
109485bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U16:
109585bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S16:
1096e2b72cb6SDaniel P. Berrange             bps = 2;
1097e2b72cb6SDaniel P. Berrange             break;
109885bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U32:
109985bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S32:
1100e2b72cb6SDaniel P. Berrange             bps = 4;
1101e2b72cb6SDaniel P. Berrange             break;
1102e2b72cb6SDaniel P. Berrange         }
1103cf070658SDaniel P. Berrangé         offset += vs->as.freq * bps * vs->as.nchannels;
1104e2b72cb6SDaniel P. Berrange     }
1105e2b72cb6SDaniel P. Berrange 
1106e2b72cb6SDaniel P. Berrange     /* Put a floor of 1MB on offset, so that if we have a large pending
1107e2b72cb6SDaniel P. Berrange      * buffer and the display is resized to a small size & back again
1108e2b72cb6SDaniel P. Berrange      * we don't suddenly apply a tiny send limit
1109e2b72cb6SDaniel P. Berrange      */
1110e2b72cb6SDaniel P. Berrange     offset = MAX(offset, 1024 * 1024);
1111e2b72cb6SDaniel P. Berrange 
11126aa22a29SDaniel P. Berrange     if (vs->throttle_output_offset != offset) {
11136aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_threshold(
11146aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
11156aa22a29SDaniel P. Berrange             vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
11166aa22a29SDaniel P. Berrange     }
11176aa22a29SDaniel P. Berrange 
1118e2b72cb6SDaniel P. Berrange     vs->throttle_output_offset = offset;
1119e2b72cb6SDaniel P. Berrange }
1120e2b72cb6SDaniel P. Berrange 
11210bad8342SDaniel P. Berrange static bool vnc_should_update(VncState *vs)
11220bad8342SDaniel P. Berrange {
11230bad8342SDaniel P. Berrange     switch (vs->update) {
11240bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_NONE:
11250bad8342SDaniel P. Berrange         break;
11260bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_INCREMENTAL:
1127e2b72cb6SDaniel P. Berrange         /* Only allow incremental updates if the pending send queue
1128ada8d2e4SDaniel P. Berrange          * is less than the permitted threshold, and the job worker
1129ada8d2e4SDaniel P. Berrange          * is completely idle.
11300bad8342SDaniel P. Berrange          */
1131ada8d2e4SDaniel P. Berrange         if (vs->output.offset < vs->throttle_output_offset &&
1132ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
11330bad8342SDaniel P. Berrange             return true;
11340bad8342SDaniel P. Berrange         }
11356aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_incremental(
11366aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->output.offset);
11370bad8342SDaniel P. Berrange         break;
11380bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_FORCE:
1139ada8d2e4SDaniel P. Berrange         /* Only allow forced updates if the pending send queue
1140ada8d2e4SDaniel P. Berrange          * does not contain a previous forced update, and the
1141ada8d2e4SDaniel P. Berrange          * job worker is completely idle.
1142ada8d2e4SDaniel P. Berrange          *
1143ada8d2e4SDaniel P. Berrange          * Note this means we'll queue a forced update, even if
1144ada8d2e4SDaniel P. Berrange          * the output buffer size is otherwise over the throttle
1145ada8d2e4SDaniel P. Berrange          * output limit.
1146ada8d2e4SDaniel P. Berrange          */
1147ada8d2e4SDaniel P. Berrange         if (vs->force_update_offset == 0 &&
1148ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
11490bad8342SDaniel P. Berrange             return true;
11500bad8342SDaniel P. Berrange         }
11516aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_forced(
11526aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->force_update_offset);
1153ada8d2e4SDaniel P. Berrange         break;
1154ada8d2e4SDaniel P. Berrange     }
11550bad8342SDaniel P. Berrange     return false;
11560bad8342SDaniel P. Berrange }
11570bad8342SDaniel P. Berrange 
11586af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty)
11593e230dd2SCorentin Chary {
11603e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
1161bd023f95SCorentin Chary     VncJob *job;
11623e230dd2SCorentin Chary     int y;
11632f487a3dSPeter Lieven     int height, width;
1164bd023f95SCorentin Chary     int n = 0;
1165bd023f95SCorentin Chary 
1166b939eb89SDaniel P. Berrange     if (vs->disconnecting) {
1167b939eb89SDaniel P. Berrange         vnc_disconnect_finish(vs);
1168b939eb89SDaniel P. Berrange         return 0;
1169b939eb89SDaniel P. Berrange     }
1170b939eb89SDaniel P. Berrange 
1171b939eb89SDaniel P. Berrange     vs->has_dirty += has_dirty;
11720bad8342SDaniel P. Berrange     if (!vnc_should_update(vs)) {
11733e230dd2SCorentin Chary         return 0;
1174b939eb89SDaniel P. Berrange     }
11753e230dd2SCorentin Chary 
1176fef1bbadSDaniel P. Berrange     if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
11773e230dd2SCorentin Chary         return 0;
1178b939eb89SDaniel P. Berrange     }
11793e230dd2SCorentin Chary 
11803e230dd2SCorentin Chary     /*
11813e230dd2SCorentin Chary      * Send screen updates to the vnc client using the server
11823e230dd2SCorentin Chary      * surface and server dirty map.  guest surface updates
11833e230dd2SCorentin Chary      * happening in parallel don't disturb us, the next pass will
11843e230dd2SCorentin Chary      * send them to the client.
11853e230dd2SCorentin Chary      */
1186bd023f95SCorentin Chary     job = vnc_job_new(vs);
11873e230dd2SCorentin Chary 
1188bea60dd7SPeter Lieven     height = pixman_image_get_height(vd->server);
1189bea60dd7SPeter Lieven     width = pixman_image_get_width(vd->server);
11903e230dd2SCorentin Chary 
119112b316d4SPeter Lieven     y = 0;
119212b316d4SPeter Lieven     for (;;) {
119312b316d4SPeter Lieven         int x, h;
119412b316d4SPeter Lieven         unsigned long x2;
119512b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
119612b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(vs),
119712b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(vs));
119812b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(vs)) {
119912b316d4SPeter Lieven             /* no more dirty bits */
120012b316d4SPeter Lieven             break;
12013e230dd2SCorentin Chary         }
120212b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(vs);
120312b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(vs);
120412b316d4SPeter Lieven         x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
120512b316d4SPeter Lieven                                 VNC_DIRTY_BPL(vs), x);
120612b316d4SPeter Lieven         bitmap_clear(vs->dirty[y], x, x2 - x);
120712b316d4SPeter Lieven         h = find_and_clear_dirty_height(vs, y, x, x2, height);
12082f487a3dSPeter Lieven         x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
12092f487a3dSPeter Lieven         if (x2 > x) {
121012b316d4SPeter Lieven             n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
121112b316d4SPeter Lieven                                   (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
12123e230dd2SCorentin Chary         }
12130e7d6f60SPeter Lieven         if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
12140e7d6f60SPeter Lieven             y += h;
12150e7d6f60SPeter Lieven             if (y == height) {
12160e7d6f60SPeter Lieven                 break;
12170e7d6f60SPeter Lieven             }
12180e7d6f60SPeter Lieven         }
12192f487a3dSPeter Lieven     }
1220bd023f95SCorentin Chary 
1221ada8d2e4SDaniel P. Berrange     vs->job_update = vs->update;
1222728a7ac9SDaniel P. Berrange     vs->update = VNC_STATE_UPDATE_NONE;
1223ada8d2e4SDaniel P. Berrange     vnc_job_push(job);
122463658280SGerd Hoffmann     vs->has_dirty = 0;
1225bd023f95SCorentin Chary     return n;
12263e230dd2SCorentin Chary }
12273e230dd2SCorentin Chary 
12283e230dd2SCorentin Chary /* audio */
12293e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
12303e230dd2SCorentin Chary {
12313e230dd2SCorentin Chary     VncState *vs = opaque;
12323e230dd2SCorentin Chary 
1233f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
12343e230dd2SCorentin Chary     switch (cmd) {
12353e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1236adc8fce8SDaniel P. Berrangé         trace_vnc_msg_server_audio_end(vs, vs->ioc);
1237bd023f95SCorentin Chary         vnc_lock_output(vs);
12383e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12393e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12403e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1241bd023f95SCorentin Chary         vnc_unlock_output(vs);
12423e230dd2SCorentin Chary         vnc_flush(vs);
12433e230dd2SCorentin Chary         break;
12443e230dd2SCorentin Chary 
12453e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1246adc8fce8SDaniel P. Berrangé         trace_vnc_msg_server_audio_begin(vs, vs->ioc);
1247bd023f95SCorentin Chary         vnc_lock_output(vs);
12483e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12493e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12503e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1251bd023f95SCorentin Chary         vnc_unlock_output(vs);
12523e230dd2SCorentin Chary         vnc_flush(vs);
12533e230dd2SCorentin Chary         break;
12543e230dd2SCorentin Chary     }
12553e230dd2SCorentin Chary }
12563e230dd2SCorentin Chary 
12573e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
12583e230dd2SCorentin Chary {
12593e230dd2SCorentin Chary }
12603e230dd2SCorentin Chary 
126157a878edSPhilippe Mathieu-Daudé static void audio_capture(void *opaque, const void *buf, int size)
12623e230dd2SCorentin Chary {
12633e230dd2SCorentin Chary     VncState *vs = opaque;
12643e230dd2SCorentin Chary 
1265f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1266adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_audio_data(vs, vs->ioc, buf, size);
1267bd023f95SCorentin Chary     vnc_lock_output(vs);
1268e2b72cb6SDaniel P. Berrange     if (vs->output.offset < vs->throttle_output_offset) {
12693e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12703e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12713e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
12723e230dd2SCorentin Chary         vnc_write_u32(vs, size);
12733e230dd2SCorentin Chary         vnc_write(vs, buf, size);
12746aa22a29SDaniel P. Berrange     } else {
12756aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1276e2b72cb6SDaniel P. Berrange     }
1277bd023f95SCorentin Chary     vnc_unlock_output(vs);
12783e230dd2SCorentin Chary     vnc_flush(vs);
12793e230dd2SCorentin Chary }
12803e230dd2SCorentin Chary 
12813e230dd2SCorentin Chary static void audio_add(VncState *vs)
12823e230dd2SCorentin Chary {
12833e230dd2SCorentin Chary     struct audio_capture_ops ops;
12843e230dd2SCorentin Chary 
12853e230dd2SCorentin Chary     if (vs->audio_cap) {
1286027a79c3SCole Robinson         error_report("audio already running");
12873e230dd2SCorentin Chary         return;
12883e230dd2SCorentin Chary     }
12893e230dd2SCorentin Chary 
12903e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
12913e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
12923e230dd2SCorentin Chary     ops.capture = audio_capture;
12933e230dd2SCorentin Chary 
1294f0b9f36dSKővágó, Zoltán     vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
12953e230dd2SCorentin Chary     if (!vs->audio_cap) {
1296027a79c3SCole Robinson         error_report("Failed to add audio capture");
12973e230dd2SCorentin Chary     }
12983e230dd2SCorentin Chary }
12993e230dd2SCorentin Chary 
13003e230dd2SCorentin Chary static void audio_del(VncState *vs)
13013e230dd2SCorentin Chary {
13023e230dd2SCorentin Chary     if (vs->audio_cap) {
13033e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
13043e230dd2SCorentin Chary         vs->audio_cap = NULL;
13053e230dd2SCorentin Chary     }
13063e230dd2SCorentin Chary }
13073e230dd2SCorentin Chary 
13083e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
13093e230dd2SCorentin Chary {
131004d2529dSDaniel P. Berrange     if (vs->disconnecting) {
13113e230dd2SCorentin Chary         return;
131204d2529dSDaniel P. Berrange     }
1313ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_start(vs, vs->ioc);
13148cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
131504d2529dSDaniel P. Berrange     if (vs->ioc_tag) {
131604d2529dSDaniel P. Berrange         g_source_remove(vs->ioc_tag);
1317a75d6f07SBrandon Carpenter         vs->ioc_tag = 0;
131804d2529dSDaniel P. Berrange     }
131904d2529dSDaniel P. Berrange     qio_channel_close(vs->ioc, NULL);
132004d2529dSDaniel P. Berrange     vs->disconnecting = TRUE;
13213e230dd2SCorentin Chary }
13223e230dd2SCorentin Chary 
13237536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
13243e230dd2SCorentin Chary {
13257d964c9dSCorentin Chary     int i;
13267d964c9dSCorentin Chary 
1327ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_finish(vs, vs->ioc);
1328ad6374c4SDaniel P. Berrange 
1329bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1330bd023f95SCorentin Chary 
1331bd023f95SCorentin Chary     vnc_lock_output(vs);
1332fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
13333e230dd2SCorentin Chary 
13343e230dd2SCorentin Chary     buffer_free(&vs->input);
13353e230dd2SCorentin Chary     buffer_free(&vs->output);
13363e230dd2SCorentin Chary 
1337fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
13383e230dd2SCorentin Chary 
13393e230dd2SCorentin Chary     vnc_zlib_clear(vs);
13403e230dd2SCorentin Chary     vnc_tight_clear(vs);
1341148954faSCorentin Chary     vnc_zrle_clear(vs);
13423e230dd2SCorentin Chary 
13433e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13443e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
13453e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13463e230dd2SCorentin Chary     audio_del(vs);
1347c2f2ba49SGerd Hoffmann     qkbd_state_lift_all_keys(vs->vd->kbd);
13483e230dd2SCorentin Chary 
134990cd03a3SDaniel P. Berrange     if (vs->mouse_mode_notifier.notify != NULL) {
13506fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
135190cd03a3SDaniel P. Berrange     }
135290cd03a3SDaniel P. Berrange     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1353c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1354c7628bffSGerd Hoffmann         /* last client gone */
1355c7628bffSGerd Hoffmann         vnc_update_server_surface(vs->vd);
1356c7628bffSGerd Hoffmann     }
13571dbbe6f1SRao Lei     vnc_unlock_output(vs);
13581dbbe6f1SRao Lei 
13591b17f1e9SMarc-André Lureau     if (vs->cbpeer.notifier.notify) {
13600bf41cabSGerd Hoffmann         qemu_clipboard_peer_unregister(&vs->cbpeer);
13610bf41cabSGerd Hoffmann     }
13623e230dd2SCorentin Chary 
1363bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
13646fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1365175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
13666fd8e79aSTim Hardeck     }
1367175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1368175b2a6eSCorentin Chary 
13697d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
13707267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
13717d964c9dSCorentin Chary     }
13727267c094SAnthony Liguori     g_free(vs->lossy_rect);
137304d2529dSDaniel P. Berrange 
137404d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->ioc));
137504d2529dSDaniel P. Berrange     vs->ioc = NULL;
137604d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->sioc));
137704d2529dSDaniel P. Berrange     vs->sioc = NULL;
1378f31f9c10SGerd Hoffmann     vs->magic = 0;
13796bf21f3dSLi Qiang     g_free(vs->zrle);
13806bf21f3dSLi Qiang     g_free(vs->tight);
13817267c094SAnthony Liguori     g_free(vs);
13823e230dd2SCorentin Chary }
13833e230dd2SCorentin Chary 
138434ab29c2SVladimir Sementsov-Ogievskiy size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
13853e230dd2SCorentin Chary {
138604d2529dSDaniel P. Berrange     if (ret <= 0) {
138704d2529dSDaniel P. Berrange         if (ret == 0) {
1388ad6374c4SDaniel P. Berrange             trace_vnc_client_eof(vs, vs->ioc);
1389537848eeSMichael Tokarev             vnc_disconnect_start(vs);
139004d2529dSDaniel P. Berrange         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1391ad6374c4SDaniel P. Berrange             trace_vnc_client_io_error(vs, vs->ioc,
139234ab29c2SVladimir Sementsov-Ogievskiy                                       err ? error_get_pretty(err) : "Unknown");
1393537848eeSMichael Tokarev             vnc_disconnect_start(vs);
13943e230dd2SCorentin Chary         }
13953e230dd2SCorentin Chary 
139634ab29c2SVladimir Sementsov-Ogievskiy         error_free(err);
13973e230dd2SCorentin Chary         return 0;
13983e230dd2SCorentin Chary     }
13993e230dd2SCorentin Chary     return ret;
14003e230dd2SCorentin Chary }
14013e230dd2SCorentin Chary 
14023e230dd2SCorentin Chary 
14033e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
14043e230dd2SCorentin Chary {
14053e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
14063e230dd2SCorentin Chary     vnc_disconnect_start(vs);
14073e230dd2SCorentin Chary }
14083e230dd2SCorentin Chary 
14093e305e4aSDaniel P. Berrange 
14103e230dd2SCorentin Chary /*
14113e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
14123e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
14133e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
14143e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
14153e230dd2SCorentin Chary  *
14163e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
14173e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
14183e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
14193e230dd2SCorentin Chary  * is active
14203e230dd2SCorentin Chary  *
14213e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
14223e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
142330b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
14243e230dd2SCorentin Chary  */
142530b80fd5SDaniel P. Berrange size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
14263e230dd2SCorentin Chary {
142704d2529dSDaniel P. Berrange     Error *err = NULL;
1428fdd1ab6aSDaniel P. Berrange     ssize_t ret;
142934ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
14303e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
143134ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
14323e230dd2SCorentin Chary }
14333e230dd2SCorentin Chary 
14343e230dd2SCorentin Chary 
14353e230dd2SCorentin Chary /*
14363e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
14373e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
14383e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
14393e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
14403e230dd2SCorentin Chary  *
14413e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
14423e230dd2SCorentin Chary  * the buffered output data if the socket would block.  Returns
144330b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
14443e230dd2SCorentin Chary  */
144530b80fd5SDaniel P. Berrange static size_t vnc_client_write_plain(VncState *vs)
14463e230dd2SCorentin Chary {
14476aa22a29SDaniel P. Berrange     size_t offset;
144830b80fd5SDaniel P. Berrange     size_t ret;
14493e230dd2SCorentin Chary 
14503e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14513e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
14523e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
14533e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
14543e230dd2SCorentin Chary 
14553e230dd2SCorentin Chary     if (vs->sasl.conn &&
14563e230dd2SCorentin Chary         vs->sasl.runSSF &&
14573e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
14583e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
14593e230dd2SCorentin Chary         if (ret)
14603e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
14613e230dd2SCorentin Chary     } else
14623e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14633e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
14643e230dd2SCorentin Chary     if (!ret)
14653e230dd2SCorentin Chary         return 0;
14663e230dd2SCorentin Chary 
1467ada8d2e4SDaniel P. Berrange     if (ret >= vs->force_update_offset) {
14686aa22a29SDaniel P. Berrange         if (vs->force_update_offset != 0) {
14696aa22a29SDaniel P. Berrange             trace_vnc_client_unthrottle_forced(vs, vs->ioc);
14706aa22a29SDaniel P. Berrange         }
1471ada8d2e4SDaniel P. Berrange         vs->force_update_offset = 0;
1472ada8d2e4SDaniel P. Berrange     } else {
1473ada8d2e4SDaniel P. Berrange         vs->force_update_offset -= ret;
1474ada8d2e4SDaniel P. Berrange     }
14756aa22a29SDaniel P. Berrange     offset = vs->output.offset;
147632ed2680STim Hardeck     buffer_advance(&vs->output, ret);
14776aa22a29SDaniel P. Berrange     if (offset >= vs->throttle_output_offset &&
14786aa22a29SDaniel P. Berrange         vs->output.offset < vs->throttle_output_offset) {
14796aa22a29SDaniel P. Berrange         trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
14806aa22a29SDaniel P. Berrange     }
14813e230dd2SCorentin Chary 
14823e230dd2SCorentin Chary     if (vs->output.offset == 0) {
148304d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
148404d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
148504d2529dSDaniel P. Berrange         }
148604d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
14872ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
14882ddafce7SDing Hui             vnc_client_io, vs, NULL);
14893e230dd2SCorentin Chary     }
14903e230dd2SCorentin Chary 
14913e230dd2SCorentin Chary     return ret;
14923e230dd2SCorentin Chary }
14933e230dd2SCorentin Chary 
14943e230dd2SCorentin Chary 
14953e230dd2SCorentin Chary /*
14963e230dd2SCorentin Chary  * First function called whenever there is data to be written to
14973e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
14983e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
14993e230dd2SCorentin Chary  */
150004d2529dSDaniel P. Berrange static void vnc_client_write_locked(VncState *vs)
15013e230dd2SCorentin Chary {
15023e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
15033e230dd2SCorentin Chary     if (vs->sasl.conn &&
15043e230dd2SCorentin Chary         vs->sasl.runSSF &&
15053e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
15063e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
15073e230dd2SCorentin Chary     } else
15083e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
15097536ee4bSTim Hardeck     {
15103e230dd2SCorentin Chary         vnc_client_write_plain(vs);
15113e230dd2SCorentin Chary     }
15127536ee4bSTim Hardeck }
15133e230dd2SCorentin Chary 
151404d2529dSDaniel P. Berrange static void vnc_client_write(VncState *vs)
1515bd023f95SCorentin Chary {
1516f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1517bd023f95SCorentin Chary     vnc_lock_output(vs);
1518d5f04223SDaniel P. Berrange     if (vs->output.offset) {
151904d2529dSDaniel P. Berrange         vnc_client_write_locked(vs);
152004d2529dSDaniel P. Berrange     } else if (vs->ioc != NULL) {
152104d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
152204d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
152304d2529dSDaniel P. Berrange         }
152404d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
15252ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
15262ddafce7SDing Hui             vnc_client_io, vs, NULL);
1527bd023f95SCorentin Chary     }
1528bd023f95SCorentin Chary     vnc_unlock_output(vs);
1529bd023f95SCorentin Chary }
1530bd023f95SCorentin Chary 
15313e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
15323e230dd2SCorentin Chary {
15333e230dd2SCorentin Chary     vs->read_handler = func;
15343e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
15353e230dd2SCorentin Chary }
15363e230dd2SCorentin Chary 
15373e230dd2SCorentin Chary 
15383e230dd2SCorentin Chary /*
15393e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
15403e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
15413e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
15423e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
15433e230dd2SCorentin Chary  *
15443e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
15453e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
15463e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
15473e230dd2SCorentin Chary  * is active
15483e230dd2SCorentin Chary  *
15493e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
15503e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
155130b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15523e230dd2SCorentin Chary  */
155330b80fd5SDaniel P. Berrange size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
15543e230dd2SCorentin Chary {
1555fdd1ab6aSDaniel P. Berrange     ssize_t ret;
155604d2529dSDaniel P. Berrange     Error *err = NULL;
155734ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
15583e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
155934ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
15603e230dd2SCorentin Chary }
15613e230dd2SCorentin Chary 
15623e230dd2SCorentin Chary 
15633e230dd2SCorentin Chary /*
15643e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
15653e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
15663e230dd2SCorentin Chary  * data as possible without blocking.
15673e230dd2SCorentin Chary  *
156830b80fd5SDaniel P. Berrange  * Returns the number of bytes read, which may be less than
156930b80fd5SDaniel P. Berrange  * the requested 'datalen' if the socket would block. Returns
157030b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15713e230dd2SCorentin Chary  */
157230b80fd5SDaniel P. Berrange static size_t vnc_client_read_plain(VncState *vs)
15733e230dd2SCorentin Chary {
157430b80fd5SDaniel P. Berrange     size_t ret;
15753e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
15763e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
15773e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
15783e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
15793e230dd2SCorentin Chary     if (!ret)
15803e230dd2SCorentin Chary         return 0;
15813e230dd2SCorentin Chary     vs->input.offset += ret;
15823e230dd2SCorentin Chary     return ret;
15833e230dd2SCorentin Chary }
15843e230dd2SCorentin Chary 
1585175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1586175b2a6eSCorentin Chary {
1587175b2a6eSCorentin Chary     VncState *vs = opaque;
1588175b2a6eSCorentin Chary 
1589f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1590175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1591175b2a6eSCorentin Chary }
15923e230dd2SCorentin Chary 
15933e230dd2SCorentin Chary /*
15943e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
15953e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
15963e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
1597ea697449SDaniel P. Berrange  * Returns 0 on success, -1 if client disconnected
15983e230dd2SCorentin Chary  */
1599ea697449SDaniel P. Berrange static int vnc_client_read(VncState *vs)
16003e230dd2SCorentin Chary {
160130b80fd5SDaniel P. Berrange     size_t ret;
16023e230dd2SCorentin Chary 
16033e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
16043e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
16053e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
16063e230dd2SCorentin Chary     else
16073e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
16083e230dd2SCorentin Chary         ret = vnc_client_read_plain(vs);
16093e230dd2SCorentin Chary     if (!ret) {
161004d2529dSDaniel P. Berrange         if (vs->disconnecting) {
16113e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1612ea697449SDaniel P. Berrange             return -1;
161304d2529dSDaniel P. Berrange         }
1614ea697449SDaniel P. Berrange         return 0;
16153e230dd2SCorentin Chary     }
16163e230dd2SCorentin Chary 
16173e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
16183e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
16193e230dd2SCorentin Chary         int ret;
16203e230dd2SCorentin Chary 
16213e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
162204d2529dSDaniel P. Berrange         if (vs->disconnecting) {
16233e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1624ea697449SDaniel P. Berrange             return -1;
16253e230dd2SCorentin Chary         }
16263e230dd2SCorentin Chary 
16273e230dd2SCorentin Chary         if (!ret) {
162832ed2680STim Hardeck             buffer_advance(&vs->input, len);
16293e230dd2SCorentin Chary         } else {
16303e230dd2SCorentin Chary             vs->read_handler_expect = ret;
16313e230dd2SCorentin Chary         }
16323e230dd2SCorentin Chary     }
1633ea697449SDaniel P. Berrange     return 0;
16343e230dd2SCorentin Chary }
16353e230dd2SCorentin Chary 
163604d2529dSDaniel P. Berrange gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
163704d2529dSDaniel P. Berrange                        GIOCondition condition, void *opaque)
163804d2529dSDaniel P. Berrange {
163904d2529dSDaniel P. Berrange     VncState *vs = opaque;
1640f31f9c10SGerd Hoffmann 
1641f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
16422ddafce7SDing Hui 
16432ddafce7SDing Hui     if (condition & (G_IO_HUP | G_IO_ERR)) {
16442ddafce7SDing Hui         vnc_disconnect_start(vs);
16452ddafce7SDing Hui         return TRUE;
16462ddafce7SDing Hui     }
16472ddafce7SDing Hui 
164804d2529dSDaniel P. Berrange     if (condition & G_IO_IN) {
1649ea697449SDaniel P. Berrange         if (vnc_client_read(vs) < 0) {
16501bc3117aSGerd Hoffmann             /* vs is free()ed here */
16511bc3117aSGerd Hoffmann             return TRUE;
1652ea697449SDaniel P. Berrange         }
165304d2529dSDaniel P. Berrange     }
165404d2529dSDaniel P. Berrange     if (condition & G_IO_OUT) {
165504d2529dSDaniel P. Berrange         vnc_client_write(vs);
165604d2529dSDaniel P. Berrange     }
16571bc3117aSGerd Hoffmann 
1658d49b87f0SKlim Kireev     if (vs->disconnecting) {
1659d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1660d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1661d49b87f0SKlim Kireev         }
1662d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1663d49b87f0SKlim Kireev     }
166404d2529dSDaniel P. Berrange     return TRUE;
166504d2529dSDaniel P. Berrange }
166604d2529dSDaniel P. Berrange 
166704d2529dSDaniel P. Berrange 
1668f887cf16SDaniel P. Berrange /*
1669f887cf16SDaniel P. Berrange  * Scale factor to apply to vs->throttle_output_offset when checking for
1670f887cf16SDaniel P. Berrange  * hard limit. Worst case normal usage could be x2, if we have a complete
1671f887cf16SDaniel P. Berrange  * incremental update and complete forced update in the output buffer.
1672f887cf16SDaniel P. Berrange  * So x3 should be good enough, but we pick x5 to be conservative and thus
1673f887cf16SDaniel P. Berrange  * (hopefully) never trigger incorrectly.
1674f887cf16SDaniel P. Berrange  */
1675f887cf16SDaniel P. Berrange #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1676f887cf16SDaniel P. Berrange 
16773e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
16783e230dd2SCorentin Chary {
1679f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1680f887cf16SDaniel P. Berrange     if (vs->disconnecting) {
1681f887cf16SDaniel P. Berrange         return;
1682f887cf16SDaniel P. Berrange     }
1683f887cf16SDaniel P. Berrange     /* Protection against malicious client/guest to prevent our output
1684f887cf16SDaniel P. Berrange      * buffer growing without bound if client stops reading data. This
1685f887cf16SDaniel P. Berrange      * should rarely trigger, because we have earlier throttling code
1686f887cf16SDaniel P. Berrange      * which stops issuing framebuffer updates and drops audio data
1687f887cf16SDaniel P. Berrange      * if the throttle_output_offset value is exceeded. So we only reach
1688f887cf16SDaniel P. Berrange      * this higher level if a huge number of pseudo-encodings get
1689f887cf16SDaniel P. Berrange      * triggered while data can't be sent on the socket.
1690f887cf16SDaniel P. Berrange      *
1691f887cf16SDaniel P. Berrange      * NB throttle_output_offset can be zero during early protocol
1692f887cf16SDaniel P. Berrange      * handshake, or from the job thread's VncState clone
1693f887cf16SDaniel P. Berrange      */
1694f887cf16SDaniel P. Berrange     if (vs->throttle_output_offset != 0 &&
1695dffa1de0SDaniel P. Berrangé         (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1696dffa1de0SDaniel P. Berrangé         vs->throttle_output_offset) {
16976aa22a29SDaniel P. Berrange         trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
16986aa22a29SDaniel P. Berrange                                       vs->throttle_output_offset);
1699f887cf16SDaniel P. Berrange         vnc_disconnect_start(vs);
1700f887cf16SDaniel P. Berrange         return;
1701f887cf16SDaniel P. Berrange     }
17023e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
17033e230dd2SCorentin Chary 
170404d2529dSDaniel P. Berrange     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
170504d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
170604d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
170704d2529dSDaniel P. Berrange         }
170804d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
17092ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
17102ddafce7SDing Hui             vnc_client_io, vs, NULL);
17113e230dd2SCorentin Chary     }
17123e230dd2SCorentin Chary 
17133e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
17143e230dd2SCorentin Chary }
17153e230dd2SCorentin Chary 
17163e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
17173e230dd2SCorentin Chary {
17183e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
17193e230dd2SCorentin Chary }
17203e230dd2SCorentin Chary 
17213e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
17223e230dd2SCorentin Chary {
17233e230dd2SCorentin Chary     uint8_t buf[4];
17243e230dd2SCorentin Chary 
17253e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
17263e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
17273e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
17283e230dd2SCorentin Chary     buf[3] = value & 0xFF;
17293e230dd2SCorentin Chary 
17303e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
17313e230dd2SCorentin Chary }
17323e230dd2SCorentin Chary 
17333e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
17343e230dd2SCorentin Chary {
17353e230dd2SCorentin Chary     uint8_t buf[2];
17363e230dd2SCorentin Chary 
17373e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
17383e230dd2SCorentin Chary     buf[1] = value & 0xFF;
17393e230dd2SCorentin Chary 
17403e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
17413e230dd2SCorentin Chary }
17423e230dd2SCorentin Chary 
17433e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
17443e230dd2SCorentin Chary {
17453e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
17463e230dd2SCorentin Chary }
17473e230dd2SCorentin Chary 
17483e230dd2SCorentin Chary void vnc_flush(VncState *vs)
17493e230dd2SCorentin Chary {
1750bd023f95SCorentin Chary     vnc_lock_output(vs);
1751d5f04223SDaniel P. Berrange     if (vs->ioc != NULL && vs->output.offset) {
1752bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1753bd023f95SCorentin Chary     }
1754d49b87f0SKlim Kireev     if (vs->disconnecting) {
1755d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1756d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1757d49b87f0SKlim Kireev         }
1758d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1759d49b87f0SKlim Kireev     }
1760bd023f95SCorentin Chary     vnc_unlock_output(vs);
17613e230dd2SCorentin Chary }
17623e230dd2SCorentin Chary 
176371a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
17643e230dd2SCorentin Chary {
17653e230dd2SCorentin Chary     return data[offset];
17663e230dd2SCorentin Chary }
17673e230dd2SCorentin Chary 
176871a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
17693e230dd2SCorentin Chary {
17703e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
17713e230dd2SCorentin Chary }
17723e230dd2SCorentin Chary 
177371a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
17743e230dd2SCorentin Chary {
17753e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
17763e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
17773e230dd2SCorentin Chary }
17783e230dd2SCorentin Chary 
17793e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
17803e230dd2SCorentin Chary {
17813e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
17823e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
17833e230dd2SCorentin Chary }
17843e230dd2SCorentin Chary 
17859e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
17863e230dd2SCorentin Chary {
17873e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
178814768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
17893e230dd2SCorentin Chary 
17903e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1791bd023f95SCorentin Chary         vnc_lock_output(vs);
17923e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
17933e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
17943e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
17953e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1796bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1797bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
17983e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1799bd023f95SCorentin Chary         vnc_unlock_output(vs);
18003e230dd2SCorentin Chary         vnc_flush(vs);
18013e230dd2SCorentin Chary     }
18023e230dd2SCorentin Chary     vs->absolute = absolute;
18033e230dd2SCorentin Chary }
18043e230dd2SCorentin Chary 
18053e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
18063e230dd2SCorentin Chary {
18077fb1cf16SEric Blake     static uint32_t bmap[INPUT_BUTTON__MAX] = {
180814768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
180914768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
181014768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
1811f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1812f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
181314768ebaSGerd Hoffmann     };
181414768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1815bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1816bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
18173e230dd2SCorentin Chary 
181814768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
181914768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
182014768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
182114768ebaSGerd Hoffmann     }
18223e230dd2SCorentin Chary 
18233e230dd2SCorentin Chary     if (vs->absolute) {
18249cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
18259cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
18263e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
182714768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
182814768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
18293e230dd2SCorentin Chary     } else {
183014768ebaSGerd Hoffmann         if (vs->last_x != -1) {
183114768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
183214768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
183314768ebaSGerd Hoffmann         }
18343e230dd2SCorentin Chary         vs->last_x = x;
18353e230dd2SCorentin Chary         vs->last_y = y;
18363e230dd2SCorentin Chary     }
183714768ebaSGerd Hoffmann     qemu_input_event_sync();
18383e230dd2SCorentin Chary }
18393e230dd2SCorentin Chary 
1840c2f2ba49SGerd Hoffmann static void press_key(VncState *vs, QKeyCode qcode)
18413e230dd2SCorentin Chary {
1842c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, true);
1843c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, false);
18443e230dd2SCorentin Chary }
18453e230dd2SCorentin Chary 
1846ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1847ab99e5c1SLei Li {
1848ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1849ab99e5c1SLei Li         return;
1850ab99e5c1SLei Li     }
1851ab99e5c1SLei Li 
1852ab99e5c1SLei Li     vnc_lock_output(vs);
1853ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1854ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1855ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1856ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1857a54f0d2bSPierre Ossman     vnc_write_u8(vs, vs->vd->ledstate);
1858ab99e5c1SLei Li     vnc_unlock_output(vs);
1859ab99e5c1SLei Li     vnc_flush(vs);
1860ab99e5c1SLei Li }
1861ab99e5c1SLei Li 
18623e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
18633e230dd2SCorentin Chary {
1864a54f0d2bSPierre Ossman     VncDisplay *vd = opaque;
1865a54f0d2bSPierre Ossman     VncState *client;
18663e230dd2SCorentin Chary 
186740066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
186840066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
186940066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
187040066175SGerd Hoffmann 
1871a54f0d2bSPierre Ossman     if (ledstate == vd->ledstate) {
1872a54f0d2bSPierre Ossman         return;
187396f3d174SLei Li     }
1874ab99e5c1SLei Li 
1875a54f0d2bSPierre Ossman     vd->ledstate = ledstate;
1876a54f0d2bSPierre Ossman 
1877a54f0d2bSPierre Ossman     QTAILQ_FOREACH(client, &vd->clients, next) {
1878a54f0d2bSPierre Ossman         vnc_led_state_change(client);
1879ab99e5c1SLei Li     }
18803e230dd2SCorentin Chary }
18813e230dd2SCorentin Chary 
18823e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
18833e230dd2SCorentin Chary {
1884c2f2ba49SGerd Hoffmann     QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1885c2f2ba49SGerd Hoffmann 
18863e230dd2SCorentin Chary     /* QEMU console switch */
1887c2f2ba49SGerd Hoffmann     switch (qcode) {
1888c2f2ba49SGerd Hoffmann     case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1889c2f2ba49SGerd Hoffmann         if (vs->vd->dcl.con == NULL && down &&
1890c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1891c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
18923e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
1893c2f2ba49SGerd Hoffmann             qkbd_state_lift_all_keys(vs->vd->kbd);
1894c2f2ba49SGerd Hoffmann             console_select(qcode - Q_KEY_CODE_1);
18953e230dd2SCorentin Chary             return;
18963e230dd2SCorentin Chary         }
1897c2f2ba49SGerd Hoffmann     default:
18983e230dd2SCorentin Chary         break;
18993e230dd2SCorentin Chary     }
19003e230dd2SCorentin Chary 
1901e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1902e7b2aaccSLei Li        state extension.
1903e7b2aaccSLei Li     */
19049892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1905e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
19063e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
19073e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
19083e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
19093e230dd2SCorentin Chary            toggles numlock away from the VNC window.
19103e230dd2SCorentin Chary         */
19113e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1912c2f2ba49SGerd Hoffmann             if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
191340066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
1914c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
19153e230dd2SCorentin Chary             }
19163e230dd2SCorentin Chary         } else {
1917c2f2ba49SGerd Hoffmann             if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
191840066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
1919c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
19203e230dd2SCorentin Chary             }
19213e230dd2SCorentin Chary         }
19223e230dd2SCorentin Chary     }
19233e230dd2SCorentin Chary 
19249892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1925e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
19263e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
19273e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
19283e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
19293e230dd2SCorentin Chary            toggles capslock away from the VNC window.
19303e230dd2SCorentin Chary         */
19313e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1932c2f2ba49SGerd Hoffmann         bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1933c2f2ba49SGerd Hoffmann         bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
19343e230dd2SCorentin Chary         if (capslock) {
19353e230dd2SCorentin Chary             if (uppercase == shift) {
193640066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
1937c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
19383e230dd2SCorentin Chary             }
19393e230dd2SCorentin Chary         } else {
19403e230dd2SCorentin Chary             if (uppercase != shift) {
194140066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
1942c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
19433e230dd2SCorentin Chary             }
19443e230dd2SCorentin Chary         }
19453e230dd2SCorentin Chary     }
19463e230dd2SCorentin Chary 
1947c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, down);
1948c2f2ba49SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
1949c2f2ba49SGerd Hoffmann         bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1950c2f2ba49SGerd Hoffmann         bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
19513e230dd2SCorentin Chary         /* QEMU console emulation */
19523e230dd2SCorentin Chary         if (down) {
19533e230dd2SCorentin Chary             switch (keycode) {
19543e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
19553e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
19563e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
19573e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
19583e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
19593e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
19603e230dd2SCorentin Chary                 break;
19613e230dd2SCorentin Chary             case 0xc8:
19623e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_UP);
19633e230dd2SCorentin Chary                 break;
19643e230dd2SCorentin Chary             case 0xd0:
19653e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DOWN);
19663e230dd2SCorentin Chary                 break;
19673e230dd2SCorentin Chary             case 0xcb:
19683e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_LEFT);
19693e230dd2SCorentin Chary                 break;
19703e230dd2SCorentin Chary             case 0xcd:
19713e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_RIGHT);
19723e230dd2SCorentin Chary                 break;
19733e230dd2SCorentin Chary             case 0xd3:
19743e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DELETE);
19753e230dd2SCorentin Chary                 break;
19763e230dd2SCorentin Chary             case 0xc7:
19773e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_HOME);
19783e230dd2SCorentin Chary                 break;
19793e230dd2SCorentin Chary             case 0xcf:
19803e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_END);
19813e230dd2SCorentin Chary                 break;
19823e230dd2SCorentin Chary             case 0xc9:
19833e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEUP);
19843e230dd2SCorentin Chary                 break;
19853e230dd2SCorentin Chary             case 0xd1:
19863e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
19873e230dd2SCorentin Chary                 break;
19883e230dd2SCorentin Chary 
19893e230dd2SCorentin Chary             case 0x47:
19903e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
19913e230dd2SCorentin Chary                 break;
19923e230dd2SCorentin Chary             case 0x48:
19933e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
19943e230dd2SCorentin Chary                 break;
19953e230dd2SCorentin Chary             case 0x49:
19963e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
19973e230dd2SCorentin Chary                 break;
19983e230dd2SCorentin Chary             case 0x4b:
19993e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
20003e230dd2SCorentin Chary                 break;
20013e230dd2SCorentin Chary             case 0x4c:
20023e230dd2SCorentin Chary                 kbd_put_keysym('5');
20033e230dd2SCorentin Chary                 break;
20043e230dd2SCorentin Chary             case 0x4d:
20053e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
20063e230dd2SCorentin Chary                 break;
20073e230dd2SCorentin Chary             case 0x4f:
20083e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
20093e230dd2SCorentin Chary                 break;
20103e230dd2SCorentin Chary             case 0x50:
20113e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
20123e230dd2SCorentin Chary                 break;
20133e230dd2SCorentin Chary             case 0x51:
20143e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
20153e230dd2SCorentin Chary                 break;
20163e230dd2SCorentin Chary             case 0x52:
20173e230dd2SCorentin Chary                 kbd_put_keysym('0');
20183e230dd2SCorentin Chary                 break;
20193e230dd2SCorentin Chary             case 0x53:
20203e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
20213e230dd2SCorentin Chary                 break;
20223e230dd2SCorentin Chary 
20233e230dd2SCorentin Chary             case 0xb5:
20243e230dd2SCorentin Chary                 kbd_put_keysym('/');
20253e230dd2SCorentin Chary                 break;
20263e230dd2SCorentin Chary             case 0x37:
20273e230dd2SCorentin Chary                 kbd_put_keysym('*');
20283e230dd2SCorentin Chary                 break;
20293e230dd2SCorentin Chary             case 0x4a:
20303e230dd2SCorentin Chary                 kbd_put_keysym('-');
20313e230dd2SCorentin Chary                 break;
20323e230dd2SCorentin Chary             case 0x4e:
20333e230dd2SCorentin Chary                 kbd_put_keysym('+');
20343e230dd2SCorentin Chary                 break;
20353e230dd2SCorentin Chary             case 0x9c:
20363e230dd2SCorentin Chary                 kbd_put_keysym('\n');
20373e230dd2SCorentin Chary                 break;
20383e230dd2SCorentin Chary 
20393e230dd2SCorentin Chary             default:
2040e26437c2SGerd Hoffmann                 if (control) {
2041e26437c2SGerd Hoffmann                     kbd_put_keysym(sym & 0x1f);
2042e26437c2SGerd Hoffmann                 } else {
20433e230dd2SCorentin Chary                     kbd_put_keysym(sym);
2044e26437c2SGerd Hoffmann                 }
20453e230dd2SCorentin Chary                 break;
20463e230dd2SCorentin Chary             }
20473e230dd2SCorentin Chary         }
20483e230dd2SCorentin Chary     }
20493e230dd2SCorentin Chary }
20503e230dd2SCorentin Chary 
205140066175SGerd Hoffmann static const char *code2name(int keycode)
205240066175SGerd Hoffmann {
2053977c736fSMarkus Armbruster     return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
205440066175SGerd Hoffmann }
205540066175SGerd Hoffmann 
20563e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
20573e230dd2SCorentin Chary {
20583e230dd2SCorentin Chary     int keycode;
20593e230dd2SCorentin Chary     int lsym = sym;
20603e230dd2SCorentin Chary 
206181c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
20623e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
20633e230dd2SCorentin Chary     }
20643e230dd2SCorentin Chary 
2065abb4f2c9SGerd Hoffmann     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
206619c1b9fdSGerd Hoffmann                               vs->vd->kbd, down) & SCANCODE_KEYMASK;
206740066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
20683e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
20693e230dd2SCorentin Chary }
20703e230dd2SCorentin Chary 
20713e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
20723e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
20733e230dd2SCorentin Chary {
20743e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
207540066175SGerd Hoffmann     if (keyboard_layout) {
20763e230dd2SCorentin Chary         key_event(vs, down, sym);
207740066175SGerd Hoffmann     } else {
207840066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
20793e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
20803e230dd2SCorentin Chary     }
208140066175SGerd Hoffmann }
20823e230dd2SCorentin Chary 
20833e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
2084bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
20853e230dd2SCorentin Chary {
2086bea60dd7SPeter Lieven     if (incremental) {
2087fef1bbadSDaniel P. Berrange         if (vs->update != VNC_STATE_UPDATE_FORCE) {
2088fef1bbadSDaniel P. Berrange             vs->update = VNC_STATE_UPDATE_INCREMENTAL;
20893e230dd2SCorentin Chary         }
2090fef1bbadSDaniel P. Berrange     } else {
2091fef1bbadSDaniel P. Berrange         vs->update = VNC_STATE_UPDATE_FORCE;
2092f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2093104b8d19SGerd Hoffmann         if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
2094104b8d19SGerd Hoffmann             vnc_desktop_resize_ext(vs, 0);
2095104b8d19SGerd Hoffmann         }
20963e230dd2SCorentin Chary     }
2097fef1bbadSDaniel P. Berrange }
20983e230dd2SCorentin Chary 
20993e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
21003e230dd2SCorentin Chary {
2101bd023f95SCorentin Chary     vnc_lock_output(vs);
21023e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
21033e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
21043e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2105d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2106bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2107bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
21083e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
2109bd023f95SCorentin Chary     vnc_unlock_output(vs);
21103e230dd2SCorentin Chary     vnc_flush(vs);
21113e230dd2SCorentin Chary }
21123e230dd2SCorentin Chary 
21133e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
21143e230dd2SCorentin Chary {
2115bd023f95SCorentin Chary     vnc_lock_output(vs);
21163e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
21173e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
21183e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2119d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2120bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2121bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
21223e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2123bd023f95SCorentin Chary     vnc_unlock_output(vs);
21243e230dd2SCorentin Chary     vnc_flush(vs);
21253e230dd2SCorentin Chary }
21263e230dd2SCorentin Chary 
21277b5fa0b5SDaniel P. Berrangé static void send_xvp_message(VncState *vs, int code)
21287b5fa0b5SDaniel P. Berrangé {
21297b5fa0b5SDaniel P. Berrangé     vnc_lock_output(vs);
21307b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
21317b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 0); /* pad */
21327b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 1); /* version */
21337b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, code);
21347b5fa0b5SDaniel P. Berrangé     vnc_unlock_output(vs);
21357b5fa0b5SDaniel P. Berrangé     vnc_flush(vs);
21367b5fa0b5SDaniel P. Berrangé }
21377b5fa0b5SDaniel P. Berrangé 
21383e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
21393e230dd2SCorentin Chary {
21403e230dd2SCorentin Chary     int i;
21413e230dd2SCorentin Chary     unsigned int enc = 0;
21423e230dd2SCorentin Chary 
21433e230dd2SCorentin Chary     vs->features = 0;
21443e230dd2SCorentin Chary     vs->vnc_encoding = 0;
21456bf21f3dSLi Qiang     vs->tight->compression = 9;
21466bf21f3dSLi Qiang     vs->tight->quality = -1; /* Lossless by default */
21473e230dd2SCorentin Chary     vs->absolute = -1;
21483e230dd2SCorentin Chary 
21493e230dd2SCorentin Chary     /*
21503e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2151e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
21523e230dd2SCorentin Chary      * will be set at the end of the loop.
21533e230dd2SCorentin Chary      */
21543e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
21553e230dd2SCorentin Chary         enc = encodings[i];
21563e230dd2SCorentin Chary         switch (enc) {
21573e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
21583e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21593e230dd2SCorentin Chary             break;
21603e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
21613e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
21623e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21633e230dd2SCorentin Chary             break;
21643e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
21653e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
21663e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21673e230dd2SCorentin Chary             break;
2168fe3e7f2dSJoel Martin #ifdef CONFIG_VNC_PNG
2169efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2170efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2171efe556adSCorentin Chary             vs->vnc_encoding = enc;
2172efe556adSCorentin Chary             break;
2173fe3e7f2dSJoel Martin #endif
21743e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
2175557ba0e5SCameron Esfahani             /*
2176557ba0e5SCameron Esfahani              * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2177557ba0e5SCameron Esfahani              * So prioritize ZRLE, even if the client hints that it prefers
2178557ba0e5SCameron Esfahani              * ZLIB.
2179557ba0e5SCameron Esfahani              */
2180557ba0e5SCameron Esfahani             if ((vs->features & VNC_FEATURE_ZRLE_MASK) == 0) {
21813e230dd2SCorentin Chary                 vs->features |= VNC_FEATURE_ZLIB_MASK;
21823e230dd2SCorentin Chary                 vs->vnc_encoding = enc;
2183557ba0e5SCameron Esfahani             }
21843e230dd2SCorentin Chary             break;
2185148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2186148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2187148954faSCorentin Chary             vs->vnc_encoding = enc;
2188148954faSCorentin Chary             break;
2189148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2190148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2191148954faSCorentin Chary             vs->vnc_encoding = enc;
2192148954faSCorentin Chary             break;
21933e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
21943e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
21953e230dd2SCorentin Chary             break;
2196763deea7SGerd Hoffmann         case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2197763deea7SGerd Hoffmann             vs->features |= VNC_FEATURE_RESIZE_EXT_MASK;
2198763deea7SGerd Hoffmann             break;
21993e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
22003e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
22013e230dd2SCorentin Chary             break;
22023e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
22033e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2204074a86d0SGerd Hoffmann             break;
2205074a86d0SGerd Hoffmann         case VNC_ENCODING_ALPHA_CURSOR:
2206074a86d0SGerd Hoffmann             vs->features |= VNC_FEATURE_ALPHA_CURSOR_MASK;
22073e230dd2SCorentin Chary             break;
22083e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
22093e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
22103e230dd2SCorentin Chary             break;
22113e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
22123e230dd2SCorentin Chary             send_ext_audio_ack(vs);
22133e230dd2SCorentin Chary             break;
22143e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
22153e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
22163e230dd2SCorentin Chary             break;
2217ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2218ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2219ab99e5c1SLei Li             break;
22207b5fa0b5SDaniel P. Berrangé         case VNC_ENCODING_XVP:
22217b5fa0b5SDaniel P. Berrangé             if (vs->vd->power_control) {
22227b5fa0b5SDaniel P. Berrangé                 vs->features |= VNC_FEATURE_XVP;
22237b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_INIT);
22247b5fa0b5SDaniel P. Berrangé             }
22257b5fa0b5SDaniel P. Berrangé             break;
22260bf41cabSGerd Hoffmann         case VNC_ENCODING_CLIPBOARD_EXT:
22270bf41cabSGerd Hoffmann             vs->features |= VNC_FEATURE_CLIPBOARD_EXT_MASK;
22280bf41cabSGerd Hoffmann             vnc_server_cut_text_caps(vs);
22290bf41cabSGerd Hoffmann             break;
22303e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
22316bf21f3dSLi Qiang             vs->tight->compression = (enc & 0x0F);
22323e230dd2SCorentin Chary             break;
22333e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2234b31f519eSCorentin Chary             if (vs->vd->lossy) {
22356bf21f3dSLi Qiang                 vs->tight->quality = (enc & 0x0F);
2236b31f519eSCorentin Chary             }
22373e230dd2SCorentin Chary             break;
22383e230dd2SCorentin Chary         default:
22393e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
22403e230dd2SCorentin Chary             break;
22413e230dd2SCorentin Chary         }
22423e230dd2SCorentin Chary     }
2243d239726cSGerd Hoffmann     vnc_desktop_resize(vs);
22449e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2245d239726cSGerd Hoffmann     vnc_led_state_change(vs);
2246d239726cSGerd Hoffmann     vnc_cursor_define(vs);
2247074a86d0SGerd Hoffmann }
22483e230dd2SCorentin Chary 
22493e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
22503e230dd2SCorentin Chary {
22519f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
22529f64916dSGerd Hoffmann 
22539f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
22543e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
22553e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
22563e230dd2SCorentin Chary     } else {
22573e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
22583e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
22593e230dd2SCorentin Chary     }
22603e230dd2SCorentin Chary }
22613e230dd2SCorentin Chary 
22620c426e45SAlexander Graf static void send_color_map(VncState *vs)
22630c426e45SAlexander Graf {
22640c426e45SAlexander Graf     int i;
22650c426e45SAlexander Graf 
2266947191b4SPeng Liang     vnc_lock_output(vs);
22670c426e45SAlexander Graf     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
22680c426e45SAlexander Graf     vnc_write_u8(vs,  0);    /* padding     */
22690c426e45SAlexander Graf     vnc_write_u16(vs, 0);    /* first color */
22700c426e45SAlexander Graf     vnc_write_u16(vs, 256);  /* # of colors */
22710c426e45SAlexander Graf 
22720c426e45SAlexander Graf     for (i = 0; i < 256; i++) {
22730c426e45SAlexander Graf         PixelFormat *pf = &vs->client_pf;
22740c426e45SAlexander Graf 
22750c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
22760c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
22770c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
22780c426e45SAlexander Graf     }
2279947191b4SPeng Liang     vnc_unlock_output(vs);
22800c426e45SAlexander Graf }
22810c426e45SAlexander Graf 
2282ec9fb41aSGerd Hoffmann static void set_pixel_format(VncState *vs, int bits_per_pixel,
22833e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
22843e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
22853e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
22863e230dd2SCorentin Chary {
22873e230dd2SCorentin Chary     if (!true_color_flag) {
22880c426e45SAlexander Graf         /* Expose a reasonable default 256 color map */
22890c426e45SAlexander Graf         bits_per_pixel = 8;
22900c426e45SAlexander Graf         red_max = 7;
22910c426e45SAlexander Graf         green_max = 7;
22920c426e45SAlexander Graf         blue_max = 3;
22930c426e45SAlexander Graf         red_shift = 0;
22940c426e45SAlexander Graf         green_shift = 3;
22950c426e45SAlexander Graf         blue_shift = 6;
22963e230dd2SCorentin Chary     }
22973e230dd2SCorentin Chary 
2298e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2299e6908bfeSPetr Matousek     case 8:
2300e6908bfeSPetr Matousek     case 16:
2301e6908bfeSPetr Matousek     case 32:
2302e6908bfeSPetr Matousek         break;
2303e6908bfeSPetr Matousek     default:
2304e6908bfeSPetr Matousek         vnc_client_error(vs);
2305e6908bfeSPetr Matousek         return;
2306e6908bfeSPetr Matousek     }
2307e6908bfeSPetr Matousek 
23084c65fed8SPrasad J Pandit     vs->client_pf.rmax = red_max ? red_max : 0xFF;
23097c9209e7SCédric Le Goater     vs->client_pf.rbits = ctpopl(red_max);
23109f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
23119f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
23124c65fed8SPrasad J Pandit     vs->client_pf.gmax = green_max ? green_max : 0xFF;
23137c9209e7SCédric Le Goater     vs->client_pf.gbits = ctpopl(green_max);
23149f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
23159f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
23164c65fed8SPrasad J Pandit     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
23177c9209e7SCédric Le Goater     vs->client_pf.bbits = ctpopl(blue_max);
23189f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
23199f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
23209f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
23219f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
23229f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
23239f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
23243e230dd2SCorentin Chary 
23250c426e45SAlexander Graf     if (!true_color_flag) {
23260c426e45SAlexander Graf         send_color_map(vs);
23270c426e45SAlexander Graf     }
23280c426e45SAlexander Graf 
23293e230dd2SCorentin Chary     set_pixel_conversion(vs);
23303e230dd2SCorentin Chary 
23311d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
23321d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
23333e230dd2SCorentin Chary }
23343e230dd2SCorentin Chary 
23353e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
23363e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
23373e230dd2SCorentin Chary 
23389f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
23399f64916dSGerd Hoffmann 
23409f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
23419f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
23423e230dd2SCorentin Chary 
23433e230dd2SCorentin Chary #ifdef HOST_WORDS_BIGENDIAN
23443e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
23453e230dd2SCorentin Chary #else
23463e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
23473e230dd2SCorentin Chary #endif
23483e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
23499f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
23509f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
23519f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
23529f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
23539f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
23549f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
23559f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
23563e230dd2SCorentin Chary 
23573e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
23583e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
23593e230dd2SCorentin Chary }
23603e230dd2SCorentin Chary 
23613e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
23623e230dd2SCorentin Chary {
23633e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
23643e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2365bd023f95SCorentin Chary         vnc_lock_output(vs);
23663e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
23673e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
23683e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2369d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
23703d3a528dSDaniel P. Berrangé                                vs->client_width,
23713d3a528dSDaniel P. Berrangé                                vs->client_height,
2372d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
23733e230dd2SCorentin Chary         pixel_format_message(vs);
2374bd023f95SCorentin Chary         vnc_unlock_output(vs);
23753e230dd2SCorentin Chary         vnc_flush(vs);
23763e230dd2SCorentin Chary     } else {
23773e230dd2SCorentin Chary         set_pixel_conversion(vs);
23783e230dd2SCorentin Chary     }
23793e230dd2SCorentin Chary }
23803e230dd2SCorentin Chary 
23813e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
23823e230dd2SCorentin Chary {
23833e230dd2SCorentin Chary     int i;
23843e230dd2SCorentin Chary     uint16_t limit;
2385cf070658SDaniel P. Berrangé     uint32_t freq;
23863e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
23873e230dd2SCorentin Chary 
23883e230dd2SCorentin Chary     if (data[0] > 3) {
23890f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
23903e230dd2SCorentin Chary     }
23913e230dd2SCorentin Chary 
23923e230dd2SCorentin Chary     switch (data[0]) {
23933e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
23943e230dd2SCorentin Chary         if (len == 1)
23953e230dd2SCorentin Chary             return 20;
23963e230dd2SCorentin Chary 
2397ec9fb41aSGerd Hoffmann         set_pixel_format(vs, read_u8(data, 4),
23983e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
23993e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
24003e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
24013e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
24023e230dd2SCorentin Chary         break;
24033e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
24043e230dd2SCorentin Chary         if (len == 1)
24053e230dd2SCorentin Chary             return 4;
24063e230dd2SCorentin Chary 
24073e230dd2SCorentin Chary         if (len == 4) {
24083e230dd2SCorentin Chary             limit = read_u16(data, 2);
24093e230dd2SCorentin Chary             if (limit > 0)
24103e230dd2SCorentin Chary                 return 4 + (limit * 4);
24113e230dd2SCorentin Chary         } else
24123e230dd2SCorentin Chary             limit = read_u16(data, 2);
24133e230dd2SCorentin Chary 
24143e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
24153e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
24163e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
24173e230dd2SCorentin Chary         }
24183e230dd2SCorentin Chary 
24193e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
24203e230dd2SCorentin Chary         break;
24213e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
24223e230dd2SCorentin Chary         if (len == 1)
24233e230dd2SCorentin Chary             return 10;
24243e230dd2SCorentin Chary 
24253e230dd2SCorentin Chary         framebuffer_update_request(vs,
24263e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
24273e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
24283e230dd2SCorentin Chary         break;
24293e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
24303e230dd2SCorentin Chary         if (len == 1)
24313e230dd2SCorentin Chary             return 8;
24323e230dd2SCorentin Chary 
24333e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
24343e230dd2SCorentin Chary         break;
24353e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
24363e230dd2SCorentin Chary         if (len == 1)
24373e230dd2SCorentin Chary             return 6;
24383e230dd2SCorentin Chary 
24393e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
24403e230dd2SCorentin Chary         break;
24413e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2442f9a70e79SPeter Lieven         if (len == 1) {
24433e230dd2SCorentin Chary             return 8;
2444f9a70e79SPeter Lieven         }
24453e230dd2SCorentin Chary         if (len == 8) {
24460bf41cabSGerd Hoffmann             uint32_t dlen = abs(read_s32(data, 4));
2447f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2448f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2449f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2450f9a70e79SPeter Lieven                 vnc_client_error(vs);
2451f9a70e79SPeter Lieven                 break;
2452f9a70e79SPeter Lieven             }
2453f9a70e79SPeter Lieven             if (dlen > 0) {
24543e230dd2SCorentin Chary                 return 8 + dlen;
24553e230dd2SCorentin Chary             }
2456f9a70e79SPeter Lieven         }
24573e230dd2SCorentin Chary 
24580bf41cabSGerd Hoffmann         if (read_s32(data, 4) < 0) {
24590bf41cabSGerd Hoffmann             vnc_client_cut_text_ext(vs, abs(read_s32(data, 4)),
24600bf41cabSGerd Hoffmann                                     read_u32(data, 8), data + 12);
24610bf41cabSGerd Hoffmann             break;
24620bf41cabSGerd Hoffmann         }
24630bf41cabSGerd Hoffmann         vnc_client_cut_text(vs, read_u32(data, 4), data + 8);
24643e230dd2SCorentin Chary         break;
24657b5fa0b5SDaniel P. Berrangé     case VNC_MSG_CLIENT_XVP:
24667b5fa0b5SDaniel P. Berrangé         if (!(vs->features & VNC_FEATURE_XVP)) {
24677b5fa0b5SDaniel P. Berrangé             error_report("vnc: xvp client message while disabled");
24687b5fa0b5SDaniel P. Berrangé             vnc_client_error(vs);
24697b5fa0b5SDaniel P. Berrangé             break;
24707b5fa0b5SDaniel P. Berrangé         }
24717b5fa0b5SDaniel P. Berrangé         if (len == 1) {
24727b5fa0b5SDaniel P. Berrangé             return 4;
24737b5fa0b5SDaniel P. Berrangé         }
24747b5fa0b5SDaniel P. Berrangé         if (len == 4) {
24757b5fa0b5SDaniel P. Berrangé             uint8_t version = read_u8(data, 2);
24767b5fa0b5SDaniel P. Berrangé             uint8_t action = read_u8(data, 3);
24777b5fa0b5SDaniel P. Berrangé 
24787b5fa0b5SDaniel P. Berrangé             if (version != 1) {
24797b5fa0b5SDaniel P. Berrangé                 error_report("vnc: xvp client message version %d != 1",
24807b5fa0b5SDaniel P. Berrangé                              version);
24817b5fa0b5SDaniel P. Berrangé                 vnc_client_error(vs);
24827b5fa0b5SDaniel P. Berrangé                 break;
24837b5fa0b5SDaniel P. Berrangé             }
24847b5fa0b5SDaniel P. Berrangé 
24857b5fa0b5SDaniel P. Berrangé             switch (action) {
24867b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_SHUTDOWN:
24877b5fa0b5SDaniel P. Berrangé                 qemu_system_powerdown_request();
24887b5fa0b5SDaniel P. Berrangé                 break;
24897b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_REBOOT:
24907b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24917b5fa0b5SDaniel P. Berrangé                 break;
24927b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_RESET:
24937b5fa0b5SDaniel P. Berrangé                 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
24947b5fa0b5SDaniel P. Berrangé                 break;
24957b5fa0b5SDaniel P. Berrangé             default:
24967b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24977b5fa0b5SDaniel P. Berrangé                 break;
24987b5fa0b5SDaniel P. Berrangé             }
24997b5fa0b5SDaniel P. Berrangé         }
25007b5fa0b5SDaniel P. Berrangé         break;
25013e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
25023e230dd2SCorentin Chary         if (len == 1)
25033e230dd2SCorentin Chary             return 2;
25043e230dd2SCorentin Chary 
25053e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
25063e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
25073e230dd2SCorentin Chary             if (len == 2)
25083e230dd2SCorentin Chary                 return 12;
25093e230dd2SCorentin Chary 
25103e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
25113e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
25123e230dd2SCorentin Chary             break;
25133e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
25143e230dd2SCorentin Chary             if (len == 2)
25153e230dd2SCorentin Chary                 return 4;
25163e230dd2SCorentin Chary 
25173e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
25183e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2519adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_enable(vs, vs->ioc);
25203e230dd2SCorentin Chary                 audio_add(vs);
25213e230dd2SCorentin Chary                 break;
25223e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2523adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_disable(vs, vs->ioc);
25243e230dd2SCorentin Chary                 audio_del(vs);
25253e230dd2SCorentin Chary                 break;
25263e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
25273e230dd2SCorentin Chary                 if (len == 4)
25283e230dd2SCorentin Chary                     return 10;
25293e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
253085bc5852SKővágó, Zoltán                 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
253185bc5852SKővágó, Zoltán                 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
253285bc5852SKővágó, Zoltán                 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
253385bc5852SKővágó, Zoltán                 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
253485bc5852SKővágó, Zoltán                 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
253585bc5852SKővágó, Zoltán                 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
25363e230dd2SCorentin Chary                 default:
2537153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
25383e230dd2SCorentin Chary                     vnc_client_error(vs);
25393e230dd2SCorentin Chary                     break;
25403e230dd2SCorentin Chary                 }
25413e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
25423e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2543090fdc83SMarc-André Lureau                     VNC_DEBUG("Invalid audio channel count %d\n",
25443e230dd2SCorentin Chary                               read_u8(data, 5));
25453e230dd2SCorentin Chary                     vnc_client_error(vs);
25463e230dd2SCorentin Chary                     break;
25473e230dd2SCorentin Chary                 }
2548cf070658SDaniel P. Berrangé                 freq = read_u32(data, 6);
2549cf070658SDaniel P. Berrangé                 /* No official limit for protocol, but 48khz is a sensible
2550cf070658SDaniel P. Berrangé                  * upper bound for trustworthy clients, and this limit
2551cf070658SDaniel P. Berrangé                  * protects calculations involving 'vs->as.freq' later.
2552cf070658SDaniel P. Berrangé                  */
2553cf070658SDaniel P. Berrangé                 if (freq > 48000) {
2554cf070658SDaniel P. Berrangé                     VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2555cf070658SDaniel P. Berrangé                     vnc_client_error(vs);
2556cf070658SDaniel P. Berrangé                     break;
2557cf070658SDaniel P. Berrangé                 }
2558cf070658SDaniel P. Berrangé                 vs->as.freq = freq;
2559adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_format(
2560adc8fce8SDaniel P. Berrangé                     vs, vs->ioc, vs->as.fmt, vs->as.nchannels, vs->as.freq);
25613e230dd2SCorentin Chary                 break;
25623e230dd2SCorentin Chary             default:
2563153130cdSDaniel P. Berrange                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
25643e230dd2SCorentin Chary                 vnc_client_error(vs);
25653e230dd2SCorentin Chary                 break;
25663e230dd2SCorentin Chary             }
25673e230dd2SCorentin Chary             break;
25683e230dd2SCorentin Chary 
25693e230dd2SCorentin Chary         default:
2570153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
25713e230dd2SCorentin Chary             vnc_client_error(vs);
25723e230dd2SCorentin Chary             break;
25733e230dd2SCorentin Chary         }
25743e230dd2SCorentin Chary         break;
2575763deea7SGerd Hoffmann     case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2576763deea7SGerd Hoffmann     {
2577763deea7SGerd Hoffmann         size_t size;
2578763deea7SGerd Hoffmann         uint8_t screens;
2579adc8fce8SDaniel P. Berrangé         int w, h;
2580763deea7SGerd Hoffmann 
2581763deea7SGerd Hoffmann         if (len < 8) {
2582763deea7SGerd Hoffmann             return 8;
2583763deea7SGerd Hoffmann         }
2584763deea7SGerd Hoffmann 
2585763deea7SGerd Hoffmann         screens = read_u8(data, 6);
2586763deea7SGerd Hoffmann         size    = 8 + screens * 16;
2587763deea7SGerd Hoffmann         if (len < size) {
2588763deea7SGerd Hoffmann             return size;
2589763deea7SGerd Hoffmann         }
2590adc8fce8SDaniel P. Berrangé         w = read_u16(data, 2);
2591adc8fce8SDaniel P. Berrangé         h = read_u16(data, 4);
2592763deea7SGerd Hoffmann 
2593adc8fce8SDaniel P. Berrangé         trace_vnc_msg_client_set_desktop_size(vs, vs->ioc, w, h, screens);
2594763deea7SGerd Hoffmann         if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2595763deea7SGerd Hoffmann             QemuUIInfo info;
2596763deea7SGerd Hoffmann             memset(&info, 0, sizeof(info));
2597adc8fce8SDaniel P. Berrangé             info.width = w;
2598adc8fce8SDaniel P. Berrangé             info.height = h;
2599ca19ef52SMarc-André Lureau             dpy_set_ui_info(vs->vd->dcl.con, &info, false);
2600763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2601763deea7SGerd Hoffmann         } else {
2602763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2603763deea7SGerd Hoffmann         }
2604763deea7SGerd Hoffmann 
2605763deea7SGerd Hoffmann         break;
2606763deea7SGerd Hoffmann     }
26073e230dd2SCorentin Chary     default:
2608153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
26093e230dd2SCorentin Chary         vnc_client_error(vs);
26103e230dd2SCorentin Chary         break;
26113e230dd2SCorentin Chary     }
26123e230dd2SCorentin Chary 
2613e2b72cb6SDaniel P. Berrange     vnc_update_throttle_offset(vs);
26143e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
26153e230dd2SCorentin Chary     return 0;
26163e230dd2SCorentin Chary }
26173e230dd2SCorentin Chary 
26183e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
26193e230dd2SCorentin Chary {
26203e230dd2SCorentin Chary     char buf[1024];
26218cf36489SGerd Hoffmann     VncShareMode mode;
26223e230dd2SCorentin Chary     int size;
26233e230dd2SCorentin Chary 
26248cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
26258cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
26268cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
26278cf36489SGerd Hoffmann         /*
26288cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
26298cf36489SGerd Hoffmann          *
26308cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
26318cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
26328cf36489SGerd Hoffmann          * reasons.
26338cf36489SGerd Hoffmann          */
26348cf36489SGerd Hoffmann         break;
26358cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
26368cf36489SGerd Hoffmann         /*
26378cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
26388cf36489SGerd Hoffmann          *
26398cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
26408cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
26418cf36489SGerd Hoffmann          * as no exclusive connection exists.
26428cf36489SGerd Hoffmann          *
26438cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
26448cf36489SGerd Hoffmann          */
26458cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
26468cf36489SGerd Hoffmann             VncState *client;
26478cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
26488cf36489SGerd Hoffmann                 if (vs == client) {
26498cf36489SGerd Hoffmann                     continue;
26508cf36489SGerd Hoffmann                 }
26518cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
26528cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
26538cf36489SGerd Hoffmann                     continue;
26548cf36489SGerd Hoffmann                 }
26558cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
26568cf36489SGerd Hoffmann             }
26578cf36489SGerd Hoffmann         }
26588cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
26598cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
26608cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
26618cf36489SGerd Hoffmann                 return 0;
26628cf36489SGerd Hoffmann             }
26638cf36489SGerd Hoffmann         }
26648cf36489SGerd Hoffmann         break;
26658cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
26668cf36489SGerd Hoffmann         /*
26678cf36489SGerd Hoffmann          * Policy: Shared connects only.
26688cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
26698cf36489SGerd Hoffmann          *
26708cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
26718cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
26728cf36489SGerd Hoffmann          * client disconnect everybody else.
26738cf36489SGerd Hoffmann          */
26748cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
26758cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
26768cf36489SGerd Hoffmann             return 0;
26778cf36489SGerd Hoffmann         }
26788cf36489SGerd Hoffmann         break;
26798cf36489SGerd Hoffmann     }
26808cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
26818cf36489SGerd Hoffmann 
2682e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2683e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2684e5f34cddSGerd Hoffmann         return 0;
2685e5f34cddSGerd Hoffmann     }
2686e5f34cddSGerd Hoffmann 
26874c956bd8SDaniel P. Berrange     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
26884c956bd8SDaniel P. Berrange            pixman_image_get_width(vs->vd->server) >= 0);
26894c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
26904c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
2691bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2692bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
26933e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
26943e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
26953e230dd2SCorentin Chary 
26963e230dd2SCorentin Chary     pixel_format_message(vs);
26973e230dd2SCorentin Chary 
269897efe4f9SThomas Huth     if (qemu_name) {
26993e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
270097efe4f9SThomas Huth         if (size > sizeof(buf)) {
270197efe4f9SThomas Huth             size = sizeof(buf);
270297efe4f9SThomas Huth         }
270397efe4f9SThomas Huth     } else {
27043e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
270597efe4f9SThomas Huth     }
27063e230dd2SCorentin Chary 
27073e230dd2SCorentin Chary     vnc_write_u32(vs, size);
27083e230dd2SCorentin Chary     vnc_write(vs, buf, size);
27093e230dd2SCorentin Chary     vnc_flush(vs);
27103e230dd2SCorentin Chary 
27113e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2712fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
27133e230dd2SCorentin Chary 
27143e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
27153e230dd2SCorentin Chary 
27163e230dd2SCorentin Chary     return 0;
27173e230dd2SCorentin Chary }
27183e230dd2SCorentin Chary 
27193e230dd2SCorentin Chary void start_client_init(VncState *vs)
27203e230dd2SCorentin Chary {
27213e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
27223e230dd2SCorentin Chary }
27233e230dd2SCorentin Chary 
27244347e638SRichard Henderson static void authentication_failed(VncState *vs)
27254347e638SRichard Henderson {
27264347e638SRichard Henderson     vnc_write_u32(vs, 1); /* Reject auth */
27274347e638SRichard Henderson     if (vs->minor >= 8) {
27284347e638SRichard Henderson         static const char err[] = "Authentication failed";
27294347e638SRichard Henderson         vnc_write_u32(vs, sizeof(err));
27304347e638SRichard Henderson         vnc_write(vs, err, sizeof(err));
27314347e638SRichard Henderson     }
27324347e638SRichard Henderson     vnc_flush(vs);
27334347e638SRichard Henderson     vnc_client_error(vs);
27344347e638SRichard Henderson }
27354347e638SRichard Henderson 
273683bee4b5SDaniel P. Berrangé static void
273783bee4b5SDaniel P. Berrangé vnc_munge_des_rfb_key(unsigned char *key, size_t nkey)
273883bee4b5SDaniel P. Berrangé {
273983bee4b5SDaniel P. Berrangé     size_t i;
274083bee4b5SDaniel P. Berrangé     for (i = 0; i < nkey; i++) {
274183bee4b5SDaniel P. Berrangé         uint8_t r = key[i];
274283bee4b5SDaniel P. Berrangé         r = (r & 0xf0) >> 4 | (r & 0x0f) << 4;
274383bee4b5SDaniel P. Berrangé         r = (r & 0xcc) >> 2 | (r & 0x33) << 2;
274483bee4b5SDaniel P. Berrangé         r = (r & 0xaa) >> 1 | (r & 0x55) << 1;
274583bee4b5SDaniel P. Berrangé         key[i] = r;
274683bee4b5SDaniel P. Berrangé     }
274783bee4b5SDaniel P. Berrangé }
274883bee4b5SDaniel P. Berrangé 
27493e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
27503e230dd2SCorentin Chary {
27513e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2752800567a6SDaniel P. Berrange     size_t i, pwlen;
27533e230dd2SCorentin Chary     unsigned char key[8];
27543c9405a0SGerd Hoffmann     time_t now = time(NULL);
275560928458SGonglei     QCryptoCipher *cipher = NULL;
2756800567a6SDaniel P. Berrange     Error *err = NULL;
27573e230dd2SCorentin Chary 
27581cd20f8bSAnthony Liguori     if (!vs->vd->password) {
27597364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
27606bffdf0fSGerd Hoffmann         goto reject;
27613e230dd2SCorentin Chary     }
27623c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
27637364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
27643c9405a0SGerd Hoffmann         goto reject;
27653c9405a0SGerd Hoffmann     }
27663e230dd2SCorentin Chary 
27673e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
27683e230dd2SCorentin Chary 
27693e230dd2SCorentin Chary     /* Calculate the expected challenge response */
27703e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
27713e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
27723e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
277383bee4b5SDaniel P. Berrangé     vnc_munge_des_rfb_key(key, sizeof(key));
2774800567a6SDaniel P. Berrange 
2775800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
277683bee4b5SDaniel P. Berrangé         QCRYPTO_CIPHER_ALG_DES,
2777800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2778800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2779800567a6SDaniel P. Berrange         &err);
2780800567a6SDaniel P. Berrange     if (!cipher) {
27817364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2782800567a6SDaniel P. Berrange                             error_get_pretty(err));
2783800567a6SDaniel P. Berrange         error_free(err);
2784800567a6SDaniel P. Berrange         goto reject;
2785800567a6SDaniel P. Berrange     }
2786800567a6SDaniel P. Berrange 
2787a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2788800567a6SDaniel P. Berrange                                vs->challenge,
2789800567a6SDaniel P. Berrange                                response,
2790800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2791800567a6SDaniel P. Berrange                                &err) < 0) {
27927364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2793800567a6SDaniel P. Berrange                             error_get_pretty(err));
2794800567a6SDaniel P. Berrange         error_free(err);
2795800567a6SDaniel P. Berrange         goto reject;
2796800567a6SDaniel P. Berrange     }
27973e230dd2SCorentin Chary 
27983e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
27993e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
28007364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
28016bffdf0fSGerd Hoffmann         goto reject;
28026bffdf0fSGerd Hoffmann     } else {
28037364dbdaSDaniel P. Berrange         trace_vnc_auth_pass(vs, vs->auth);
28046bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
28056bffdf0fSGerd Hoffmann         vnc_flush(vs);
28066bffdf0fSGerd Hoffmann 
28076bffdf0fSGerd Hoffmann         start_client_init(vs);
28086bffdf0fSGerd Hoffmann     }
280960928458SGonglei 
281060928458SGonglei     qcrypto_cipher_free(cipher);
28116bffdf0fSGerd Hoffmann     return 0;
28126bffdf0fSGerd Hoffmann 
28136bffdf0fSGerd Hoffmann reject:
28144347e638SRichard Henderson     authentication_failed(vs);
281560928458SGonglei     qcrypto_cipher_free(cipher);
28163e230dd2SCorentin Chary     return 0;
28173e230dd2SCorentin Chary }
28183e230dd2SCorentin Chary 
28193e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
28203e230dd2SCorentin Chary {
2821f7b2502cSRichard Henderson     Error *err = NULL;
2822f7b2502cSRichard Henderson 
2823f7b2502cSRichard Henderson     if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2824f7b2502cSRichard Henderson         trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2825f7b2502cSRichard Henderson                             error_get_pretty(err));
2826f7b2502cSRichard Henderson         error_free(err);
2827f7b2502cSRichard Henderson         authentication_failed(vs);
2828f7b2502cSRichard Henderson         return;
2829f7b2502cSRichard Henderson     }
2830f7b2502cSRichard Henderson 
28313e230dd2SCorentin Chary     /* Send client a 'random' challenge */
28323e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
28333e230dd2SCorentin Chary     vnc_flush(vs);
28343e230dd2SCorentin Chary 
28353e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
28363e230dd2SCorentin Chary }
28373e230dd2SCorentin Chary 
28383e230dd2SCorentin Chary 
28393e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
28403e230dd2SCorentin Chary {
28413e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
28423e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
28437e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
28447364dbdaSDaniel P. Berrange        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
28454347e638SRichard Henderson        authentication_failed(vs);
28463e230dd2SCorentin Chary     } else { /* Accept requested auth */
28477364dbdaSDaniel P. Berrange        trace_vnc_auth_start(vs, vs->auth);
28487e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
28493e230dd2SCorentin Chary        case VNC_AUTH_NONE:
28503e230dd2SCorentin Chary            if (vs->minor >= 8) {
28513e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
28523e230dd2SCorentin Chary                vnc_flush(vs);
28533e230dd2SCorentin Chary            }
28547364dbdaSDaniel P. Berrange            trace_vnc_auth_pass(vs, vs->auth);
28553e230dd2SCorentin Chary            start_client_init(vs);
28563e230dd2SCorentin Chary            break;
28573e230dd2SCorentin Chary 
28583e230dd2SCorentin Chary        case VNC_AUTH_VNC:
28593e230dd2SCorentin Chary            start_auth_vnc(vs);
28603e230dd2SCorentin Chary            break;
28613e230dd2SCorentin Chary 
28623e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
28633e230dd2SCorentin Chary            start_auth_vencrypt(vs);
28643e230dd2SCorentin Chary            break;
28653e230dd2SCorentin Chary 
28663e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
28673e230dd2SCorentin Chary        case VNC_AUTH_SASL:
28683e230dd2SCorentin Chary            start_auth_sasl(vs);
28693e230dd2SCorentin Chary            break;
28703e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
28713e230dd2SCorentin Chary 
28723e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
28737364dbdaSDaniel P. Berrange            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
28744347e638SRichard Henderson            authentication_failed(vs);
28753e230dd2SCorentin Chary        }
28763e230dd2SCorentin Chary     }
28773e230dd2SCorentin Chary     return 0;
28783e230dd2SCorentin Chary }
28793e230dd2SCorentin Chary 
28803e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
28813e230dd2SCorentin Chary {
28823e230dd2SCorentin Chary     char local[13];
28833e230dd2SCorentin Chary 
28843e230dd2SCorentin Chary     memcpy(local, version, 12);
28853e230dd2SCorentin Chary     local[12] = 0;
28863e230dd2SCorentin Chary 
28873e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
28883e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
28893e230dd2SCorentin Chary         vnc_client_error(vs);
28903e230dd2SCorentin Chary         return 0;
28913e230dd2SCorentin Chary     }
28923e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
28933e230dd2SCorentin Chary     if (vs->major != 3 ||
28943e230dd2SCorentin Chary         (vs->minor != 3 &&
28953e230dd2SCorentin Chary          vs->minor != 4 &&
28963e230dd2SCorentin Chary          vs->minor != 5 &&
28973e230dd2SCorentin Chary          vs->minor != 7 &&
28983e230dd2SCorentin Chary          vs->minor != 8)) {
28993e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
29003e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
29013e230dd2SCorentin Chary         vnc_flush(vs);
29023e230dd2SCorentin Chary         vnc_client_error(vs);
29033e230dd2SCorentin Chary         return 0;
29043e230dd2SCorentin Chary     }
29053e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
29063e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
29073e230dd2SCorentin Chary      */
29083e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
29093e230dd2SCorentin Chary         vs->minor = 3;
29103e230dd2SCorentin Chary 
29113e230dd2SCorentin Chary     if (vs->minor == 3) {
29127364dbdaSDaniel P. Berrange         trace_vnc_auth_start(vs, vs->auth);
29137e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
29147e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
29153e230dd2SCorentin Chary             vnc_flush(vs);
29167364dbdaSDaniel P. Berrange             trace_vnc_auth_pass(vs, vs->auth);
29173e230dd2SCorentin Chary             start_client_init(vs);
29187e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
29193e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
29207e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
29213e230dd2SCorentin Chary             vnc_flush(vs);
29223e230dd2SCorentin Chary             start_auth_vnc(vs);
29233e230dd2SCorentin Chary        } else {
29247364dbdaSDaniel P. Berrange             trace_vnc_auth_fail(vs, vs->auth,
29257364dbdaSDaniel P. Berrange                                 "Unsupported auth method for v3.3", "");
29263e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
29273e230dd2SCorentin Chary             vnc_flush(vs);
29283e230dd2SCorentin Chary             vnc_client_error(vs);
29293e230dd2SCorentin Chary        }
29303e230dd2SCorentin Chary     } else {
29313e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
29327e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
29333e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
29343e230dd2SCorentin Chary         vnc_flush(vs);
29353e230dd2SCorentin Chary     }
29363e230dd2SCorentin Chary 
29373e230dd2SCorentin Chary     return 0;
29383e230dd2SCorentin Chary }
29393e230dd2SCorentin Chary 
2940999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2941999342a0SCorentin Chary {
2942999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2943999342a0SCorentin Chary 
2944999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2945999342a0SCorentin Chary }
2946999342a0SCorentin Chary 
29477d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
29487d964c9dSCorentin Chary {
29497d964c9dSCorentin Chary     int i, j;
29507d964c9dSCorentin Chary 
29517d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
29527d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
29537d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
29547d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
29557d964c9dSCorentin Chary 
2956207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2957207f328aSCorentin Chary         for (i = x; i <= w; i++) {
29587d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
29597d964c9dSCorentin Chary         }
29607d964c9dSCorentin Chary     }
29617d964c9dSCorentin Chary }
29627d964c9dSCorentin Chary 
29637d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
29647d964c9dSCorentin Chary {
29657d964c9dSCorentin Chary     VncState *vs;
29667d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
29677d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
29687d964c9dSCorentin Chary     int has_dirty = 0;
29697d964c9dSCorentin Chary 
29705a3804dbSMarc-André Lureau     y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
29715a3804dbSMarc-André Lureau     x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
29727d964c9dSCorentin Chary 
29737d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2974bc2429b9SCorentin Chary         int j;
29757d964c9dSCorentin Chary 
29767d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
29777d964c9dSCorentin Chary         if (vs->output.offset) {
29787d964c9dSCorentin Chary             continue;
29797d964c9dSCorentin Chary         }
29807d964c9dSCorentin Chary 
29817d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
29827d964c9dSCorentin Chary             continue;
29837d964c9dSCorentin Chary         }
2984207f328aSCorentin Chary 
29857d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
29867d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2987b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2988b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2989b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
29907d964c9dSCorentin Chary         }
29917d964c9dSCorentin Chary         has_dirty++;
29927d964c9dSCorentin Chary     }
2993207f328aSCorentin Chary 
29947d964c9dSCorentin Chary     return has_dirty;
29957d964c9dSCorentin Chary }
29967d964c9dSCorentin Chary 
29977d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2998999342a0SCorentin Chary {
2999eebe0b79SGerd Hoffmann     int width = MIN(pixman_image_get_width(vd->guest.fb),
3000eebe0b79SGerd Hoffmann                     pixman_image_get_width(vd->server));
3001eebe0b79SGerd Hoffmann     int height = MIN(pixman_image_get_height(vd->guest.fb),
3002eebe0b79SGerd Hoffmann                      pixman_image_get_height(vd->server));
3003999342a0SCorentin Chary     int x, y;
3004999342a0SCorentin Chary     struct timeval res;
30057d964c9dSCorentin Chary     int has_dirty = 0;
3006999342a0SCorentin Chary 
30079f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
30089f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
3009999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
3010999342a0SCorentin Chary 
3011999342a0SCorentin Chary             rect->updated = false;
3012999342a0SCorentin Chary         }
3013999342a0SCorentin Chary     }
3014999342a0SCorentin Chary 
3015ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
3016999342a0SCorentin Chary 
3017999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
30187d964c9dSCorentin Chary         return has_dirty;
3019999342a0SCorentin Chary     }
3020999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
3021999342a0SCorentin Chary 
30229f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
30239f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
3024999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
3025999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
3026999342a0SCorentin Chary             struct timeval min, max;
3027999342a0SCorentin Chary 
3028999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
3029999342a0SCorentin Chary                 continue ;
3030999342a0SCorentin Chary             }
3031999342a0SCorentin Chary 
3032999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
3033ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
3034999342a0SCorentin Chary 
3035999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
3036999342a0SCorentin Chary                 rect->freq = 0;
30377d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
3038999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
3039999342a0SCorentin Chary                 continue ;
3040999342a0SCorentin Chary             }
3041999342a0SCorentin Chary 
3042999342a0SCorentin Chary             min = rect->times[rect->idx];
3043999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
3044ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
3045999342a0SCorentin Chary 
3046999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
3047999342a0SCorentin Chary             rect->freq /= count;
3048999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
3049999342a0SCorentin Chary         }
3050999342a0SCorentin Chary     }
30517d964c9dSCorentin Chary     return has_dirty;
3052999342a0SCorentin Chary }
3053999342a0SCorentin Chary 
3054999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
3055999342a0SCorentin Chary {
3056999342a0SCorentin Chary     int i, j;
3057999342a0SCorentin Chary     double total = 0;
3058999342a0SCorentin Chary     int num = 0;
3059999342a0SCorentin Chary 
30605a3804dbSMarc-André Lureau     x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
30615a3804dbSMarc-André Lureau     y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
3062999342a0SCorentin Chary 
3063999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
3064999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
3065999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
3066999342a0SCorentin Chary             num++;
3067999342a0SCorentin Chary         }
3068999342a0SCorentin Chary     }
3069999342a0SCorentin Chary 
3070999342a0SCorentin Chary     if (num) {
3071999342a0SCorentin Chary         return total / num;
3072999342a0SCorentin Chary     } else {
3073999342a0SCorentin Chary         return 0;
3074999342a0SCorentin Chary     }
3075999342a0SCorentin Chary }
3076999342a0SCorentin Chary 
3077999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
3078999342a0SCorentin Chary {
3079999342a0SCorentin Chary     VncRectStat *rect;
3080999342a0SCorentin Chary 
3081999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
3082999342a0SCorentin Chary     if (rect->updated) {
3083999342a0SCorentin Chary         return ;
3084999342a0SCorentin Chary     }
3085999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
3086999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3087999342a0SCorentin Chary     rect->updated = true;
3088999342a0SCorentin Chary }
3089999342a0SCorentin Chary 
30903e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
30913e230dd2SCorentin Chary {
3092bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
3093bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
3094bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
3095bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
3096eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
309712b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
30983e230dd2SCorentin Chary     VncState *vs;
30993e230dd2SCorentin Chary     int has_dirty = 0;
31009f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
3101*6c08964bSWen, Jianxian     unsigned long offset;
3102*6c08964bSWen, Jianxian     int x;
3103*6c08964bSWen, Jianxian     uint8_t *guest_ptr, *server_ptr;
31043e230dd2SCorentin Chary 
310580e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
3106999342a0SCorentin Chary 
310780e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
3108999342a0SCorentin Chary         gettimeofday(&tv, NULL);
31097d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
311080e0c8c3SCorentin Chary     }
3111999342a0SCorentin Chary 
3112*6c08964bSWen, Jianxian     offset = find_next_bit((unsigned long *) &vd->guest.dirty,
3113*6c08964bSWen, Jianxian                            height * VNC_DIRTY_BPL(&vd->guest), 0);
3114*6c08964bSWen, Jianxian     if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
3115*6c08964bSWen, Jianxian         /* no dirty bits in guest surface */
3116*6c08964bSWen, Jianxian         return has_dirty;
3117*6c08964bSWen, Jianxian     }
3118*6c08964bSWen, Jianxian 
31193e230dd2SCorentin Chary     /*
31203e230dd2SCorentin Chary      * Walk through the guest dirty map.
31213e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
31223e230dd2SCorentin Chary      * Update server dirty map.
31233e230dd2SCorentin Chary      */
3124bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3125eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
3126eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
3127bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3128bea60dd7SPeter Lieven                     server_stride);
31299f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
31309f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
31319f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
313212b316d4SPeter Lieven     } else {
3133eb8934b0SGerd Hoffmann         int guest_bpp =
3134eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
313512b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
313612b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
3137949ed4c2SPhilippe Mathieu-Daudé         guest_ll = pixman_image_get_width(vd->guest.fb)
3138949ed4c2SPhilippe Mathieu-Daudé                    * DIV_ROUND_UP(guest_bpp, 8);
31399f64916dSGerd Hoffmann     }
3140eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
314112b316d4SPeter Lieven 
314212b316d4SPeter Lieven     for (;;) {
314312b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
314412b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
314512b316d4SPeter Lieven 
314612b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
31473e230dd2SCorentin Chary 
31489f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3149bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
31509f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
31519f64916dSGerd Hoffmann         } else {
315212b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
31539f64916dSGerd Hoffmann         }
315412b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
31553e230dd2SCorentin Chary 
315612b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
315712b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3158bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
315912b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
31603e230dd2SCorentin Chary                 continue;
3161b4c85ddcSPeter Lieven             }
3162eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
3163eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
3164bea60dd7SPeter Lieven             }
3165eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
3166bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
31673e230dd2SCorentin Chary                 continue;
3168b4c85ddcSPeter Lieven             }
3169bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
317012b316d4SPeter Lieven             if (!vd->non_adaptive) {
317112b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
317212b316d4SPeter Lieven                                  y, &tv);
317312b316d4SPeter Lieven             }
31743e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
317512b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
31763e230dd2SCorentin Chary             }
31773e230dd2SCorentin Chary             has_dirty++;
31783e230dd2SCorentin Chary         }
317912b316d4SPeter Lieven 
318012b316d4SPeter Lieven         y++;
3181*6c08964bSWen, Jianxian         offset = find_next_bit((unsigned long *) &vd->guest.dirty,
3182*6c08964bSWen, Jianxian                                height * VNC_DIRTY_BPL(&vd->guest),
3183*6c08964bSWen, Jianxian                                y * VNC_DIRTY_BPL(&vd->guest));
3184*6c08964bSWen, Jianxian         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
3185*6c08964bSWen, Jianxian             /* no more dirty bits */
3186*6c08964bSWen, Jianxian             break;
3187*6c08964bSWen, Jianxian         }
31883e230dd2SCorentin Chary     }
31899f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
31903e230dd2SCorentin Chary     return has_dirty;
31913e230dd2SCorentin Chary }
31923e230dd2SCorentin Chary 
31930f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
31943e230dd2SCorentin Chary {
31950f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
31963e230dd2SCorentin Chary     VncState *vs, *vn;
31973e230dd2SCorentin Chary     int has_dirty, rects = 0;
31983e230dd2SCorentin Chary 
31999d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
32009d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
32019d6b2070SChenLiang         return;
32029d6b2070SChenLiang     }
32039d6b2070SChenLiang 
32041d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
32053e230dd2SCorentin Chary 
3206bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
32070f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3208bd023f95SCorentin Chary         return;
3209bd023f95SCorentin Chary     }
3210bd023f95SCorentin Chary 
32113e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
3212bd023f95SCorentin Chary     vnc_unlock_display(vd);
32133e230dd2SCorentin Chary 
32143e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
32156af998dbSDaniel P. Berrange         rects += vnc_update_client(vs, has_dirty);
32163e230dd2SCorentin Chary         /* vs might be free()ed here */
32173e230dd2SCorentin Chary     }
3218bd023f95SCorentin Chary 
32193e230dd2SCorentin Chary     if (has_dirty && rects) {
32200f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
32210f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
32220f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
32230f7b2864SGerd Hoffmann         }
32243e230dd2SCorentin Chary     } else {
32250f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
32260f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
32270f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
32283e230dd2SCorentin Chary         }
32293e230dd2SCorentin Chary     }
32303e230dd2SCorentin Chary }
32313e230dd2SCorentin Chary 
323204d2529dSDaniel P. Berrange static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
32332c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
32343e230dd2SCorentin Chary {
3235fedf0d35SMarkus Armbruster     VncState *vs = g_new0(VncState, 1);
323690cd03a3SDaniel P. Berrange     bool first_client = QTAILQ_EMPTY(&vd->clients);
32377d964c9dSCorentin Chary     int i;
32387d964c9dSCorentin Chary 
3239ad6374c4SDaniel P. Berrange     trace_vnc_client_connect(vs, sioc);
32406bf21f3dSLi Qiang     vs->zrle = g_new0(VncZrle, 1);
32416bf21f3dSLi Qiang     vs->tight = g_new0(VncTight, 1);
3242f31f9c10SGerd Hoffmann     vs->magic = VNC_MAGIC;
324304d2529dSDaniel P. Berrange     vs->sioc = sioc;
324404d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->sioc));
324504d2529dSDaniel P. Berrange     vs->ioc = QIO_CHANNEL(sioc);
324604d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->ioc));
3247d616ccc5SGerd Hoffmann     vs->vd = vd;
32487e7e2ebcSDaniel P. Berrange 
324904d2529dSDaniel P. Berrange     buffer_init(&vs->input,          "vnc-input/%p", sioc);
325004d2529dSDaniel P. Berrange     buffer_init(&vs->output,         "vnc-output/%p", sioc);
325104d2529dSDaniel P. Berrange     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3252543b9580SGerd Hoffmann 
32536bf21f3dSLi Qiang     buffer_init(&vs->tight->tight,    "vnc-tight/%p", sioc);
32546bf21f3dSLi Qiang     buffer_init(&vs->tight->zlib,     "vnc-tight-zlib/%p", sioc);
32556bf21f3dSLi Qiang     buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3256543b9580SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
32576bf21f3dSLi Qiang     buffer_init(&vs->tight->jpeg,     "vnc-tight-jpeg/%p", sioc);
3258543b9580SGerd Hoffmann #endif
3259543b9580SGerd Hoffmann #ifdef CONFIG_VNC_PNG
32606bf21f3dSLi Qiang     buffer_init(&vs->tight->png,      "vnc-tight-png/%p", sioc);
3261543b9580SGerd Hoffmann #endif
326204d2529dSDaniel P. Berrange     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
32636bf21f3dSLi Qiang     buffer_init(&vs->zrle->zrle,      "vnc-zrle/%p", sioc);
32646bf21f3dSLi Qiang     buffer_init(&vs->zrle->fb,        "vnc-zrle-fb/%p", sioc);
32656bf21f3dSLi Qiang     buffer_init(&vs->zrle->zlib,      "vnc-zrle-zlib/%p", sioc);
3266543b9580SGerd Hoffmann 
32677e7e2ebcSDaniel P. Berrange     if (skipauth) {
32687e7e2ebcSDaniel P. Berrange         vs->auth = VNC_AUTH_NONE;
32697e7e2ebcSDaniel P. Berrange         vs->subauth = VNC_AUTH_INVALID;
32707e7e2ebcSDaniel P. Berrange     } else {
3271f9148c8aSDaniel P. Berrange         if (websocket) {
3272f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
3273f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
3274f9148c8aSDaniel P. Berrange         } else {
32757e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
32767e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
32777e7e2ebcSDaniel P. Berrange         }
3278f9148c8aSDaniel P. Berrange     }
327904d2529dSDaniel P. Berrange     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
328004d2529dSDaniel P. Berrange               sioc, websocket, vs->auth, vs->subauth);
32817e7e2ebcSDaniel P. Berrange 
32827267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
32837d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3284fedf0d35SMarkus Armbruster         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
32857d964c9dSCorentin Chary     }
32863e230dd2SCorentin Chary 
328704d2529dSDaniel P. Berrange     VNC_DEBUG("New client on socket %p\n", vs->sioc);
32880f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
328904d2529dSDaniel P. Berrange     qio_channel_set_blocking(vs->ioc, false, NULL);
3290a75d6f07SBrandon Carpenter     if (vs->ioc_tag) {
3291a75d6f07SBrandon Carpenter         g_source_remove(vs->ioc_tag);
3292a75d6f07SBrandon Carpenter     }
32937536ee4bSTim Hardeck     if (websocket) {
32947536ee4bSTim Hardeck         vs->websocket = 1;
329538e5756aSDaniel P. Berrange         if (vd->tlscreds) {
329604d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
32972ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32982ddafce7SDing Hui                 vncws_tls_handshake_io, vs, NULL);
32993e305e4aSDaniel P. Berrange         } else {
330004d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
33012ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
33022ddafce7SDing Hui                 vncws_handshake_io, vs, NULL);
33030057a0d5STim Hardeck         }
330404d2529dSDaniel P. Berrange     } else {
330504d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
33062ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
33072ddafce7SDing Hui             vnc_client_io, vs, NULL);
33087536ee4bSTim Hardeck     }
33093e230dd2SCorentin Chary 
33103e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3311fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
33128cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
33133e230dd2SCorentin Chary 
33143e230dd2SCorentin Chary     vs->last_x = -1;
33153e230dd2SCorentin Chary     vs->last_y = -1;
33163e230dd2SCorentin Chary 
33173e230dd2SCorentin Chary     vs->as.freq = 44100;
33183e230dd2SCorentin Chary     vs->as.nchannels = 2;
331985bc5852SKővágó, Zoltán     vs->as.fmt = AUDIO_FORMAT_S16;
33203e230dd2SCorentin Chary     vs->as.endianness = 0;
33213e230dd2SCorentin Chary 
3322bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3323175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3324bd023f95SCorentin Chary 
3325e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3326c7628bffSGerd Hoffmann     if (first_client) {
3327c7628bffSGerd Hoffmann         vnc_update_server_surface(vd);
3328c7628bffSGerd Hoffmann     }
33293e230dd2SCorentin Chary 
33301d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
33313e230dd2SCorentin Chary 
333290cd03a3SDaniel P. Berrange     if (!vs->websocket) {
3333dbee9897SDaniel P. Berrange         vnc_start_protocol(vs);
333490cd03a3SDaniel P. Berrange     }
333590cd03a3SDaniel P. Berrange 
333690cd03a3SDaniel P. Berrange     if (vd->num_connecting > vd->connections_limit) {
333790cd03a3SDaniel P. Berrange         QTAILQ_FOREACH(vs, &vd->clients, next) {
333890cd03a3SDaniel P. Berrange             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
333990cd03a3SDaniel P. Berrange                 vnc_disconnect_start(vs);
334090cd03a3SDaniel P. Berrange                 return;
334190cd03a3SDaniel P. Berrange             }
334290cd03a3SDaniel P. Berrange         }
334390cd03a3SDaniel P. Berrange     }
334490cd03a3SDaniel P. Berrange }
334590cd03a3SDaniel P. Berrange 
3346dbee9897SDaniel P. Berrange void vnc_start_protocol(VncState *vs)
334790cd03a3SDaniel P. Berrange {
33483e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
33493e230dd2SCorentin Chary     vnc_flush(vs);
33503e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
33513e230dd2SCorentin Chary 
33523e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
33533e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
33543e230dd2SCorentin Chary }
33553e230dd2SCorentin Chary 
335613e1d0e7SDaniel P. Berrange static void vnc_listen_io(QIONetListener *listener,
335713e1d0e7SDaniel P. Berrange                           QIOChannelSocket *cioc,
335804d2529dSDaniel P. Berrange                           void *opaque)
33593e230dd2SCorentin Chary {
3360bf01c179SDaniel P. Berrange     VncDisplay *vd = opaque;
336113e1d0e7SDaniel P. Berrange     bool isWebsock = listener == vd->wslistener;
33624ee74fa7SDaniel P. Berrange 
336313e1d0e7SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(cioc),
33644ee74fa7SDaniel P. Berrange                          isWebsock ? "vnc-ws-server" : "vnc-server");
336513e1d0e7SDaniel P. Berrange     qio_channel_set_delay(QIO_CHANNEL(cioc), false);
336613e1d0e7SDaniel P. Berrange     vnc_connect(vd, cioc, false, isWebsock);
33677536ee4bSTim Hardeck }
33687536ee4bSTim Hardeck 
33697c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
33707c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
33710f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
33727c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3373c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
337434da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
33757c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
33767c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
33777c20b4a3SGerd Hoffmann };
33787c20b4a3SGerd Hoffmann 
3379ab4f931eSFei Li void vnc_display_init(const char *id, Error **errp)
33803e230dd2SCorentin Chary {
3381bf01c179SDaniel P. Berrange     VncDisplay *vd;
33824db14629SGerd Hoffmann 
33834db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
33844db14629SGerd Hoffmann         return;
33854db14629SGerd Hoffmann     }
3386bf01c179SDaniel P. Berrange     vd = g_malloc0(sizeof(*vd));
33873e230dd2SCorentin Chary 
3388bf01c179SDaniel P. Berrange     vd->id = strdup(id);
3389bf01c179SDaniel P. Berrange     QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
33903e230dd2SCorentin Chary 
3391bf01c179SDaniel P. Berrange     QTAILQ_INIT(&vd->clients);
3392bf01c179SDaniel P. Berrange     vd->expires = TIME_MAX;
33933e230dd2SCorentin Chary 
339440066175SGerd Hoffmann     if (keyboard_layout) {
339540066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
3396ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym,
3397ab4f931eSFei Li                                               keyboard_layout, errp);
339840066175SGerd Hoffmann     } else {
3399ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
340040066175SGerd Hoffmann     }
34013e230dd2SCorentin Chary 
3402bf01c179SDaniel P. Berrange     if (!vd->kbd_layout) {
3403ab4f931eSFei Li         return;
3404bf01c179SDaniel P. Berrange     }
34053e230dd2SCorentin Chary 
3406bf01c179SDaniel P. Berrange     vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3407bf01c179SDaniel P. Berrange     vd->connections_limit = 32;
340812e29b16SDaniel P. Berrange 
3409bf01c179SDaniel P. Berrange     qemu_mutex_init(&vd->mutex);
3410bd023f95SCorentin Chary     vnc_start_worker_thread();
3411bd023f95SCorentin Chary 
3412bf01c179SDaniel P. Berrange     vd->dcl.ops = &dcl_ops;
3413bf01c179SDaniel P. Berrange     register_displaychangelistener(&vd->dcl);
3414c2f2ba49SGerd Hoffmann     vd->kbd = qkbd_state_init(vd->dcl.con);
34153e230dd2SCorentin Chary }
34163e230dd2SCorentin Chary 
34173e230dd2SCorentin Chary 
3418bf01c179SDaniel P. Berrange static void vnc_display_close(VncDisplay *vd)
34193e230dd2SCorentin Chary {
3420bf01c179SDaniel P. Berrange     if (!vd) {
34213e230dd2SCorentin Chary         return;
342204d2529dSDaniel P. Berrange     }
3423bf01c179SDaniel P. Berrange     vd->is_unix = false;
34244ee74fa7SDaniel P. Berrange 
342513e1d0e7SDaniel P. Berrange     if (vd->listener) {
342613e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->listener);
342713e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->listener));
342804d2529dSDaniel P. Berrange     }
342913e1d0e7SDaniel P. Berrange     vd->listener = NULL;
343013e1d0e7SDaniel P. Berrange 
343113e1d0e7SDaniel P. Berrange     if (vd->wslistener) {
343213e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->wslistener);
343313e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->wslistener));
34347536ee4bSTim Hardeck     }
343513e1d0e7SDaniel P. Berrange     vd->wslistener = NULL;
34364ee74fa7SDaniel P. Berrange 
3437bf01c179SDaniel P. Berrange     vd->auth = VNC_AUTH_INVALID;
3438bf01c179SDaniel P. Berrange     vd->subauth = VNC_AUTH_INVALID;
3439bf01c179SDaniel P. Berrange     if (vd->tlscreds) {
3440521534dfSZihao Chang         object_unref(OBJECT(vd->tlscreds));
3441bf01c179SDaniel P. Berrange         vd->tlscreds = NULL;
3442bf01c179SDaniel P. Berrange     }
3443b76806d4SDaniel P. Berrange     if (vd->tlsauthz) {
3444b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->tlsauthz));
3445b76806d4SDaniel P. Berrange         vd->tlsauthz = NULL;
3446b76806d4SDaniel P. Berrange     }
3447b76806d4SDaniel P. Berrange     g_free(vd->tlsauthzid);
3448b76806d4SDaniel P. Berrange     vd->tlsauthzid = NULL;
3449a54f0d2bSPierre Ossman     if (vd->lock_key_sync) {
3450a54f0d2bSPierre Ossman         qemu_remove_led_event_handler(vd->led);
34512dc120beSGerd Hoffmann         vd->led = NULL;
3452a54f0d2bSPierre Ossman     }
3453b76806d4SDaniel P. Berrange #ifdef CONFIG_VNC_SASL
3454b76806d4SDaniel P. Berrange     if (vd->sasl.authz) {
3455b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->sasl.authz));
3456b76806d4SDaniel P. Berrange         vd->sasl.authz = NULL;
3457b76806d4SDaniel P. Berrange     }
3458b76806d4SDaniel P. Berrange     g_free(vd->sasl.authzid);
3459b76806d4SDaniel P. Berrange     vd->sasl.authzid = NULL;
3460b76806d4SDaniel P. Berrange #endif
34613e230dd2SCorentin Chary }
34623e230dd2SCorentin Chary 
346314f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
34641cd20f8bSAnthony Liguori {
3465bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
34661cd20f8bSAnthony Liguori 
3467bf01c179SDaniel P. Berrange     if (!vd) {
3468a6aa9d3eSLuiz Capitulino         return -EINVAL;
34691cd20f8bSAnthony Liguori     }
3470bf01c179SDaniel P. Berrange     if (vd->auth == VNC_AUTH_NONE) {
3471cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
34727ea7d36eSMarkus Armbruster                                 "password auth using '-vnc ${dpy},password'.\n");
3473cf864569SGerd Hoffmann         return -EINVAL;
34741cd20f8bSAnthony Liguori     }
34751cd20f8bSAnthony Liguori 
3476bf01c179SDaniel P. Berrange     g_free(vd->password);
3477bf01c179SDaniel P. Berrange     vd->password = g_strdup(password);
3478a6aa9d3eSLuiz Capitulino 
3479a6aa9d3eSLuiz Capitulino     return 0;
34803e230dd2SCorentin Chary }
34813e230dd2SCorentin Chary 
348214f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
34833c9405a0SGerd Hoffmann {
3484bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
34853c9405a0SGerd Hoffmann 
3486bf01c179SDaniel P. Berrange     if (!vd) {
34871643f2b2SGerd Hoffmann         return -EINVAL;
34881643f2b2SGerd Hoffmann     }
34891643f2b2SGerd Hoffmann 
3490bf01c179SDaniel P. Berrange     vd->expires = expires;
34913c9405a0SGerd Hoffmann     return 0;
34923c9405a0SGerd Hoffmann }
34933c9405a0SGerd Hoffmann 
3494bf01c179SDaniel P. Berrange static void vnc_display_print_local_addr(VncDisplay *vd)
34953e230dd2SCorentin Chary {
3496bd269ebcSMarkus Armbruster     SocketAddress *addr;
34973e230dd2SCorentin Chary 
349813e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
34994ee74fa7SDaniel P. Berrange         return;
35004ee74fa7SDaniel P. Berrange     }
35014ee74fa7SDaniel P. Berrange 
3502b94b3c02SMarkus Armbruster     addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
350304d2529dSDaniel P. Berrange     if (!addr) {
350433df7bf3SPaolo Bonzini         return;
350504d2529dSDaniel P. Berrange     }
350604d2529dSDaniel P. Berrange 
3507bd269ebcSMarkus Armbruster     if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3508bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
350933df7bf3SPaolo Bonzini         return;
351004d2529dSDaniel P. Berrange     }
351133df7bf3SPaolo Bonzini     error_printf_unless_qmp("VNC server running on %s:%s\n",
3512bd269ebcSMarkus Armbruster                             addr->u.inet.host,
3513bd269ebcSMarkus Armbruster                             addr->u.inet.port);
3514bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
35153e230dd2SCorentin Chary }
35163e230dd2SCorentin Chary 
35174db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
35184db14629SGerd Hoffmann     .name = "vnc",
35194db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
35204db14629SGerd Hoffmann     .implied_opt_name = "vnc",
35214db14629SGerd Hoffmann     .desc = {
35224db14629SGerd Hoffmann         {
35234db14629SGerd Hoffmann             .name = "vnc",
35244db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
35254db14629SGerd Hoffmann         },{
35264db14629SGerd Hoffmann             .name = "websocket",
35274db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
35284db14629SGerd Hoffmann         },{
35293e305e4aSDaniel P. Berrange             .name = "tls-creds",
35303e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
35313e305e4aSDaniel P. Berrange         },{
35324db14629SGerd Hoffmann             .name = "share",
35334db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
35344db14629SGerd Hoffmann         },{
35351d0d59feSGerd Hoffmann             .name = "display",
35361d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
35371d0d59feSGerd Hoffmann         },{
35381d0d59feSGerd Hoffmann             .name = "head",
35391d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
35401d0d59feSGerd Hoffmann         },{
3541e5f34cddSGerd Hoffmann             .name = "connections",
3542e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3543e5f34cddSGerd Hoffmann         },{
354488428b7aSGonglei             .name = "to",
354588428b7aSGonglei             .type = QEMU_OPT_NUMBER,
354688428b7aSGonglei         },{
354788428b7aSGonglei             .name = "ipv4",
354888428b7aSGonglei             .type = QEMU_OPT_BOOL,
354988428b7aSGonglei         },{
355088428b7aSGonglei             .name = "ipv6",
355188428b7aSGonglei             .type = QEMU_OPT_BOOL,
355288428b7aSGonglei         },{
35534db14629SGerd Hoffmann             .name = "password",
35544db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35554db14629SGerd Hoffmann         },{
35566c6840e9SDaniel P. Berrangé             .name = "password-secret",
35576c6840e9SDaniel P. Berrangé             .type = QEMU_OPT_STRING,
35586c6840e9SDaniel P. Berrangé         },{
35594db14629SGerd Hoffmann             .name = "reverse",
35604db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35614db14629SGerd Hoffmann         },{
35624db14629SGerd Hoffmann             .name = "lock-key-sync",
35634db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35644db14629SGerd Hoffmann         },{
3565c5ce8333SGerd Hoffmann             .name = "key-delay-ms",
3566c5ce8333SGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3567c5ce8333SGerd Hoffmann         },{
35684db14629SGerd Hoffmann             .name = "sasl",
35694db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35704db14629SGerd Hoffmann         },{
357155cf09a0SDaniel P. Berrange             .name = "tls-authz",
357255cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
357355cf09a0SDaniel P. Berrange         },{
357455cf09a0SDaniel P. Berrange             .name = "sasl-authz",
357555cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
357655cf09a0SDaniel P. Berrange         },{
35774db14629SGerd Hoffmann             .name = "lossy",
35784db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35794db14629SGerd Hoffmann         },{
35804db14629SGerd Hoffmann             .name = "non-adaptive",
35814db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
3582f0b9f36dSKővágó, Zoltán         },{
3583f0b9f36dSKővágó, Zoltán             .name = "audiodev",
3584f0b9f36dSKővágó, Zoltán             .type = QEMU_OPT_STRING,
35857b5fa0b5SDaniel P. Berrangé         },{
35867b5fa0b5SDaniel P. Berrangé             .name = "power-control",
35877b5fa0b5SDaniel P. Berrangé             .type = QEMU_OPT_BOOL,
35884db14629SGerd Hoffmann         },
35894db14629SGerd Hoffmann         { /* end of list */ }
35904db14629SGerd Hoffmann     },
35914db14629SGerd Hoffmann };
35924db14629SGerd Hoffmann 
35930dd72e15SDaniel P. Berrange 
35943e305e4aSDaniel P. Berrange static int
3595eda24e18SDaniel P. Berrange vnc_display_setup_auth(int *auth,
3596eda24e18SDaniel P. Berrange                        int *subauth,
3597eda24e18SDaniel P. Berrange                        QCryptoTLSCreds *tlscreds,
35980dd72e15SDaniel P. Berrange                        bool password,
35990dd72e15SDaniel P. Berrange                        bool sasl,
36003e305e4aSDaniel P. Berrange                        bool websocket,
36013e305e4aSDaniel P. Berrange                        Error **errp)
36020dd72e15SDaniel P. Berrange {
36030dd72e15SDaniel P. Berrange     /*
36040dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
36050dd72e15SDaniel P. Berrange      *
36060dd72e15SDaniel P. Berrange      *   1. none
36070dd72e15SDaniel P. Berrange      *   2. vnc
36080dd72e15SDaniel P. Berrange      *   3. sasl
36090dd72e15SDaniel P. Berrange      *
36100dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
36110dd72e15SDaniel P. Berrange      *
36120dd72e15SDaniel P. Berrange      *   1. clear
36130dd72e15SDaniel P. Berrange      *   2. tls
36140dd72e15SDaniel P. Berrange      *
36150dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
36160dd72e15SDaniel P. Berrange      *
36170dd72e15SDaniel P. Berrange      *   1. anon
36180dd72e15SDaniel P. Berrange      *   2. x509
36190dd72e15SDaniel P. Berrange      *
36200dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
36210dd72e15SDaniel P. Berrange      *
36220dd72e15SDaniel P. Berrange      *   1. clear + none
36230dd72e15SDaniel P. Berrange      *   2. clear + vnc
36240dd72e15SDaniel P. Berrange      *   3. clear + sasl
36250dd72e15SDaniel P. Berrange      *   4. tls + anon + none
36260dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
36270dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
36280dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
36290dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
36300dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
36310dd72e15SDaniel P. Berrange      *
36320dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
36330dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
36340dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
36350dd72e15SDaniel P. Berrange      * sub-auth types.
3636f9148c8aSDaniel P. Berrange      *
3637f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3638f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3639f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3640f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3641f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3642f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3643f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3644f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3645f9148c8aSDaniel P. Berrange      *
3646f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3647f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3648f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
36490dd72e15SDaniel P. Berrange      */
3650eda24e18SDaniel P. Berrange     if (websocket || !tlscreds) {
36510dd72e15SDaniel P. Berrange         if (password) {
36520dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
3653eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_VNC;
36540dd72e15SDaniel P. Berrange         } else if (sasl) {
36550dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3656eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_SASL;
36570dd72e15SDaniel P. Berrange         } else {
36580dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
3659eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_NONE;
36600dd72e15SDaniel P. Berrange         }
3661eda24e18SDaniel P. Berrange         *subauth = VNC_AUTH_INVALID;
3662f9148c8aSDaniel P. Berrange     } else {
3663eda24e18SDaniel P. Berrange         bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3664eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3665eda24e18SDaniel P. Berrange         bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3666eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3667eda24e18SDaniel P. Berrange 
3668eda24e18SDaniel P. Berrange         if (!is_x509 && !is_anon) {
3669eda24e18SDaniel P. Berrange             error_setg(errp,
3670eda24e18SDaniel P. Berrange                        "Unsupported TLS cred type %s",
3671eda24e18SDaniel P. Berrange                        object_get_typename(OBJECT(tlscreds)));
3672eda24e18SDaniel P. Berrange             return -1;
3673eda24e18SDaniel P. Berrange         }
3674eda24e18SDaniel P. Berrange         *auth = VNC_AUTH_VENCRYPT;
3675eda24e18SDaniel P. Berrange         if (password) {
3676eda24e18SDaniel P. Berrange             if (is_x509) {
3677eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3678eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3679eda24e18SDaniel P. Berrange             } else {
3680eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3681eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3682eda24e18SDaniel P. Berrange             }
3683eda24e18SDaniel P. Berrange 
3684eda24e18SDaniel P. Berrange         } else if (sasl) {
3685eda24e18SDaniel P. Berrange             if (is_x509) {
3686eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3687eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3688eda24e18SDaniel P. Berrange             } else {
3689eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3690eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3691eda24e18SDaniel P. Berrange             }
3692eda24e18SDaniel P. Berrange         } else {
3693eda24e18SDaniel P. Berrange             if (is_x509) {
3694eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3695eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3696eda24e18SDaniel P. Berrange             } else {
3697eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3698eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3699eda24e18SDaniel P. Berrange             }
3700f9148c8aSDaniel P. Berrange         }
37010dd72e15SDaniel P. Berrange     }
37023e305e4aSDaniel P. Berrange     return 0;
37030dd72e15SDaniel P. Berrange }
37040dd72e15SDaniel P. Berrange 
37053e305e4aSDaniel P. Berrange 
3706275e0d61SDaniel P. Berrange static int vnc_display_get_address(const char *addrstr,
3707275e0d61SDaniel P. Berrange                                    bool websocket,
3708e5766eb4SGerd Hoffmann                                    bool reverse,
3709275e0d61SDaniel P. Berrange                                    int displaynum,
3710275e0d61SDaniel P. Berrange                                    int to,
3711275e0d61SDaniel P. Berrange                                    bool has_ipv4,
3712275e0d61SDaniel P. Berrange                                    bool has_ipv6,
3713275e0d61SDaniel P. Berrange                                    bool ipv4,
3714275e0d61SDaniel P. Berrange                                    bool ipv6,
3715bd269ebcSMarkus Armbruster                                    SocketAddress **retaddr,
3716275e0d61SDaniel P. Berrange                                    Error **errp)
3717275e0d61SDaniel P. Berrange {
3718275e0d61SDaniel P. Berrange     int ret = -1;
3719bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3720275e0d61SDaniel P. Berrange 
3721bd269ebcSMarkus Armbruster     addr = g_new0(SocketAddress, 1);
3722275e0d61SDaniel P. Berrange 
3723275e0d61SDaniel P. Berrange     if (strncmp(addrstr, "unix:", 5) == 0) {
3724bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3725bd269ebcSMarkus Armbruster         addr->u.q_unix.path = g_strdup(addrstr + 5);
3726275e0d61SDaniel P. Berrange 
3727275e0d61SDaniel P. Berrange         if (websocket) {
3728275e0d61SDaniel P. Berrange             error_setg(errp, "UNIX sockets not supported with websock");
3729275e0d61SDaniel P. Berrange             goto cleanup;
3730275e0d61SDaniel P. Berrange         }
3731275e0d61SDaniel P. Berrange 
3732275e0d61SDaniel P. Berrange         if (to) {
3733275e0d61SDaniel P. Berrange             error_setg(errp, "Port range not support with UNIX socket");
3734275e0d61SDaniel P. Berrange             goto cleanup;
3735275e0d61SDaniel P. Berrange         }
3736275e0d61SDaniel P. Berrange         ret = 0;
3737275e0d61SDaniel P. Berrange     } else {
3738275e0d61SDaniel P. Berrange         const char *port;
3739275e0d61SDaniel P. Berrange         size_t hostlen;
3740275e0d61SDaniel P. Berrange         unsigned long long baseport = 0;
3741275e0d61SDaniel P. Berrange         InetSocketAddress *inet;
3742275e0d61SDaniel P. Berrange 
3743275e0d61SDaniel P. Berrange         port = strrchr(addrstr, ':');
3744275e0d61SDaniel P. Berrange         if (!port) {
3745275e0d61SDaniel P. Berrange             if (websocket) {
3746275e0d61SDaniel P. Berrange                 hostlen = 0;
3747275e0d61SDaniel P. Berrange                 port = addrstr;
3748275e0d61SDaniel P. Berrange             } else {
3749275e0d61SDaniel P. Berrange                 error_setg(errp, "no vnc port specified");
3750275e0d61SDaniel P. Berrange                 goto cleanup;
3751275e0d61SDaniel P. Berrange             }
3752275e0d61SDaniel P. Berrange         } else {
3753275e0d61SDaniel P. Berrange             hostlen = port - addrstr;
3754275e0d61SDaniel P. Berrange             port++;
3755275e0d61SDaniel P. Berrange             if (*port == '\0') {
3756275e0d61SDaniel P. Berrange                 error_setg(errp, "vnc port cannot be empty");
3757275e0d61SDaniel P. Berrange                 goto cleanup;
3758275e0d61SDaniel P. Berrange             }
3759275e0d61SDaniel P. Berrange         }
3760275e0d61SDaniel P. Berrange 
3761bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_INET;
3762bd269ebcSMarkus Armbruster         inet = &addr->u.inet;
3763275e0d61SDaniel P. Berrange         if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3764275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr + 1, hostlen - 2);
3765275e0d61SDaniel P. Berrange         } else {
3766275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr, hostlen);
3767275e0d61SDaniel P. Berrange         }
3768275e0d61SDaniel P. Berrange         /* plain VNC port is just an offset, for websocket
3769275e0d61SDaniel P. Berrange          * port is absolute */
3770275e0d61SDaniel P. Berrange         if (websocket) {
3771275e0d61SDaniel P. Berrange             if (g_str_equal(addrstr, "") ||
3772275e0d61SDaniel P. Berrange                 g_str_equal(addrstr, "on")) {
3773396f935aSDaniel P. Berrange                 if (displaynum == -1) {
3774396f935aSDaniel P. Berrange                     error_setg(errp, "explicit websocket port is required");
3775396f935aSDaniel P. Berrange                     goto cleanup;
3776396f935aSDaniel P. Berrange                 }
3777275e0d61SDaniel P. Berrange                 inet->port = g_strdup_printf(
3778275e0d61SDaniel P. Berrange                     "%d", displaynum + 5700);
3779275e0d61SDaniel P. Berrange                 if (to) {
3780275e0d61SDaniel P. Berrange                     inet->has_to = true;
3781275e0d61SDaniel P. Berrange                     inet->to = to + 5700;
3782275e0d61SDaniel P. Berrange                 }
3783275e0d61SDaniel P. Berrange             } else {
3784275e0d61SDaniel P. Berrange                 inet->port = g_strdup(port);
3785275e0d61SDaniel P. Berrange             }
3786275e0d61SDaniel P. Berrange         } else {
3787e5766eb4SGerd Hoffmann             int offset = reverse ? 0 : 5900;
3788275e0d61SDaniel P. Berrange             if (parse_uint_full(port, &baseport, 10) < 0) {
3789275e0d61SDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", port);
3790275e0d61SDaniel P. Berrange                 goto cleanup;
3791275e0d61SDaniel P. Berrange             }
3792275e0d61SDaniel P. Berrange             if (baseport > 65535 ||
3793e5766eb4SGerd Hoffmann                 baseport + offset > 65535) {
3794275e0d61SDaniel P. Berrange                 error_setg(errp, "port %s out of range", port);
3795275e0d61SDaniel P. Berrange                 goto cleanup;
3796275e0d61SDaniel P. Berrange             }
3797275e0d61SDaniel P. Berrange             inet->port = g_strdup_printf(
3798e5766eb4SGerd Hoffmann                 "%d", (int)baseport + offset);
3799275e0d61SDaniel P. Berrange 
3800275e0d61SDaniel P. Berrange             if (to) {
3801275e0d61SDaniel P. Berrange                 inet->has_to = true;
3802e5766eb4SGerd Hoffmann                 inet->to = to + offset;
3803275e0d61SDaniel P. Berrange             }
3804275e0d61SDaniel P. Berrange         }
3805275e0d61SDaniel P. Berrange 
3806275e0d61SDaniel P. Berrange         inet->ipv4 = ipv4;
3807275e0d61SDaniel P. Berrange         inet->has_ipv4 = has_ipv4;
3808275e0d61SDaniel P. Berrange         inet->ipv6 = ipv6;
3809275e0d61SDaniel P. Berrange         inet->has_ipv6 = has_ipv6;
3810275e0d61SDaniel P. Berrange 
3811275e0d61SDaniel P. Berrange         ret = baseport;
3812275e0d61SDaniel P. Berrange     }
3813275e0d61SDaniel P. Berrange 
3814275e0d61SDaniel P. Berrange     *retaddr = addr;
3815275e0d61SDaniel P. Berrange 
3816275e0d61SDaniel P. Berrange  cleanup:
3817275e0d61SDaniel P. Berrange     if (ret < 0) {
3818bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
3819275e0d61SDaniel P. Berrange     }
3820275e0d61SDaniel P. Berrange     return ret;
3821275e0d61SDaniel P. Berrange }
3822275e0d61SDaniel P. Berrange 
38239f26f325SPhilippe Mathieu-Daudé static void vnc_free_addresses(SocketAddress ***retsaddr,
38249f26f325SPhilippe Mathieu-Daudé                                size_t *retnsaddr)
38259f26f325SPhilippe Mathieu-Daudé {
38269f26f325SPhilippe Mathieu-Daudé     size_t i;
38279f26f325SPhilippe Mathieu-Daudé 
38289f26f325SPhilippe Mathieu-Daudé     for (i = 0; i < *retnsaddr; i++) {
38299f26f325SPhilippe Mathieu-Daudé         qapi_free_SocketAddress((*retsaddr)[i]);
38309f26f325SPhilippe Mathieu-Daudé     }
38319f26f325SPhilippe Mathieu-Daudé     g_free(*retsaddr);
38329f26f325SPhilippe Mathieu-Daudé 
38339f26f325SPhilippe Mathieu-Daudé     *retsaddr = NULL;
38349f26f325SPhilippe Mathieu-Daudé     *retnsaddr = 0;
38359f26f325SPhilippe Mathieu-Daudé }
38369f26f325SPhilippe Mathieu-Daudé 
3837275e0d61SDaniel P. Berrange static int vnc_display_get_addresses(QemuOpts *opts,
3838e5766eb4SGerd Hoffmann                                      bool reverse,
3839bd269ebcSMarkus Armbruster                                      SocketAddress ***retsaddr,
3840396f935aSDaniel P. Berrange                                      size_t *retnsaddr,
3841bd269ebcSMarkus Armbruster                                      SocketAddress ***retwsaddr,
3842396f935aSDaniel P. Berrange                                      size_t *retnwsaddr,
3843275e0d61SDaniel P. Berrange                                      Error **errp)
3844275e0d61SDaniel P. Berrange {
3845bd269ebcSMarkus Armbruster     SocketAddress *saddr = NULL;
3846bd269ebcSMarkus Armbruster     SocketAddress *wsaddr = NULL;
3847396f935aSDaniel P. Berrange     QemuOptsIter addriter;
3848396f935aSDaniel P. Berrange     const char *addr;
3849275e0d61SDaniel P. Berrange     int to = qemu_opt_get_number(opts, "to", 0);
3850275e0d61SDaniel P. Berrange     bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3851275e0d61SDaniel P. Berrange     bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3852275e0d61SDaniel P. Berrange     bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3853275e0d61SDaniel P. Berrange     bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3854396f935aSDaniel P. Berrange     int displaynum = -1;
3855396f935aSDaniel P. Berrange     int ret = -1;
3856275e0d61SDaniel P. Berrange 
3857275e0d61SDaniel P. Berrange     *retsaddr = NULL;
3858396f935aSDaniel P. Berrange     *retnsaddr = 0;
3859275e0d61SDaniel P. Berrange     *retwsaddr = NULL;
3860396f935aSDaniel P. Berrange     *retnwsaddr = 0;
3861275e0d61SDaniel P. Berrange 
3862396f935aSDaniel P. Berrange     addr = qemu_opt_get(opts, "vnc");
3863396f935aSDaniel P. Berrange     if (addr == NULL || g_str_equal(addr, "none")) {
3864396f935aSDaniel P. Berrange         ret = 0;
3865396f935aSDaniel P. Berrange         goto cleanup;
3866396f935aSDaniel P. Berrange     }
3867396f935aSDaniel P. Berrange     if (qemu_opt_get(opts, "websocket") &&
3868275e0d61SDaniel P. Berrange         !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3869275e0d61SDaniel P. Berrange         error_setg(errp,
3870275e0d61SDaniel P. Berrange                    "SHA1 hash support is required for websockets");
3871396f935aSDaniel P. Berrange         goto cleanup;
3872275e0d61SDaniel P. Berrange     }
3873275e0d61SDaniel P. Berrange 
3874396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "vnc");
3875396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3876396f935aSDaniel P. Berrange         int rv;
3877e5766eb4SGerd Hoffmann         rv = vnc_display_get_address(addr, false, reverse, 0, to,
3878275e0d61SDaniel P. Berrange                                      has_ipv4, has_ipv6,
3879275e0d61SDaniel P. Berrange                                      ipv4, ipv6,
3880275e0d61SDaniel P. Berrange                                      &saddr, errp);
3881396f935aSDaniel P. Berrange         if (rv < 0) {
3882396f935aSDaniel P. Berrange             goto cleanup;
3883275e0d61SDaniel P. Berrange         }
3884396f935aSDaniel P. Berrange         /* Historical compat - first listen address can be used
3885396f935aSDaniel P. Berrange          * to set the default websocket port
3886396f935aSDaniel P. Berrange          */
3887396f935aSDaniel P. Berrange         if (displaynum == -1) {
3888396f935aSDaniel P. Berrange             displaynum = rv;
3889396f935aSDaniel P. Berrange         }
3890bd269ebcSMarkus Armbruster         *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3891396f935aSDaniel P. Berrange         (*retsaddr)[(*retnsaddr)++] = saddr;
3892396f935aSDaniel P. Berrange     }
3893396f935aSDaniel P. Berrange 
3894396f935aSDaniel P. Berrange     /* If we had multiple primary displays, we don't do defaults
3895396f935aSDaniel P. Berrange      * for websocket, and require explicit config instead. */
3896396f935aSDaniel P. Berrange     if (*retnsaddr > 1) {
3897396f935aSDaniel P. Berrange         displaynum = -1;
3898396f935aSDaniel P. Berrange     }
3899396f935aSDaniel P. Berrange 
3900396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "websocket");
3901396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3902e5766eb4SGerd Hoffmann         if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3903275e0d61SDaniel P. Berrange                                     has_ipv4, has_ipv6,
3904275e0d61SDaniel P. Berrange                                     ipv4, ipv6,
3905275e0d61SDaniel P. Berrange                                     &wsaddr, errp) < 0) {
3906396f935aSDaniel P. Berrange             goto cleanup;
3907275e0d61SDaniel P. Berrange         }
3908396f935aSDaniel P. Berrange 
3909396f935aSDaniel P. Berrange         /* Historical compat - if only a single listen address was
3910396f935aSDaniel P. Berrange          * provided, then this is used to set the default listen
3911396f935aSDaniel P. Berrange          * address for websocket too
3912396f935aSDaniel P. Berrange          */
3913396f935aSDaniel P. Berrange         if (*retnsaddr == 1 &&
3914bd269ebcSMarkus Armbruster             (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3915bd269ebcSMarkus Armbruster             wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3916bd269ebcSMarkus Armbruster             g_str_equal(wsaddr->u.inet.host, "") &&
3917bd269ebcSMarkus Armbruster             !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3918bd269ebcSMarkus Armbruster             g_free(wsaddr->u.inet.host);
3919bd269ebcSMarkus Armbruster             wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3920275e0d61SDaniel P. Berrange         }
3921275e0d61SDaniel P. Berrange 
3922bd269ebcSMarkus Armbruster         *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3923396f935aSDaniel P. Berrange         (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3924396f935aSDaniel P. Berrange     }
3925396f935aSDaniel P. Berrange 
3926396f935aSDaniel P. Berrange     ret = 0;
3927396f935aSDaniel P. Berrange  cleanup:
3928396f935aSDaniel P. Berrange     if (ret < 0) {
39299f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retsaddr, retnsaddr);
39309f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retwsaddr, retnwsaddr);
3931396f935aSDaniel P. Berrange     }
3932396f935aSDaniel P. Berrange     return ret;
3933275e0d61SDaniel P. Berrange }
3934275e0d61SDaniel P. Berrange 
39358bd22f47SDaniel P. Berrange static int vnc_display_connect(VncDisplay *vd,
3936bd269ebcSMarkus Armbruster                                SocketAddress **saddr,
3937396f935aSDaniel P. Berrange                                size_t nsaddr,
3938bd269ebcSMarkus Armbruster                                SocketAddress **wsaddr,
3939396f935aSDaniel P. Berrange                                size_t nwsaddr,
39408bd22f47SDaniel P. Berrange                                Error **errp)
39418bd22f47SDaniel P. Berrange {
39428bd22f47SDaniel P. Berrange     /* connect to viewer */
39438bd22f47SDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
3944396f935aSDaniel P. Berrange     if (nwsaddr != 0) {
39458bd22f47SDaniel P. Berrange         error_setg(errp, "Cannot use websockets in reverse mode");
39468bd22f47SDaniel P. Berrange         return -1;
39478bd22f47SDaniel P. Berrange     }
3948396f935aSDaniel P. Berrange     if (nsaddr != 1) {
3949396f935aSDaniel P. Berrange         error_setg(errp, "Expected a single address in reverse mode");
3950396f935aSDaniel P. Berrange         return -1;
3951396f935aSDaniel P. Berrange     }
3952bd269ebcSMarkus Armbruster     /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3953bd269ebcSMarkus Armbruster     vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
39548bd22f47SDaniel P. Berrange     sioc = qio_channel_socket_new();
39558bd22f47SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3956396f935aSDaniel P. Berrange     if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
39575f8679feSAlex Chen         object_unref(OBJECT(sioc));
39588bd22f47SDaniel P. Berrange         return -1;
39598bd22f47SDaniel P. Berrange     }
39608bd22f47SDaniel P. Berrange     vnc_connect(vd, sioc, false, false);
39618bd22f47SDaniel P. Berrange     object_unref(OBJECT(sioc));
39628bd22f47SDaniel P. Berrange     return 0;
39638bd22f47SDaniel P. Berrange }
39648bd22f47SDaniel P. Berrange 
39658bd22f47SDaniel P. Berrange 
39668bd22f47SDaniel P. Berrange static int vnc_display_listen(VncDisplay *vd,
3967bd269ebcSMarkus Armbruster                               SocketAddress **saddr,
3968396f935aSDaniel P. Berrange                               size_t nsaddr,
3969bd269ebcSMarkus Armbruster                               SocketAddress **wsaddr,
3970396f935aSDaniel P. Berrange                               size_t nwsaddr,
39718bd22f47SDaniel P. Berrange                               Error **errp)
39728bd22f47SDaniel P. Berrange {
3973396f935aSDaniel P. Berrange     size_t i;
39748bd22f47SDaniel P. Berrange 
397513e1d0e7SDaniel P. Berrange     if (nsaddr) {
397613e1d0e7SDaniel P. Berrange         vd->listener = qio_net_listener_new();
397713e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->listener, "vnc-listen");
3978396f935aSDaniel P. Berrange         for (i = 0; i < nsaddr; i++) {
397913e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->listener,
3980fc8135c6SJuan Quintela                                            saddr[i], 1,
39818bd22f47SDaniel P. Berrange                                            errp) < 0)  {
39828bd22f47SDaniel P. Berrange                 return -1;
39838bd22f47SDaniel P. Berrange             }
3984396f935aSDaniel P. Berrange         }
398513e1d0e7SDaniel P. Berrange 
398613e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->listener,
398713e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
398813e1d0e7SDaniel P. Berrange     }
398913e1d0e7SDaniel P. Berrange 
399013e1d0e7SDaniel P. Berrange     if (nwsaddr) {
399113e1d0e7SDaniel P. Berrange         vd->wslistener = qio_net_listener_new();
399213e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3993396f935aSDaniel P. Berrange         for (i = 0; i < nwsaddr; i++) {
399413e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->wslistener,
3995fc8135c6SJuan Quintela                                            wsaddr[i], 1,
39968bd22f47SDaniel P. Berrange                                            errp) < 0)  {
39978bd22f47SDaniel P. Berrange                 return -1;
39988bd22f47SDaniel P. Berrange             }
3999396f935aSDaniel P. Berrange         }
40008bd22f47SDaniel P. Berrange 
400113e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->wslistener,
400213e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
400313e1d0e7SDaniel P. Berrange     }
400413e1d0e7SDaniel P. Berrange 
40058bd22f47SDaniel P. Berrange     return 0;
40068bd22f47SDaniel P. Berrange }
40078bd22f47SDaniel P. Berrange 
40088bd22f47SDaniel P. Berrange 
40094db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
40103e230dd2SCorentin Chary {
4011bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
40124db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
4013bd269ebcSMarkus Armbruster     SocketAddress **saddr = NULL, **wsaddr = NULL;
4014396f935aSDaniel P. Berrange     size_t nsaddr, nwsaddr;
4015e2a11d9dSGonglei     const char *share, *device_id;
40161d0d59feSGerd Hoffmann     QemuConsole *con;
4017a2c72de0SGonglei     bool password = false;
4018a2c72de0SGonglei     bool reverse = false;
40193e305e4aSDaniel P. Berrange     const char *credid;
4020a2c72de0SGonglei     bool sasl = false;
402155cf09a0SDaniel P. Berrange     const char *tlsauthz;
402255cf09a0SDaniel P. Berrange     const char *saslauthz;
40233e230dd2SCorentin Chary     int lock_key_sync = 1;
4024c5ce8333SGerd Hoffmann     int key_delay_ms;
4025f0b9f36dSKővágó, Zoltán     const char *audiodev;
40266c6840e9SDaniel P. Berrangé     const char *passwordSecret;
40273e230dd2SCorentin Chary 
4028bf01c179SDaniel P. Berrange     if (!vd) {
40292d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
40302d55f0e8SPaolo Bonzini         return;
40312d55f0e8SPaolo Bonzini     }
4032bf01c179SDaniel P. Berrange     vnc_display_close(vd);
40334db14629SGerd Hoffmann 
40344db14629SGerd Hoffmann     if (!opts) {
40352d55f0e8SPaolo Bonzini         return;
40364db14629SGerd Hoffmann     }
4037275e0d61SDaniel P. Berrange 
4038e5766eb4SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
4039e5766eb4SGerd Hoffmann     if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
4040396f935aSDaniel P. Berrange                                   &wsaddr, &nwsaddr, errp) < 0) {
4041275e0d61SDaniel P. Berrange         goto fail;
4042275e0d61SDaniel P. Berrange     }
4043275e0d61SDaniel P. Berrange 
40446c6840e9SDaniel P. Berrangé 
40456c6840e9SDaniel P. Berrangé     passwordSecret = qemu_opt_get(opts, "password-secret");
40466c6840e9SDaniel P. Berrangé     if (passwordSecret) {
40476c6840e9SDaniel P. Berrangé         if (qemu_opt_get(opts, "password")) {
40486c6840e9SDaniel P. Berrangé             error_setg(errp,
40496c6840e9SDaniel P. Berrangé                        "'password' flag is redundant with 'password-secret'");
40506c6840e9SDaniel P. Berrangé             goto fail;
40516c6840e9SDaniel P. Berrangé         }
40526c6840e9SDaniel P. Berrangé         vd->password = qcrypto_secret_lookup_as_utf8(passwordSecret,
40536c6840e9SDaniel P. Berrangé                                                      errp);
40546c6840e9SDaniel P. Berrangé         if (!vd->password) {
40556c6840e9SDaniel P. Berrangé             goto fail;
40566c6840e9SDaniel P. Berrangé         }
40576c6840e9SDaniel P. Berrangé         password = true;
40586c6840e9SDaniel P. Berrangé     } else {
40594db14629SGerd Hoffmann         password = qemu_opt_get_bool(opts, "password", false);
40606c6840e9SDaniel P. Berrangé     }
4061800567a6SDaniel P. Berrange     if (password) {
4062800567a6SDaniel P. Berrange         if (fips_get_state()) {
40632d55f0e8SPaolo Bonzini             error_setg(errp,
40640f66998fSPaul Moore                        "VNC password auth disabled due to FIPS mode, "
40650f66998fSPaul Moore                        "consider using the VeNCrypt or SASL authentication "
40662d55f0e8SPaolo Bonzini                        "methods as an alternative");
40671ce52c78SPaolo Bonzini             goto fail;
40680f66998fSPaul Moore         }
4069800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
407083bee4b5SDaniel P. Berrangé                 QCRYPTO_CIPHER_ALG_DES, QCRYPTO_CIPHER_MODE_ECB)) {
4071800567a6SDaniel P. Berrange             error_setg(errp,
407283bee4b5SDaniel P. Berrangé                        "Cipher backend does not support DES algorithm");
4073800567a6SDaniel P. Berrange             goto fail;
4074800567a6SDaniel P. Berrange         }
4075800567a6SDaniel P. Berrange     }
40764db14629SGerd Hoffmann 
40774db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
4078d3b0db6dSAlexander Graf     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
40794db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
4080d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
4081d169f04bSDaniel P. Berrange     if (sasl) {
4082d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
4083d169f04bSDaniel P. Berrange         goto fail;
4084d169f04bSDaniel P. Berrange     }
4085d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
40863e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
40873e305e4aSDaniel P. Berrange     if (credid) {
40883e305e4aSDaniel P. Berrange         Object *creds;
40893e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
40903e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
40913e305e4aSDaniel P. Berrange         if (!creds) {
40923e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
40933e305e4aSDaniel P. Berrange                        credid);
40943e305e4aSDaniel P. Berrange             goto fail;
40953e305e4aSDaniel P. Berrange         }
4096bf01c179SDaniel P. Berrange         vd->tlscreds = (QCryptoTLSCreds *)
40973e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
40983e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
4099bf01c179SDaniel P. Berrange         if (!vd->tlscreds) {
41003e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
41013e305e4aSDaniel P. Berrange                        credid);
41023e305e4aSDaniel P. Berrange             goto fail;
41033e305e4aSDaniel P. Berrange         }
4104bf01c179SDaniel P. Berrange         object_ref(OBJECT(vd->tlscreds));
41053e305e4aSDaniel P. Berrange 
41063c52bf0cSPhilippe Mathieu-Daudé         if (!qcrypto_tls_creds_check_endpoint(vd->tlscreds,
41073c52bf0cSPhilippe Mathieu-Daudé                                               QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
41083c52bf0cSPhilippe Mathieu-Daudé                                               errp)) {
41093e305e4aSDaniel P. Berrange             goto fail;
41103e305e4aSDaniel P. Berrange         }
4111d169f04bSDaniel P. Berrange     }
411255cf09a0SDaniel P. Berrange     tlsauthz = qemu_opt_get(opts, "tls-authz");
411355cf09a0SDaniel P. Berrange     if (tlsauthz && !vd->tlscreds) {
411455cf09a0SDaniel P. Berrange         error_setg(errp, "'tls-authz' provided but TLS is not enabled");
411555cf09a0SDaniel P. Berrange         goto fail;
411655cf09a0SDaniel P. Berrange     }
411755cf09a0SDaniel P. Berrange 
411855cf09a0SDaniel P. Berrange     saslauthz = qemu_opt_get(opts, "sasl-authz");
411955cf09a0SDaniel P. Berrange     if (saslauthz && !sasl) {
412055cf09a0SDaniel P. Berrange         error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
412155cf09a0SDaniel P. Berrange         goto fail;
412255cf09a0SDaniel P. Berrange     }
41234db14629SGerd Hoffmann 
41244db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
41254db14629SGerd Hoffmann     if (share) {
41264db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
4127bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_IGNORE;
41284db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
4129bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
41304db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
4131bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
41328cf36489SGerd Hoffmann         } else {
41332d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
41341ce52c78SPaolo Bonzini             goto fail;
41358cf36489SGerd Hoffmann         }
41364db14629SGerd Hoffmann     } else {
4137bf01c179SDaniel P. Berrange         vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
41383e230dd2SCorentin Chary     }
4139bf01c179SDaniel P. Berrange     vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
41403e230dd2SCorentin Chary 
41414db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
4142bf01c179SDaniel P. Berrange     vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
41434db14629SGerd Hoffmann #endif
4144bf01c179SDaniel P. Berrange     vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4145e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
4146e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
4147e22492d3SPeter Lieven      * calculations otherwise */
4148bf01c179SDaniel P. Berrange     if (!vd->lossy) {
4149bf01c179SDaniel P. Berrange         vd->non_adaptive = true;
4150e22492d3SPeter Lieven     }
4151e22492d3SPeter Lieven 
41527b5fa0b5SDaniel P. Berrangé     vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
41537b5fa0b5SDaniel P. Berrangé 
415455cf09a0SDaniel P. Berrange     if (tlsauthz) {
415555cf09a0SDaniel P. Berrange         vd->tlsauthzid = g_strdup(tlsauthz);
41563e230dd2SCorentin Chary     }
41573e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
415855cf09a0SDaniel P. Berrange     if (sasl) {
415955cf09a0SDaniel P. Berrange         if (saslauthz) {
416055cf09a0SDaniel P. Berrange             vd->sasl.authzid = g_strdup(saslauthz);
41613e230dd2SCorentin Chary         }
416255cf09a0SDaniel P. Berrange     }
41633e230dd2SCorentin Chary #endif
41643e230dd2SCorentin Chary 
4165eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4166eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4167eda24e18SDaniel P. Berrange                                sasl, false, errp) < 0) {
4168eda24e18SDaniel P. Berrange         goto fail;
4169eda24e18SDaniel P. Berrange     }
41707364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4171eda24e18SDaniel P. Berrange 
4172eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4173eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4174eda24e18SDaniel P. Berrange                                sasl, true, errp) < 0) {
41753e305e4aSDaniel P. Berrange         goto fail;
41763e305e4aSDaniel P. Berrange     }
41777364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
41783e230dd2SCorentin Chary 
41793e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
4180b65310abSPaolo Bonzini     if (sasl && !vnc_sasl_server_init(errp)) {
41811ce52c78SPaolo Bonzini         goto fail;
41823e230dd2SCorentin Chary     }
41833e230dd2SCorentin Chary #endif
4184bf01c179SDaniel P. Berrange     vd->lock_key_sync = lock_key_sync;
4185a54f0d2bSPierre Ossman     if (lock_key_sync) {
4186a54f0d2bSPierre Ossman         vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4187a54f0d2bSPierre Ossman     }
4188a54f0d2bSPierre Ossman     vd->ledstate = 0;
41893e230dd2SCorentin Chary 
4190f0b9f36dSKővágó, Zoltán     audiodev = qemu_opt_get(opts, "audiodev");
4191f0b9f36dSKővágó, Zoltán     if (audiodev) {
4192f0b9f36dSKővágó, Zoltán         vd->audio_state = audio_state_by_name(audiodev);
4193f0b9f36dSKővágó, Zoltán         if (!vd->audio_state) {
4194f0b9f36dSKővágó, Zoltán             error_setg(errp, "Audiodev '%s' not found", audiodev);
4195f0b9f36dSKővágó, Zoltán             goto fail;
4196f0b9f36dSKővágó, Zoltán         }
4197f0b9f36dSKővágó, Zoltán     }
4198f0b9f36dSKővágó, Zoltán 
41991d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
42001d0d59feSGerd Hoffmann     if (device_id) {
42011d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
4202f2c1d54cSGerd Hoffmann         Error *err = NULL;
42031d0d59feSGerd Hoffmann 
4204f2c1d54cSGerd Hoffmann         con = qemu_console_lookup_by_device_name(device_id, head, &err);
4205f2c1d54cSGerd Hoffmann         if (err) {
4206f2c1d54cSGerd Hoffmann             error_propagate(errp, err);
42071d0d59feSGerd Hoffmann             goto fail;
42081d0d59feSGerd Hoffmann         }
42091d0d59feSGerd Hoffmann     } else {
42101d0d59feSGerd Hoffmann         con = NULL;
42111d0d59feSGerd Hoffmann     }
42121d0d59feSGerd Hoffmann 
4213bf01c179SDaniel P. Berrange     if (con != vd->dcl.con) {
4214c2f2ba49SGerd Hoffmann         qkbd_state_free(vd->kbd);
4215bf01c179SDaniel P. Berrange         unregister_displaychangelistener(&vd->dcl);
4216bf01c179SDaniel P. Berrange         vd->dcl.con = con;
4217bf01c179SDaniel P. Berrange         register_displaychangelistener(&vd->dcl);
4218c2f2ba49SGerd Hoffmann         vd->kbd = qkbd_state_init(vd->dcl.con);
42191d0d59feSGerd Hoffmann     }
4220c2f2ba49SGerd Hoffmann     qkbd_state_set_delay(vd->kbd, key_delay_ms);
42211d0d59feSGerd Hoffmann 
4222fa03cb7fSMarc-André Lureau     if (saddr == NULL) {
4223fa03cb7fSMarc-André Lureau         goto cleanup;
4224fa03cb7fSMarc-André Lureau     }
4225fa03cb7fSMarc-André Lureau 
42263e230dd2SCorentin Chary     if (reverse) {
4227396f935aSDaniel P. Berrange         if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4228e0d03b8cSDaniel P. Berrange             goto fail;
42293e230dd2SCorentin Chary         }
42303e230dd2SCorentin Chary     } else {
4231396f935aSDaniel P. Berrange         if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
42323d00ac1aSCole Robinson             goto fail;
42333d00ac1aSCole Robinson         }
42343e230dd2SCorentin Chary     }
4235e0d03b8cSDaniel P. Berrange 
4236275e0d61SDaniel P. Berrange     if (qemu_opt_get(opts, "to")) {
4237bf01c179SDaniel P. Berrange         vnc_display_print_local_addr(vd);
423833df7bf3SPaolo Bonzini     }
423933df7bf3SPaolo Bonzini 
4240396f935aSDaniel P. Berrange  cleanup:
42419f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&saddr, &nsaddr);
42429f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&wsaddr, &nwsaddr);
42432d55f0e8SPaolo Bonzini     return;
42441ce52c78SPaolo Bonzini 
42451ce52c78SPaolo Bonzini fail:
42464ee74fa7SDaniel P. Berrange     vnc_display_close(vd);
4247396f935aSDaniel P. Berrange     goto cleanup;
42483e230dd2SCorentin Chary }
424913661089SDaniel P. Berrange 
425014f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
425113661089SDaniel P. Berrange {
4252bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
425304d2529dSDaniel P. Berrange     QIOChannelSocket *sioc;
425413661089SDaniel P. Berrange 
4255bf01c179SDaniel P. Berrange     if (!vd) {
4256d616ccc5SGerd Hoffmann         return;
4257d616ccc5SGerd Hoffmann     }
425804d2529dSDaniel P. Berrange 
425904d2529dSDaniel P. Berrange     sioc = qio_channel_socket_new_fd(csock, NULL);
426004d2529dSDaniel P. Berrange     if (sioc) {
426110bcfe58SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4262bf01c179SDaniel P. Berrange         vnc_connect(vd, sioc, skipauth, false);
426304d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
426404d2529dSDaniel P. Berrange     }
426513661089SDaniel P. Berrange }
42664db14629SGerd Hoffmann 
42679634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
42682779672fSGonglei {
42692779672fSGonglei     int i = 2;
42702779672fSGonglei     char *id;
42712779672fSGonglei 
42722779672fSGonglei     id = g_strdup("default");
42732779672fSGonglei     while (qemu_opts_find(olist, id)) {
42742779672fSGonglei         g_free(id);
42752779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
42762779672fSGonglei     }
42772779672fSGonglei     qemu_opts_set_id(opts, id);
42782779672fSGonglei }
42792779672fSGonglei 
4280653c9747SPaolo Bonzini void vnc_parse(const char *str)
42814db14629SGerd Hoffmann {
42824db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
4283653c9747SPaolo Bonzini     QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
428481607cbfSGonglei     const char *id;
42854db14629SGerd Hoffmann 
428681607cbfSGonglei     if (!opts) {
4287653c9747SPaolo Bonzini         exit(1);
428881607cbfSGonglei     }
428981607cbfSGonglei 
429081607cbfSGonglei     id = qemu_opts_id(opts);
42914db14629SGerd Hoffmann     if (!id) {
42924db14629SGerd Hoffmann         /* auto-assign id if not present */
42932779672fSGonglei         vnc_auto_assign_id(olist, opts);
42949634f4e3SGerd Hoffmann     }
42954db14629SGerd Hoffmann }
42964db14629SGerd Hoffmann 
429728d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
42989634f4e3SGerd Hoffmann {
42999634f4e3SGerd Hoffmann     Error *local_err = NULL;
43009634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
43019634f4e3SGerd Hoffmann 
43029634f4e3SGerd Hoffmann     assert(id);
4303ab4f931eSFei Li     vnc_display_init(id, &local_err);
4304ab4f931eSFei Li     if (local_err) {
4305612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4306612aea20SMarkus Armbruster         return -1;
4307ab4f931eSFei Li     }
43084db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
43094db14629SGerd Hoffmann     if (local_err != NULL) {
4310612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4311612aea20SMarkus Armbruster         return -1;
43124db14629SGerd Hoffmann     }
43134db14629SGerd Hoffmann     return 0;
43144db14629SGerd Hoffmann }
43154db14629SGerd Hoffmann 
43164db14629SGerd Hoffmann static void vnc_register_config(void)
43174db14629SGerd Hoffmann {
43184db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
43194db14629SGerd Hoffmann }
432034294e2fSEduardo Habkost opts_init(vnc_register_config);
4321