xref: /openbmc/qemu/ui/vnc.c (revision 69cc8db44bdf7c9289e1fd1f695e01ec6132bf2b)
13e230dd2SCorentin Chary /*
23e230dd2SCorentin Chary  * QEMU VNC display driver
33e230dd2SCorentin Chary  *
43e230dd2SCorentin Chary  * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
53e230dd2SCorentin Chary  * Copyright (C) 2006 Fabrice Bellard
63e230dd2SCorentin Chary  * Copyright (C) 2009 Red Hat, Inc
73e230dd2SCorentin Chary  *
83e230dd2SCorentin Chary  * Permission is hereby granted, free of charge, to any person obtaining a copy
93e230dd2SCorentin Chary  * of this software and associated documentation files (the "Software"), to deal
103e230dd2SCorentin Chary  * in the Software without restriction, including without limitation the rights
113e230dd2SCorentin Chary  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
123e230dd2SCorentin Chary  * copies of the Software, and to permit persons to whom the Software is
133e230dd2SCorentin Chary  * furnished to do so, subject to the following conditions:
143e230dd2SCorentin Chary  *
153e230dd2SCorentin Chary  * The above copyright notice and this permission notice shall be included in
163e230dd2SCorentin Chary  * all copies or substantial portions of the Software.
173e230dd2SCorentin Chary  *
183e230dd2SCorentin Chary  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
193e230dd2SCorentin Chary  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
203e230dd2SCorentin Chary  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
213e230dd2SCorentin Chary  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
223e230dd2SCorentin Chary  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
233e230dd2SCorentin Chary  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
243e230dd2SCorentin Chary  * THE SOFTWARE.
253e230dd2SCorentin Chary  */
263e230dd2SCorentin Chary 
27e16f4c87SPeter Maydell #include "qemu/osdep.h"
283e230dd2SCorentin Chary #include "vnc.h"
29bd023f95SCorentin Chary #include "vnc-jobs.h"
3040066175SGerd Hoffmann #include "trace.h"
3113d4ff07SMarkus Armbruster #include "hw/qdev-core.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
337b5fa0b5SDaniel P. Berrangé #include "sysemu/runstate.h"
34d49b6836SMarkus Armbruster #include "qemu/error-report.h"
35db725815SMarkus Armbruster #include "qemu/main-loop.h"
360b8fa32fSMarkus Armbruster #include "qemu/module.h"
37922a01a0SMarkus Armbruster #include "qemu/option.h"
381de7afc9SPaolo Bonzini #include "qemu/sockets.h"
391de7afc9SPaolo Bonzini #include "qemu/timer.h"
40b76806d4SDaniel P. Berrange #include "authz/list.h"
414db14629SGerd Hoffmann #include "qemu/config-file.h"
425d75648bSMarkus Armbruster #include "qapi/qapi-emit-events.h"
435d75648bSMarkus Armbruster #include "qapi/qapi-events-ui.h"
44e688df6bSMarkus Armbruster #include "qapi/error.h"
459af23989SMarkus Armbruster #include "qapi/qapi-commands-ui.h"
468d447d10SGerd Hoffmann #include "ui/input.h"
478e9b0d24SDaniel P. Berrange #include "crypto/hash.h"
483e305e4aSDaniel P. Berrange #include "crypto/tlscredsanon.h"
493e305e4aSDaniel P. Berrange #include "crypto/tlscredsx509.h"
50f7b2502cSRichard Henderson #include "crypto/random.h"
516c6840e9SDaniel P. Berrangé #include "crypto/secret_common.h"
523e305e4aSDaniel P. Berrange #include "qom/object_interfaces.h"
53f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
54653c9747SPaolo Bonzini #include "qemu/help_option.h"
5557a6d6d5SDaniel P. Berrange #include "io/dns-resolver.h"
563e230dd2SCorentin Chary 
570f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
583e230dd2SCorentin Chary #define VNC_REFRESH_INTERVAL_INC  50
590f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
60999342a0SCorentin Chary static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
61999342a0SCorentin Chary static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
623e230dd2SCorentin Chary 
633e230dd2SCorentin Chary #include "vnc_keysym.h"
64800567a6SDaniel P. Berrange #include "crypto/cipher.h"
653e230dd2SCorentin Chary 
66d616ccc5SGerd Hoffmann static QTAILQ_HEAD(, VncDisplay) vnc_displays =
67d616ccc5SGerd Hoffmann     QTAILQ_HEAD_INITIALIZER(vnc_displays);
683e230dd2SCorentin Chary 
693e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs);
70e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs);
713e230dd2SCorentin Chary 
728cf36489SGerd Hoffmann static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
738cf36489SGerd Hoffmann {
748cf36489SGerd Hoffmann #ifdef _VNC_DEBUG
758cf36489SGerd Hoffmann     static const char *mn[] = {
768cf36489SGerd Hoffmann         [0]                           = "undefined",
778cf36489SGerd Hoffmann         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
788cf36489SGerd Hoffmann         [VNC_SHARE_MODE_SHARED]       = "shared",
798cf36489SGerd Hoffmann         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
808cf36489SGerd Hoffmann         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
818cf36489SGerd Hoffmann     };
8204d2529dSDaniel P. Berrange     fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
8304d2529dSDaniel P. Berrange             vs->ioc, mn[vs->share_mode], mn[mode]);
848cf36489SGerd Hoffmann #endif
858cf36489SGerd Hoffmann 
86e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
87e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
88e5f34cddSGerd Hoffmann         vs->vd->num_connecting--;
89e5f34cddSGerd Hoffmann         break;
90e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
91e5f34cddSGerd Hoffmann         vs->vd->num_shared--;
92e5f34cddSGerd Hoffmann         break;
93e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
948cf36489SGerd Hoffmann         vs->vd->num_exclusive--;
95e5f34cddSGerd Hoffmann         break;
96e5f34cddSGerd Hoffmann     default:
97e5f34cddSGerd Hoffmann         break;
988cf36489SGerd Hoffmann     }
99e5f34cddSGerd Hoffmann 
1008cf36489SGerd Hoffmann     vs->share_mode = mode;
101e5f34cddSGerd Hoffmann 
102e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
103e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
104e5f34cddSGerd Hoffmann         vs->vd->num_connecting++;
105e5f34cddSGerd Hoffmann         break;
106e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
107e5f34cddSGerd Hoffmann         vs->vd->num_shared++;
108e5f34cddSGerd Hoffmann         break;
109e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
1108cf36489SGerd Hoffmann         vs->vd->num_exclusive++;
111e5f34cddSGerd Hoffmann         break;
112e5f34cddSGerd Hoffmann     default:
113e5f34cddSGerd Hoffmann         break;
1148cf36489SGerd Hoffmann     }
1158cf36489SGerd Hoffmann }
1168cf36489SGerd Hoffmann 
1173e230dd2SCorentin Chary 
118bd269ebcSMarkus Armbruster static void vnc_init_basic_info(SocketAddress *addr,
11998481bfcSEric Blake                                 VncBasicInfo *info,
12098481bfcSEric Blake                                 Error **errp)
1213e230dd2SCorentin Chary {
12204d2529dSDaniel P. Berrange     switch (addr->type) {
123bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_INET:
124bd269ebcSMarkus Armbruster         info->host = g_strdup(addr->u.inet.host);
125bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.inet.port);
126bd269ebcSMarkus Armbruster         if (addr->u.inet.ipv6) {
12704d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
12804d2529dSDaniel P. Berrange         } else {
12904d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
13004d2529dSDaniel P. Berrange         }
13104d2529dSDaniel P. Berrange         break;
1323e230dd2SCorentin Chary 
133bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_UNIX:
13404d2529dSDaniel P. Berrange         info->host = g_strdup("");
135bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.q_unix.path);
13604d2529dSDaniel P. Berrange         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
13704d2529dSDaniel P. Berrange         break;
13804d2529dSDaniel P. Berrange 
139bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_VSOCK:
140bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_FD:
141a6c76285SMarkus Armbruster         error_setg(errp, "Unsupported socket address type %s",
142977c736fSMarkus Armbruster                    SocketAddressType_str(addr->type));
14304d2529dSDaniel P. Berrange         break;
144a6c76285SMarkus Armbruster     default:
145a6c76285SMarkus Armbruster         abort();
14604d2529dSDaniel P. Berrange     }
14704d2529dSDaniel P. Berrange 
14898481bfcSEric Blake     return;
1493e230dd2SCorentin Chary }
1503e230dd2SCorentin Chary 
15104d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
15204d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
15398481bfcSEric Blake                                                  Error **errp)
1543e230dd2SCorentin Chary {
155bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1563e230dd2SCorentin Chary 
157624cdd46SDaniel P. Berrange     if (!ioc) {
158624cdd46SDaniel P. Berrange         error_setg(errp, "No listener socket available");
159624cdd46SDaniel P. Berrange         return;
160624cdd46SDaniel P. Berrange     }
161624cdd46SDaniel P. Berrange 
16204d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, errp);
16304d2529dSDaniel P. Berrange     if (!addr) {
16498481bfcSEric Blake         return;
1653e230dd2SCorentin Chary     }
1663e230dd2SCorentin Chary 
16704d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
168bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1693e230dd2SCorentin Chary }
1703e230dd2SCorentin Chary 
17104d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
17204d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
17398481bfcSEric Blake                                                  Error **errp)
1743e230dd2SCorentin Chary {
175bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1763e230dd2SCorentin Chary 
17704d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_remote_address(ioc, errp);
17804d2529dSDaniel P. Berrange     if (!addr) {
17998481bfcSEric Blake         return;
1803e230dd2SCorentin Chary     }
1813e230dd2SCorentin Chary 
18204d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
183bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1843e230dd2SCorentin Chary }
1853e230dd2SCorentin Chary 
1863e230dd2SCorentin Chary static const char *vnc_auth_name(VncDisplay *vd) {
1873e230dd2SCorentin Chary     switch (vd->auth) {
1883e230dd2SCorentin Chary     case VNC_AUTH_INVALID:
1893e230dd2SCorentin Chary         return "invalid";
1903e230dd2SCorentin Chary     case VNC_AUTH_NONE:
1913e230dd2SCorentin Chary         return "none";
1923e230dd2SCorentin Chary     case VNC_AUTH_VNC:
1933e230dd2SCorentin Chary         return "vnc";
1943e230dd2SCorentin Chary     case VNC_AUTH_RA2:
1953e230dd2SCorentin Chary         return "ra2";
1963e230dd2SCorentin Chary     case VNC_AUTH_RA2NE:
1973e230dd2SCorentin Chary         return "ra2ne";
1983e230dd2SCorentin Chary     case VNC_AUTH_TIGHT:
1993e230dd2SCorentin Chary         return "tight";
2003e230dd2SCorentin Chary     case VNC_AUTH_ULTRA:
2013e230dd2SCorentin Chary         return "ultra";
2023e230dd2SCorentin Chary     case VNC_AUTH_TLS:
2033e230dd2SCorentin Chary         return "tls";
2043e230dd2SCorentin Chary     case VNC_AUTH_VENCRYPT:
2053e230dd2SCorentin Chary         switch (vd->subauth) {
2063e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_PLAIN:
2073e230dd2SCorentin Chary             return "vencrypt+plain";
2083e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSNONE:
2093e230dd2SCorentin Chary             return "vencrypt+tls+none";
2103e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSVNC:
2113e230dd2SCorentin Chary             return "vencrypt+tls+vnc";
2123e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSPLAIN:
2133e230dd2SCorentin Chary             return "vencrypt+tls+plain";
2143e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509NONE:
2153e230dd2SCorentin Chary             return "vencrypt+x509+none";
2163e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509VNC:
2173e230dd2SCorentin Chary             return "vencrypt+x509+vnc";
2183e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509PLAIN:
2193e230dd2SCorentin Chary             return "vencrypt+x509+plain";
2203e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSSASL:
2213e230dd2SCorentin Chary             return "vencrypt+tls+sasl";
2223e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509SASL:
2233e230dd2SCorentin Chary             return "vencrypt+x509+sasl";
2243e230dd2SCorentin Chary         default:
2253e230dd2SCorentin Chary             return "vencrypt";
2263e230dd2SCorentin Chary         }
2273e230dd2SCorentin Chary     case VNC_AUTH_SASL:
2283e230dd2SCorentin Chary         return "sasl";
2293e230dd2SCorentin Chary     }
2303e230dd2SCorentin Chary     return "unknown";
2313e230dd2SCorentin Chary }
2323e230dd2SCorentin Chary 
233d616ccc5SGerd Hoffmann static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
2343e230dd2SCorentin Chary {
235fb6ba0d5SWenchao Xia     VncServerInfo *info;
23698481bfcSEric Blake     Error *err = NULL;
2373e230dd2SCorentin Chary 
23813e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
2394ee74fa7SDaniel P. Berrange         return NULL;
2404ee74fa7SDaniel P. Berrange     }
2414ee74fa7SDaniel P. Berrange 
2423e7f136dSDaniel P. Berrange     info = g_malloc0(sizeof(*info));
24313e1d0e7SDaniel P. Berrange     vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
244ddf21908SEric Blake                                          qapi_VncServerInfo_base(info), &err);
245fb6ba0d5SWenchao Xia     info->has_auth = true;
246d616ccc5SGerd Hoffmann     info->auth = g_strdup(vnc_auth_name(vd));
24798481bfcSEric Blake     if (err) {
24898481bfcSEric Blake         qapi_free_VncServerInfo(info);
24998481bfcSEric Blake         info = NULL;
25098481bfcSEric Blake         error_free(err);
25198481bfcSEric Blake     }
252fb6ba0d5SWenchao Xia     return info;
2533e230dd2SCorentin Chary }
2543e230dd2SCorentin Chary 
2553e230dd2SCorentin Chary static void vnc_client_cache_auth(VncState *client)
2563e230dd2SCorentin Chary {
2573e230dd2SCorentin Chary     if (!client->info) {
2583e230dd2SCorentin Chary         return;
2593e230dd2SCorentin Chary     }
2603e230dd2SCorentin Chary 
2613e305e4aSDaniel P. Berrange     if (client->tls) {
2623e305e4aSDaniel P. Berrange         client->info->x509_dname =
2633e305e4aSDaniel P. Berrange             qcrypto_tls_session_get_peer_name(client->tls);
2643e305e4aSDaniel P. Berrange         client->info->has_x509_dname =
2653e305e4aSDaniel P. Berrange             client->info->x509_dname != NULL;
2663e230dd2SCorentin Chary     }
2673e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
2683e230dd2SCorentin Chary     if (client->sasl.conn &&
2693e230dd2SCorentin Chary         client->sasl.username) {
270fb6ba0d5SWenchao Xia         client->info->has_sasl_username = true;
271fb6ba0d5SWenchao Xia         client->info->sasl_username = g_strdup(client->sasl.username);
2723e230dd2SCorentin Chary     }
2733e230dd2SCorentin Chary #endif
2743e230dd2SCorentin Chary }
2753e230dd2SCorentin Chary 
2763e230dd2SCorentin Chary static void vnc_client_cache_addr(VncState *client)
2773e230dd2SCorentin Chary {
27898481bfcSEric Blake     Error *err = NULL;
2793e230dd2SCorentin Chary 
280fb6ba0d5SWenchao Xia     client->info = g_malloc0(sizeof(*client->info));
28104d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
282ddf21908SEric Blake                                          qapi_VncClientInfo_base(client->info),
28398481bfcSEric Blake                                          &err);
284e1b3d477SGerd Hoffmann     client->info->websocket = client->websocket;
28598481bfcSEric Blake     if (err) {
28698481bfcSEric Blake         qapi_free_VncClientInfo(client->info);
28798481bfcSEric Blake         client->info = NULL;
28898481bfcSEric Blake         error_free(err);
289fb6ba0d5SWenchao Xia     }
2903e230dd2SCorentin Chary }
2913e230dd2SCorentin Chary 
292fb6ba0d5SWenchao Xia static void vnc_qmp_event(VncState *vs, QAPIEvent event)
2933e230dd2SCorentin Chary {
294fb6ba0d5SWenchao Xia     VncServerInfo *si;
2953e230dd2SCorentin Chary 
2963e230dd2SCorentin Chary     if (!vs->info) {
2973e230dd2SCorentin Chary         return;
2983e230dd2SCorentin Chary     }
2993e230dd2SCorentin Chary 
300d616ccc5SGerd Hoffmann     si = vnc_server_info_get(vs->vd);
301fb6ba0d5SWenchao Xia     if (!si) {
3023e230dd2SCorentin Chary         return;
3033e230dd2SCorentin Chary     }
3043e230dd2SCorentin Chary 
305fb6ba0d5SWenchao Xia     switch (event) {
306fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_CONNECTED:
3073ab72385SPeter Xu         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
308fb6ba0d5SWenchao Xia         break;
309fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_INITIALIZED:
3103ab72385SPeter Xu         qapi_event_send_vnc_initialized(si, vs->info);
311fb6ba0d5SWenchao Xia         break;
312fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_DISCONNECTED:
3133ab72385SPeter Xu         qapi_event_send_vnc_disconnected(si, vs->info);
314fb6ba0d5SWenchao Xia         break;
315fb6ba0d5SWenchao Xia     default:
316fb6ba0d5SWenchao Xia         break;
317fb6ba0d5SWenchao Xia     }
3183e230dd2SCorentin Chary 
319fb6ba0d5SWenchao Xia     qapi_free_VncServerInfo(si);
3203e230dd2SCorentin Chary }
3213e230dd2SCorentin Chary 
3222b54aa87SLuiz Capitulino static VncClientInfo *qmp_query_vnc_client(const VncState *client)
3233e230dd2SCorentin Chary {
3242b54aa87SLuiz Capitulino     VncClientInfo *info;
32504d2529dSDaniel P. Berrange     Error *err = NULL;
3262b54aa87SLuiz Capitulino 
3272b54aa87SLuiz Capitulino     info = g_malloc0(sizeof(*info));
32804d2529dSDaniel P. Berrange 
32904d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
33004d2529dSDaniel P. Berrange                                          qapi_VncClientInfo_base(info),
33104d2529dSDaniel P. Berrange                                          &err);
33204d2529dSDaniel P. Berrange     if (err) {
33304d2529dSDaniel P. Berrange         error_free(err);
33404d2529dSDaniel P. Berrange         qapi_free_VncClientInfo(info);
33504d2529dSDaniel P. Berrange         return NULL;
33604d2529dSDaniel P. Berrange     }
33704d2529dSDaniel P. Berrange 
338ddf21908SEric Blake     info->websocket = client->websocket;
3393e230dd2SCorentin Chary 
3403e305e4aSDaniel P. Berrange     if (client->tls) {
3413e305e4aSDaniel P. Berrange         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
3423e305e4aSDaniel P. Berrange         info->has_x509_dname = info->x509_dname != NULL;
3432b54aa87SLuiz Capitulino     }
3443e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
3452b54aa87SLuiz Capitulino     if (client->sasl.conn && client->sasl.username) {
3462b54aa87SLuiz Capitulino         info->has_sasl_username = true;
3472b54aa87SLuiz Capitulino         info->sasl_username = g_strdup(client->sasl.username);
3482b54aa87SLuiz Capitulino     }
3493e230dd2SCorentin Chary #endif
3502b54aa87SLuiz Capitulino 
3512b54aa87SLuiz Capitulino     return info;
3523e230dd2SCorentin Chary }
3533e230dd2SCorentin Chary 
354d616ccc5SGerd Hoffmann static VncDisplay *vnc_display_find(const char *id)
355d616ccc5SGerd Hoffmann {
356d616ccc5SGerd Hoffmann     VncDisplay *vd;
357d616ccc5SGerd Hoffmann 
358d616ccc5SGerd Hoffmann     if (id == NULL) {
359d616ccc5SGerd Hoffmann         return QTAILQ_FIRST(&vnc_displays);
360d616ccc5SGerd Hoffmann     }
361d616ccc5SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
362d616ccc5SGerd Hoffmann         if (strcmp(id, vd->id) == 0) {
363d616ccc5SGerd Hoffmann             return vd;
364d616ccc5SGerd Hoffmann         }
365d616ccc5SGerd Hoffmann     }
366d616ccc5SGerd Hoffmann     return NULL;
367d616ccc5SGerd Hoffmann }
368d616ccc5SGerd Hoffmann 
3692d29a436SGerd Hoffmann static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
3702d29a436SGerd Hoffmann {
37154aa3de7SEric Blake     VncClientInfoList *prev = NULL;
3722d29a436SGerd Hoffmann     VncState *client;
3732d29a436SGerd Hoffmann 
3742d29a436SGerd Hoffmann     QTAILQ_FOREACH(client, &vd->clients, next) {
37554aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, qmp_query_vnc_client(client));
3762d29a436SGerd Hoffmann     }
3772d29a436SGerd Hoffmann     return prev;
3782d29a436SGerd Hoffmann }
3792d29a436SGerd Hoffmann 
3802b54aa87SLuiz Capitulino VncInfo *qmp_query_vnc(Error **errp)
3813e230dd2SCorentin Chary {
3822b54aa87SLuiz Capitulino     VncInfo *info = g_malloc0(sizeof(*info));
383d616ccc5SGerd Hoffmann     VncDisplay *vd = vnc_display_find(NULL);
384bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3853e230dd2SCorentin Chary 
38613e1d0e7SDaniel P. Berrange     if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
3872b54aa87SLuiz Capitulino         info->enabled = false;
3883e230dd2SCorentin Chary     } else {
3892b54aa87SLuiz Capitulino         info->enabled = true;
3902b54aa87SLuiz Capitulino 
3912b54aa87SLuiz Capitulino         /* for compatibility with the original command */
3922b54aa87SLuiz Capitulino         info->has_clients = true;
3932d29a436SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
3943e230dd2SCorentin Chary 
39513e1d0e7SDaniel P. Berrange         addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
39613e1d0e7SDaniel P. Berrange                                                     errp);
39704d2529dSDaniel P. Berrange         if (!addr) {
3982b54aa87SLuiz Capitulino             goto out_error;
3992b54aa87SLuiz Capitulino         }
4003e230dd2SCorentin Chary 
40104d2529dSDaniel P. Berrange         switch (addr->type) {
402bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_INET:
403bd269ebcSMarkus Armbruster             info->host = g_strdup(addr->u.inet.host);
404bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.inet.port);
405bd269ebcSMarkus Armbruster             if (addr->u.inet.ipv6) {
40604d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
40704d2529dSDaniel P. Berrange             } else {
40804d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
40904d2529dSDaniel P. Berrange             }
41004d2529dSDaniel P. Berrange             break;
41104d2529dSDaniel P. Berrange 
412bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_UNIX:
41304d2529dSDaniel P. Berrange             info->host = g_strdup("");
414bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.q_unix.path);
41504d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
41604d2529dSDaniel P. Berrange             break;
41704d2529dSDaniel P. Berrange 
418bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_VSOCK:
419bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_FD:
420a6c76285SMarkus Armbruster             error_setg(errp, "Unsupported socket address type %s",
421977c736fSMarkus Armbruster                        SocketAddressType_str(addr->type));
4222b54aa87SLuiz Capitulino             goto out_error;
423a6c76285SMarkus Armbruster         default:
424a6c76285SMarkus Armbruster             abort();
4253e230dd2SCorentin Chary         }
4262b54aa87SLuiz Capitulino 
4272b54aa87SLuiz Capitulino         info->has_host = true;
4282b54aa87SLuiz Capitulino         info->has_service = true;
4292b54aa87SLuiz Capitulino         info->has_family = true;
4302b54aa87SLuiz Capitulino 
4312b54aa87SLuiz Capitulino         info->has_auth = true;
432d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4333e230dd2SCorentin Chary     }
4342b54aa87SLuiz Capitulino 
435bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4362b54aa87SLuiz Capitulino     return info;
4372b54aa87SLuiz Capitulino 
4382b54aa87SLuiz Capitulino out_error:
439bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4402b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4412b54aa87SLuiz Capitulino     return NULL;
4423e230dd2SCorentin Chary }
4433e230dd2SCorentin Chary 
4442a7e6857SDaniel P. Berrange 
4452a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4462a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4472a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4482a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt);
4492a7e6857SDaniel P. Berrange 
4502a7e6857SDaniel P. Berrange static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
4514478aa76SGerd Hoffmann                                                   bool websocket,
4522a7e6857SDaniel P. Berrange                                                   int auth,
4532a7e6857SDaniel P. Berrange                                                   int subauth,
4542a7e6857SDaniel P. Berrange                                                   VncServerInfo2List *prev)
455df887684SGerd Hoffmann {
4562a7e6857SDaniel P. Berrange     VncServerInfo2 *info;
45704d2529dSDaniel P. Berrange     Error *err = NULL;
458bd269ebcSMarkus Armbruster     SocketAddress *addr;
459df887684SGerd Hoffmann 
4609261ef5eSMarkus Armbruster     addr = qio_channel_socket_get_local_address(ioc, NULL);
46104d2529dSDaniel P. Berrange     if (!addr) {
462df887684SGerd Hoffmann         return prev;
463df887684SGerd Hoffmann     }
464df887684SGerd Hoffmann 
4652a7e6857SDaniel P. Berrange     info = g_new0(VncServerInfo2, 1);
4662a7e6857SDaniel P. Berrange     vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
467bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
46804d2529dSDaniel P. Berrange     if (err) {
4692a7e6857SDaniel P. Berrange         qapi_free_VncServerInfo2(info);
47004d2529dSDaniel P. Berrange         error_free(err);
47104d2529dSDaniel P. Berrange         return prev;
47204d2529dSDaniel P. Berrange     }
4734478aa76SGerd Hoffmann     info->websocket = websocket;
474df887684SGerd Hoffmann 
4752a7e6857SDaniel P. Berrange     qmp_query_auth(auth, subauth, &info->auth,
4762a7e6857SDaniel P. Berrange                    &info->vencrypt, &info->has_vencrypt);
4772a7e6857SDaniel P. Berrange 
47854aa3de7SEric Blake     QAPI_LIST_PREPEND(prev, info);
47954aa3de7SEric Blake     return prev;
480df887684SGerd Hoffmann }
481df887684SGerd Hoffmann 
4822a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4832a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4842a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4852a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt)
486df887684SGerd Hoffmann {
4872a7e6857SDaniel P. Berrange     switch (auth) {
488df887684SGerd Hoffmann     case VNC_AUTH_VNC:
4892a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VNC;
490df887684SGerd Hoffmann         break;
491df887684SGerd Hoffmann     case VNC_AUTH_RA2:
4922a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2;
493df887684SGerd Hoffmann         break;
494df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
4952a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
496df887684SGerd Hoffmann         break;
497df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
4982a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
499df887684SGerd Hoffmann         break;
500df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
5012a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
502df887684SGerd Hoffmann         break;
503df887684SGerd Hoffmann     case VNC_AUTH_TLS:
5042a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TLS;
505df887684SGerd Hoffmann         break;
506df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
5072a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
5082a7e6857SDaniel P. Berrange         *qmp_has_vencrypt = true;
5092a7e6857SDaniel P. Berrange         switch (subauth) {
510df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
5112a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
512df887684SGerd Hoffmann             break;
513df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
5142a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
515df887684SGerd Hoffmann             break;
516df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
5172a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
518df887684SGerd Hoffmann             break;
519df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
5202a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
521df887684SGerd Hoffmann             break;
522df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
5232a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
524df887684SGerd Hoffmann             break;
525df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
5262a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
527df887684SGerd Hoffmann             break;
528df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
5292a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
530df887684SGerd Hoffmann             break;
531df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
5322a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
533df887684SGerd Hoffmann             break;
534df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
5352a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
536df887684SGerd Hoffmann             break;
537df887684SGerd Hoffmann         default:
5382a7e6857SDaniel P. Berrange             *qmp_has_vencrypt = false;
539df887684SGerd Hoffmann             break;
540df887684SGerd Hoffmann         }
541df887684SGerd Hoffmann         break;
542df887684SGerd Hoffmann     case VNC_AUTH_SASL:
5432a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_SASL;
544df887684SGerd Hoffmann         break;
545df887684SGerd Hoffmann     case VNC_AUTH_NONE:
546df887684SGerd Hoffmann     default:
5472a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_NONE;
548df887684SGerd Hoffmann         break;
549df887684SGerd Hoffmann     }
550df887684SGerd Hoffmann }
551df887684SGerd Hoffmann 
552df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
553df887684SGerd Hoffmann {
55454aa3de7SEric Blake     VncInfo2List *prev = NULL;
555df887684SGerd Hoffmann     VncInfo2 *info;
556df887684SGerd Hoffmann     VncDisplay *vd;
557df887684SGerd Hoffmann     DeviceState *dev;
5584ee74fa7SDaniel P. Berrange     size_t i;
559df887684SGerd Hoffmann 
560df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
561df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
562df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
563df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
5642a7e6857SDaniel P. Berrange         qmp_query_auth(vd->auth, vd->subauth, &info->auth,
5652a7e6857SDaniel P. Berrange                        &info->vencrypt, &info->has_vencrypt);
566df887684SGerd Hoffmann         if (vd->dcl.con) {
567df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
568552d7f49SMarkus Armbruster                                                   "device", &error_abort));
569df887684SGerd Hoffmann             info->has_display = true;
570df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
571df887684SGerd Hoffmann         }
57213e1d0e7SDaniel P. Berrange         for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
57304d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57413e1d0e7SDaniel P. Berrange                 vd->listener->sioc[i], false, vd->auth, vd->subauth,
57513e1d0e7SDaniel P. Berrange                 info->server);
576df887684SGerd Hoffmann         }
57713e1d0e7SDaniel P. Berrange         for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
57804d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57913e1d0e7SDaniel P. Berrange                 vd->wslistener->sioc[i], true, vd->ws_auth,
5804ee74fa7SDaniel P. Berrange                 vd->ws_subauth, info->server);
581df887684SGerd Hoffmann         }
582df887684SGerd Hoffmann 
58354aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, info);
584df887684SGerd Hoffmann     }
585df887684SGerd Hoffmann     return prev;
586df887684SGerd Hoffmann }
587df887684SGerd Hoffmann 
5883e230dd2SCorentin Chary /* TODO
5893e230dd2SCorentin Chary    1) Get the queue working for IO.
5903e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
5913e230dd2SCorentin Chary       and not totally invalidated
5923e230dd2SCorentin Chary    3) resolutions > 1024
5933e230dd2SCorentin Chary */
5943e230dd2SCorentin Chary 
5956af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty);
5963e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
5973e230dd2SCorentin Chary 
5983e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
5993e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
6003e230dd2SCorentin Chary                                        int x_position, int y_position,
6013e230dd2SCorentin Chary                                        int w, int h);
6020f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
6033e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
6043e230dd2SCorentin Chary 
605d05959c2SGerd Hoffmann static int vnc_width(VncDisplay *vd)
606d05959c2SGerd Hoffmann {
607d05959c2SGerd Hoffmann     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
608d05959c2SGerd Hoffmann                                        VNC_DIRTY_PIXELS_PER_BIT));
609d05959c2SGerd Hoffmann }
610d05959c2SGerd Hoffmann 
611*69cc8db4SDaniel P. Berrangé static int vnc_true_width(VncDisplay *vd)
612*69cc8db4SDaniel P. Berrangé {
613*69cc8db4SDaniel P. Berrangé     return MIN(VNC_MAX_WIDTH, surface_width(vd->ds));
614*69cc8db4SDaniel P. Berrangé }
615*69cc8db4SDaniel P. Berrangé 
616d05959c2SGerd Hoffmann static int vnc_height(VncDisplay *vd)
617d05959c2SGerd Hoffmann {
618d05959c2SGerd Hoffmann     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
619d05959c2SGerd Hoffmann }
620d05959c2SGerd Hoffmann 
621bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
622bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
623f7b3d68cSGerd Hoffmann                                VncDisplay *vd,
624f7b3d68cSGerd Hoffmann                                int x, int y, int w, int h)
625f7b3d68cSGerd Hoffmann {
626f7b3d68cSGerd Hoffmann     int width = vnc_width(vd);
627f7b3d68cSGerd Hoffmann     int height = vnc_height(vd);
628f7b3d68cSGerd Hoffmann 
62991937225SPeter Lieven     /* this is needed this to ensure we updated all affected
63091937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
631b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
632b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6333e230dd2SCorentin Chary 
6349f64916dSGerd Hoffmann     x = MIN(x, width);
6359f64916dSGerd Hoffmann     y = MIN(y, height);
6369f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
63791937225SPeter Lieven     h = MIN(y + h, height);
6383e230dd2SCorentin Chary 
639b4c85ddcSPeter Lieven     for (; y < h; y++) {
640bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
64191937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
642b4c85ddcSPeter Lieven     }
6433e230dd2SCorentin Chary }
6443e230dd2SCorentin Chary 
645bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
646bea60dd7SPeter Lieven                            int x, int y, int w, int h)
647bea60dd7SPeter Lieven {
648bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
649bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
650bea60dd7SPeter Lieven 
651f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
652bea60dd7SPeter Lieven }
653bea60dd7SPeter Lieven 
6543e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6553e230dd2SCorentin Chary                             int32_t encoding)
6563e230dd2SCorentin Chary {
6573e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6583e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6593e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6603e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6613e230dd2SCorentin Chary 
6623e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6633e230dd2SCorentin Chary }
6643e230dd2SCorentin Chary 
665763deea7SGerd Hoffmann static void vnc_desktop_resize_ext(VncState *vs, int reject_reason)
666763deea7SGerd Hoffmann {
667adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_ext_desktop_resize(
668adc8fce8SDaniel P. Berrangé         vs, vs->ioc, vs->client_width, vs->client_height, reject_reason);
669adc8fce8SDaniel P. Berrangé 
670763deea7SGerd Hoffmann     vnc_lock_output(vs);
671763deea7SGerd Hoffmann     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
672763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);
673763deea7SGerd Hoffmann     vnc_write_u16(vs, 1); /* number of rects */
674763deea7SGerd Hoffmann     vnc_framebuffer_update(vs,
675763deea7SGerd Hoffmann                            reject_reason ? 1 : 0,
676763deea7SGerd Hoffmann                            reject_reason,
677763deea7SGerd Hoffmann                            vs->client_width, vs->client_height,
678763deea7SGerd Hoffmann                            VNC_ENCODING_DESKTOP_RESIZE_EXT);
679763deea7SGerd Hoffmann     vnc_write_u8(vs, 1);  /* number of screens */
680763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
681763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
682763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
683763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen id */
684763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen x-pos */
685763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen y-pos */
686763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_width);
687763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_height);
688763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen flags */
689763deea7SGerd Hoffmann     vnc_unlock_output(vs);
690763deea7SGerd Hoffmann     vnc_flush(vs);
691763deea7SGerd Hoffmann }
69232ed2680STim Hardeck 
6933e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
6943e230dd2SCorentin Chary {
695763deea7SGerd Hoffmann     if (vs->ioc == NULL || (!vnc_has_feature(vs, VNC_FEATURE_RESIZE) &&
696763deea7SGerd Hoffmann                             !vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT))) {
6973e230dd2SCorentin Chary         return;
6983e230dd2SCorentin Chary     }
699*69cc8db4SDaniel P. Berrangé     if (vs->client_width == vs->vd->true_width &&
700d239726cSGerd Hoffmann         vs->client_height == pixman_image_get_height(vs->vd->server)) {
701d239726cSGerd Hoffmann         return;
702d239726cSGerd Hoffmann     }
7034c956bd8SDaniel P. Berrange 
704*69cc8db4SDaniel P. Berrangé     assert(vs->vd->true_width < 65536 &&
705*69cc8db4SDaniel P. Berrangé            vs->vd->true_width >= 0);
7064c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
7074c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
708*69cc8db4SDaniel P. Berrangé     vs->client_width = vs->vd->true_width;
709bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
710763deea7SGerd Hoffmann 
711763deea7SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
712763deea7SGerd Hoffmann         vnc_desktop_resize_ext(vs, 0);
713763deea7SGerd Hoffmann         return;
714763deea7SGerd Hoffmann     }
715763deea7SGerd Hoffmann 
716adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_desktop_resize(
717adc8fce8SDaniel P. Berrangé         vs, vs->ioc, vs->client_width, vs->client_height);
718adc8fce8SDaniel P. Berrangé 
719bd023f95SCorentin Chary     vnc_lock_output(vs);
7203e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
7213e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
7223e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
7233e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
7243e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
725bd023f95SCorentin Chary     vnc_unlock_output(vs);
7263e230dd2SCorentin Chary     vnc_flush(vs);
7273e230dd2SCorentin Chary }
7283e230dd2SCorentin Chary 
729bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
730bd023f95SCorentin Chary {
731bd023f95SCorentin Chary     VncState *vs;
732bd023f95SCorentin Chary 
733bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
734bd023f95SCorentin Chary         vnc_lock_output(vs);
735bd023f95SCorentin Chary         vs->abort = true;
736bd023f95SCorentin Chary         vnc_unlock_output(vs);
737bd023f95SCorentin Chary     }
738bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
739bd023f95SCorentin Chary         vnc_jobs_join(vs);
740bd023f95SCorentin Chary     }
741bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
742bd023f95SCorentin Chary         vnc_lock_output(vs);
743bbcdeb62SGerd Hoffmann         if (vs->update == VNC_STATE_UPDATE_NONE &&
744bbcdeb62SGerd Hoffmann             vs->job_update != VNC_STATE_UPDATE_NONE) {
745bbcdeb62SGerd Hoffmann             /* job aborted before completion */
746bbcdeb62SGerd Hoffmann             vs->update = vs->job_update;
747bbcdeb62SGerd Hoffmann             vs->job_update = VNC_STATE_UPDATE_NONE;
748bbcdeb62SGerd Hoffmann         }
749bd023f95SCorentin Chary         vs->abort = false;
750bd023f95SCorentin Chary         vnc_unlock_output(vs);
751bd023f95SCorentin Chary     }
752bd023f95SCorentin Chary }
753bd023f95SCorentin Chary 
7549f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
7559f64916dSGerd Hoffmann {
7569f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
7579f64916dSGerd Hoffmann }
7589f64916dSGerd Hoffmann 
7599f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
7609f64916dSGerd Hoffmann {
7619f64916dSGerd Hoffmann     uint8_t *ptr;
7629f64916dSGerd Hoffmann 
7639f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
7649f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
7659f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
7669f64916dSGerd Hoffmann     return ptr;
7679f64916dSGerd Hoffmann }
7689f64916dSGerd Hoffmann 
769453f842bSGerd Hoffmann static void vnc_update_server_surface(VncDisplay *vd)
770453f842bSGerd Hoffmann {
771b69a553bSDaniel P. Berrange     int width, height;
772b69a553bSDaniel P. Berrange 
773453f842bSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
774453f842bSGerd Hoffmann     vd->server = NULL;
775453f842bSGerd Hoffmann 
776c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vd->clients)) {
777c7628bffSGerd Hoffmann         return;
778c7628bffSGerd Hoffmann     }
779c7628bffSGerd Hoffmann 
780b69a553bSDaniel P. Berrange     width = vnc_width(vd);
781b69a553bSDaniel P. Berrange     height = vnc_height(vd);
782*69cc8db4SDaniel P. Berrangé     vd->true_width = vnc_true_width(vd);
783453f842bSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
784b69a553bSDaniel P. Berrange                                           width, height,
785453f842bSGerd Hoffmann                                           NULL, 0);
786b69a553bSDaniel P. Berrange 
787b69a553bSDaniel P. Berrange     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
788b69a553bSDaniel P. Berrange     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
789b69a553bSDaniel P. Berrange                        width, height);
790453f842bSGerd Hoffmann }
791453f842bSGerd Hoffmann 
79261e77a5fSGerd Hoffmann static bool vnc_check_pageflip(DisplaySurface *s1,
79361e77a5fSGerd Hoffmann                                DisplaySurface *s2)
79461e77a5fSGerd Hoffmann {
79561e77a5fSGerd Hoffmann     return (s1 != NULL &&
79661e77a5fSGerd Hoffmann             s2 != NULL &&
79761e77a5fSGerd Hoffmann             surface_width(s1) == surface_width(s2) &&
79861e77a5fSGerd Hoffmann             surface_height(s1) == surface_height(s2) &&
79961e77a5fSGerd Hoffmann             surface_format(s1) == surface_format(s2));
80061e77a5fSGerd Hoffmann 
80161e77a5fSGerd Hoffmann }
80261e77a5fSGerd Hoffmann 
803c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
804c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
8053e230dd2SCorentin Chary {
80621ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
80761e77a5fSGerd Hoffmann     bool pageflip = vnc_check_pageflip(vd->ds, surface);
8083e230dd2SCorentin Chary     VncState *vs;
8093e230dd2SCorentin Chary 
810bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
811453f842bSGerd Hoffmann     vd->ds = surface;
812bd023f95SCorentin Chary 
8133e230dd2SCorentin Chary     /* guest surface */
8149f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
815d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
816d39fa6d8SGerd Hoffmann     vd->guest.format = surface->format;
8173e230dd2SCorentin Chary 
818*69cc8db4SDaniel P. Berrangé 
81961e77a5fSGerd Hoffmann     if (pageflip) {
820*69cc8db4SDaniel P. Berrangé         trace_vnc_server_dpy_pageflip(vd,
821*69cc8db4SDaniel P. Berrangé                                       surface_width(surface),
822*69cc8db4SDaniel P. Berrangé                                       surface_height(surface),
823*69cc8db4SDaniel P. Berrangé                                       surface_format(surface));
82461e77a5fSGerd Hoffmann         vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
82561e77a5fSGerd Hoffmann                            surface_width(surface),
82661e77a5fSGerd Hoffmann                            surface_height(surface));
82761e77a5fSGerd Hoffmann         return;
82861e77a5fSGerd Hoffmann     }
82961e77a5fSGerd Hoffmann 
830*69cc8db4SDaniel P. Berrangé     trace_vnc_server_dpy_recreate(vd,
831*69cc8db4SDaniel P. Berrangé                                   surface_width(surface),
832*69cc8db4SDaniel P. Berrangé                                   surface_height(surface),
833*69cc8db4SDaniel P. Berrangé                                   surface_format(surface));
83461e77a5fSGerd Hoffmann     /* server surface */
83561e77a5fSGerd Hoffmann     vnc_update_server_surface(vd);
83661e77a5fSGerd Hoffmann 
8373e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
8383e230dd2SCorentin Chary         vnc_colordepth(vs);
8393e230dd2SCorentin Chary         vnc_desktop_resize(vs);
8403e230dd2SCorentin Chary         vnc_cursor_define(vs);
841bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
842f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
843b69a553bSDaniel P. Berrange                            vnc_width(vd),
844b69a553bSDaniel P. Berrange                            vnc_height(vd));
845e2b72cb6SDaniel P. Berrange         vnc_update_throttle_offset(vs);
8463e230dd2SCorentin Chary     }
8473e230dd2SCorentin Chary }
8483e230dd2SCorentin Chary 
8493e230dd2SCorentin Chary /* fastest code */
8509f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
8513e230dd2SCorentin Chary                                   void *pixels, int size)
8523e230dd2SCorentin Chary {
8533e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
8543e230dd2SCorentin Chary }
8553e230dd2SCorentin Chary 
8563e230dd2SCorentin Chary /* slowest but generic code. */
8573e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
8583e230dd2SCorentin Chary {
8593e230dd2SCorentin Chary     uint8_t r, g, b;
8603e230dd2SCorentin Chary 
8619f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
8629f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
8639f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
8649f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
8659f64916dSGerd Hoffmann #else
8669f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
8679f64916dSGerd Hoffmann #endif
8689f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
8699f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
8709f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
8719f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
8723e230dd2SCorentin Chary     case 1:
8733e230dd2SCorentin Chary         buf[0] = v;
8743e230dd2SCorentin Chary         break;
8753e230dd2SCorentin Chary     case 2:
8769f64916dSGerd Hoffmann         if (vs->client_be) {
8773e230dd2SCorentin Chary             buf[0] = v >> 8;
8783e230dd2SCorentin Chary             buf[1] = v;
8793e230dd2SCorentin Chary         } else {
8803e230dd2SCorentin Chary             buf[1] = v >> 8;
8813e230dd2SCorentin Chary             buf[0] = v;
8823e230dd2SCorentin Chary         }
8833e230dd2SCorentin Chary         break;
8843e230dd2SCorentin Chary     default:
8853e230dd2SCorentin Chary     case 4:
8869f64916dSGerd Hoffmann         if (vs->client_be) {
8873e230dd2SCorentin Chary             buf[0] = v >> 24;
8883e230dd2SCorentin Chary             buf[1] = v >> 16;
8893e230dd2SCorentin Chary             buf[2] = v >> 8;
8903e230dd2SCorentin Chary             buf[3] = v;
8913e230dd2SCorentin Chary         } else {
8923e230dd2SCorentin Chary             buf[3] = v >> 24;
8933e230dd2SCorentin Chary             buf[2] = v >> 16;
8943e230dd2SCorentin Chary             buf[1] = v >> 8;
8953e230dd2SCorentin Chary             buf[0] = v;
8963e230dd2SCorentin Chary         }
8973e230dd2SCorentin Chary         break;
8983e230dd2SCorentin Chary     }
8993e230dd2SCorentin Chary }
9003e230dd2SCorentin Chary 
9019f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
9023e230dd2SCorentin Chary                                      void *pixels1, int size)
9033e230dd2SCorentin Chary {
9043e230dd2SCorentin Chary     uint8_t buf[4];
9053e230dd2SCorentin Chary 
9069f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
9073e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
9083e230dd2SCorentin Chary         int n, i;
9093e230dd2SCorentin Chary         n = size >> 2;
9103e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
9113e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
9129f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
9133e230dd2SCorentin Chary         }
9143e230dd2SCorentin Chary     }
9153e230dd2SCorentin Chary }
9163e230dd2SCorentin Chary 
9173e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9183e230dd2SCorentin Chary {
9193e230dd2SCorentin Chary     int i;
9203e230dd2SCorentin Chary     uint8_t *row;
9213e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
9223e230dd2SCorentin Chary 
9239f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
9243e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
9259f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
9269f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
9273e230dd2SCorentin Chary     }
9283e230dd2SCorentin Chary     return 1;
9293e230dd2SCorentin Chary }
9303e230dd2SCorentin Chary 
931bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9323e230dd2SCorentin Chary {
9333e230dd2SCorentin Chary     int n = 0;
9343e230dd2SCorentin Chary 
9353e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
9363e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
9373e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
9383e230dd2SCorentin Chary             break;
9393e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
9403e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
9413e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
9423e230dd2SCorentin Chary             break;
9433e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
9443e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
9453e230dd2SCorentin Chary             break;
946efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
947efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
948efe556adSCorentin Chary             break;
949148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
950148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
951148954faSCorentin Chary             break;
952148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
953148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
954148954faSCorentin Chary             break;
9553e230dd2SCorentin Chary         default:
956de3f7de7SPeter Lieven             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
957de3f7de7SPeter Lieven             n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
9580780ec7bSGerd Hoffmann             break;
959de3f7de7SPeter Lieven     }
9603e230dd2SCorentin Chary     return n;
9613e230dd2SCorentin Chary }
9623e230dd2SCorentin Chary 
9637c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9647c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9653e230dd2SCorentin Chary {
9663e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9673e230dd2SCorentin Chary }
9683e230dd2SCorentin Chary 
9693e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
9703e230dd2SCorentin Chary {
9713e230dd2SCorentin Chary     QEMUCursor *c = vs->vd->cursor;
9723e230dd2SCorentin Chary     int isize;
9733e230dd2SCorentin Chary 
974b3c2de9cSGerd Hoffmann     if (!vs->vd->cursor) {
975b3c2de9cSGerd Hoffmann         return -1;
976b3c2de9cSGerd Hoffmann     }
977b3c2de9cSGerd Hoffmann 
978074a86d0SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
979074a86d0SGerd Hoffmann         vnc_lock_output(vs);
980074a86d0SGerd Hoffmann         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
981074a86d0SGerd Hoffmann         vnc_write_u8(vs,  0);  /*  padding     */
982074a86d0SGerd Hoffmann         vnc_write_u16(vs, 1);  /*  # of rects  */
983074a86d0SGerd Hoffmann         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
984074a86d0SGerd Hoffmann                                VNC_ENCODING_ALPHA_CURSOR);
985074a86d0SGerd Hoffmann         vnc_write_s32(vs, VNC_ENCODING_RAW);
986074a86d0SGerd Hoffmann         vnc_write(vs, c->data, c->width * c->height * 4);
987074a86d0SGerd Hoffmann         vnc_unlock_output(vs);
988074a86d0SGerd Hoffmann         return 0;
989074a86d0SGerd Hoffmann     }
9903e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
991d01f9595SCorentin Chary         vnc_lock_output(vs);
9923e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
9933e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
9943e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
9953e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
9963e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
9979f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
9989f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
9993e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
1000d01f9595SCorentin Chary         vnc_unlock_output(vs);
10013e230dd2SCorentin Chary         return 0;
10023e230dd2SCorentin Chary     }
10033e230dd2SCorentin Chary     return -1;
10043e230dd2SCorentin Chary }
10053e230dd2SCorentin Chary 
10067c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
10077c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
10083e230dd2SCorentin Chary {
1009d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
10103e230dd2SCorentin Chary     VncState *vs;
10113e230dd2SCorentin Chary 
10123e230dd2SCorentin Chary     cursor_put(vd->cursor);
10137267c094SAnthony Liguori     g_free(vd->cursor_mask);
10143e230dd2SCorentin Chary 
10153e230dd2SCorentin Chary     vd->cursor = c;
10163e230dd2SCorentin Chary     cursor_get(vd->cursor);
10173e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
10187267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
10193e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
10203e230dd2SCorentin Chary 
10213e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
10223e230dd2SCorentin Chary         vnc_cursor_define(vs);
10233e230dd2SCorentin Chary     }
10243e230dd2SCorentin Chary }
10253e230dd2SCorentin Chary 
10264769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
10276c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
10283e230dd2SCorentin Chary {
10293e230dd2SCorentin Chary     int h;
10303e230dd2SCorentin Chary 
10316c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
1032bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
10333e230dd2SCorentin Chary             break;
1034bc2429b9SCorentin Chary         }
1035863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
10363e230dd2SCorentin Chary     }
10373e230dd2SCorentin Chary 
10383e230dd2SCorentin Chary     return h;
10393e230dd2SCorentin Chary }
10403e230dd2SCorentin Chary 
1041e2b72cb6SDaniel P. Berrange /*
1042e2b72cb6SDaniel P. Berrange  * Figure out how much pending data we should allow in the output
1043e2b72cb6SDaniel P. Berrange  * buffer before we throttle incremental display updates, and/or
1044e2b72cb6SDaniel P. Berrange  * drop audio samples.
1045e2b72cb6SDaniel P. Berrange  *
1046e2b72cb6SDaniel P. Berrange  * We allow for equiv of 1 full display's worth of FB updates,
1047e2b72cb6SDaniel P. Berrange  * and 1 second of audio samples. If audio backlog was larger
1048e2b72cb6SDaniel P. Berrange  * than that the client would already suffering awful audio
1049e2b72cb6SDaniel P. Berrange  * glitches, so dropping samples is no worse really).
1050e2b72cb6SDaniel P. Berrange  */
1051e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs)
1052e2b72cb6SDaniel P. Berrange {
1053e2b72cb6SDaniel P. Berrange     size_t offset =
1054e2b72cb6SDaniel P. Berrange         vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1055e2b72cb6SDaniel P. Berrange 
1056e2b72cb6SDaniel P. Berrange     if (vs->audio_cap) {
1057e2b72cb6SDaniel P. Berrange         int bps;
1058e2b72cb6SDaniel P. Berrange         switch (vs->as.fmt) {
1059e2b72cb6SDaniel P. Berrange         default:
106085bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U8:
106185bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S8:
1062e2b72cb6SDaniel P. Berrange             bps = 1;
1063e2b72cb6SDaniel P. Berrange             break;
106485bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U16:
106585bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S16:
1066e2b72cb6SDaniel P. Berrange             bps = 2;
1067e2b72cb6SDaniel P. Berrange             break;
106885bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U32:
106985bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S32:
1070e2b72cb6SDaniel P. Berrange             bps = 4;
1071e2b72cb6SDaniel P. Berrange             break;
1072e2b72cb6SDaniel P. Berrange         }
1073cf070658SDaniel P. Berrangé         offset += vs->as.freq * bps * vs->as.nchannels;
1074e2b72cb6SDaniel P. Berrange     }
1075e2b72cb6SDaniel P. Berrange 
1076e2b72cb6SDaniel P. Berrange     /* Put a floor of 1MB on offset, so that if we have a large pending
1077e2b72cb6SDaniel P. Berrange      * buffer and the display is resized to a small size & back again
1078e2b72cb6SDaniel P. Berrange      * we don't suddenly apply a tiny send limit
1079e2b72cb6SDaniel P. Berrange      */
1080e2b72cb6SDaniel P. Berrange     offset = MAX(offset, 1024 * 1024);
1081e2b72cb6SDaniel P. Berrange 
10826aa22a29SDaniel P. Berrange     if (vs->throttle_output_offset != offset) {
10836aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_threshold(
10846aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
10856aa22a29SDaniel P. Berrange             vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
10866aa22a29SDaniel P. Berrange     }
10876aa22a29SDaniel P. Berrange 
1088e2b72cb6SDaniel P. Berrange     vs->throttle_output_offset = offset;
1089e2b72cb6SDaniel P. Berrange }
1090e2b72cb6SDaniel P. Berrange 
10910bad8342SDaniel P. Berrange static bool vnc_should_update(VncState *vs)
10920bad8342SDaniel P. Berrange {
10930bad8342SDaniel P. Berrange     switch (vs->update) {
10940bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_NONE:
10950bad8342SDaniel P. Berrange         break;
10960bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_INCREMENTAL:
1097e2b72cb6SDaniel P. Berrange         /* Only allow incremental updates if the pending send queue
1098ada8d2e4SDaniel P. Berrange          * is less than the permitted threshold, and the job worker
1099ada8d2e4SDaniel P. Berrange          * is completely idle.
11000bad8342SDaniel P. Berrange          */
1101ada8d2e4SDaniel P. Berrange         if (vs->output.offset < vs->throttle_output_offset &&
1102ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
11030bad8342SDaniel P. Berrange             return true;
11040bad8342SDaniel P. Berrange         }
11056aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_incremental(
11066aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->output.offset);
11070bad8342SDaniel P. Berrange         break;
11080bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_FORCE:
1109ada8d2e4SDaniel P. Berrange         /* Only allow forced updates if the pending send queue
1110ada8d2e4SDaniel P. Berrange          * does not contain a previous forced update, and the
1111ada8d2e4SDaniel P. Berrange          * job worker is completely idle.
1112ada8d2e4SDaniel P. Berrange          *
1113ada8d2e4SDaniel P. Berrange          * Note this means we'll queue a forced update, even if
1114ada8d2e4SDaniel P. Berrange          * the output buffer size is otherwise over the throttle
1115ada8d2e4SDaniel P. Berrange          * output limit.
1116ada8d2e4SDaniel P. Berrange          */
1117ada8d2e4SDaniel P. Berrange         if (vs->force_update_offset == 0 &&
1118ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
11190bad8342SDaniel P. Berrange             return true;
11200bad8342SDaniel P. Berrange         }
11216aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_forced(
11226aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->force_update_offset);
1123ada8d2e4SDaniel P. Berrange         break;
1124ada8d2e4SDaniel P. Berrange     }
11250bad8342SDaniel P. Berrange     return false;
11260bad8342SDaniel P. Berrange }
11270bad8342SDaniel P. Berrange 
11286af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty)
11293e230dd2SCorentin Chary {
11303e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
1131bd023f95SCorentin Chary     VncJob *job;
11323e230dd2SCorentin Chary     int y;
11332f487a3dSPeter Lieven     int height, width;
1134bd023f95SCorentin Chary     int n = 0;
1135bd023f95SCorentin Chary 
1136b939eb89SDaniel P. Berrange     if (vs->disconnecting) {
1137b939eb89SDaniel P. Berrange         vnc_disconnect_finish(vs);
1138b939eb89SDaniel P. Berrange         return 0;
1139b939eb89SDaniel P. Berrange     }
1140b939eb89SDaniel P. Berrange 
1141b939eb89SDaniel P. Berrange     vs->has_dirty += has_dirty;
11420bad8342SDaniel P. Berrange     if (!vnc_should_update(vs)) {
11433e230dd2SCorentin Chary         return 0;
1144b939eb89SDaniel P. Berrange     }
11453e230dd2SCorentin Chary 
1146fef1bbadSDaniel P. Berrange     if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
11473e230dd2SCorentin Chary         return 0;
1148b939eb89SDaniel P. Berrange     }
11493e230dd2SCorentin Chary 
11503e230dd2SCorentin Chary     /*
11513e230dd2SCorentin Chary      * Send screen updates to the vnc client using the server
11523e230dd2SCorentin Chary      * surface and server dirty map.  guest surface updates
11533e230dd2SCorentin Chary      * happening in parallel don't disturb us, the next pass will
11543e230dd2SCorentin Chary      * send them to the client.
11553e230dd2SCorentin Chary      */
1156bd023f95SCorentin Chary     job = vnc_job_new(vs);
11573e230dd2SCorentin Chary 
1158bea60dd7SPeter Lieven     height = pixman_image_get_height(vd->server);
1159bea60dd7SPeter Lieven     width = pixman_image_get_width(vd->server);
11603e230dd2SCorentin Chary 
116112b316d4SPeter Lieven     y = 0;
116212b316d4SPeter Lieven     for (;;) {
116312b316d4SPeter Lieven         int x, h;
116412b316d4SPeter Lieven         unsigned long x2;
116512b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
116612b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(vs),
116712b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(vs));
116812b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(vs)) {
116912b316d4SPeter Lieven             /* no more dirty bits */
117012b316d4SPeter Lieven             break;
11713e230dd2SCorentin Chary         }
117212b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(vs);
117312b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(vs);
117412b316d4SPeter Lieven         x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
117512b316d4SPeter Lieven                                 VNC_DIRTY_BPL(vs), x);
117612b316d4SPeter Lieven         bitmap_clear(vs->dirty[y], x, x2 - x);
117712b316d4SPeter Lieven         h = find_and_clear_dirty_height(vs, y, x, x2, height);
11782f487a3dSPeter Lieven         x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
11792f487a3dSPeter Lieven         if (x2 > x) {
118012b316d4SPeter Lieven             n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
118112b316d4SPeter Lieven                                   (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
11823e230dd2SCorentin Chary         }
11830e7d6f60SPeter Lieven         if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
11840e7d6f60SPeter Lieven             y += h;
11850e7d6f60SPeter Lieven             if (y == height) {
11860e7d6f60SPeter Lieven                 break;
11870e7d6f60SPeter Lieven             }
11880e7d6f60SPeter Lieven         }
11892f487a3dSPeter Lieven     }
1190bd023f95SCorentin Chary 
1191ada8d2e4SDaniel P. Berrange     vs->job_update = vs->update;
1192728a7ac9SDaniel P. Berrange     vs->update = VNC_STATE_UPDATE_NONE;
1193ada8d2e4SDaniel P. Berrange     vnc_job_push(job);
119463658280SGerd Hoffmann     vs->has_dirty = 0;
1195bd023f95SCorentin Chary     return n;
11963e230dd2SCorentin Chary }
11973e230dd2SCorentin Chary 
11983e230dd2SCorentin Chary /* audio */
11993e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
12003e230dd2SCorentin Chary {
12013e230dd2SCorentin Chary     VncState *vs = opaque;
12023e230dd2SCorentin Chary 
1203f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
12043e230dd2SCorentin Chary     switch (cmd) {
12053e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1206adc8fce8SDaniel P. Berrangé         trace_vnc_msg_server_audio_end(vs, vs->ioc);
1207bd023f95SCorentin Chary         vnc_lock_output(vs);
12083e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12093e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12103e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1211bd023f95SCorentin Chary         vnc_unlock_output(vs);
12123e230dd2SCorentin Chary         vnc_flush(vs);
12133e230dd2SCorentin Chary         break;
12143e230dd2SCorentin Chary 
12153e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1216adc8fce8SDaniel P. Berrangé         trace_vnc_msg_server_audio_begin(vs, vs->ioc);
1217bd023f95SCorentin Chary         vnc_lock_output(vs);
12183e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12193e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12203e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1221bd023f95SCorentin Chary         vnc_unlock_output(vs);
12223e230dd2SCorentin Chary         vnc_flush(vs);
12233e230dd2SCorentin Chary         break;
12243e230dd2SCorentin Chary     }
12253e230dd2SCorentin Chary }
12263e230dd2SCorentin Chary 
12273e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
12283e230dd2SCorentin Chary {
12293e230dd2SCorentin Chary }
12303e230dd2SCorentin Chary 
123157a878edSPhilippe Mathieu-Daudé static void audio_capture(void *opaque, const void *buf, int size)
12323e230dd2SCorentin Chary {
12333e230dd2SCorentin Chary     VncState *vs = opaque;
12343e230dd2SCorentin Chary 
1235f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1236adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_audio_data(vs, vs->ioc, buf, size);
1237bd023f95SCorentin Chary     vnc_lock_output(vs);
1238e2b72cb6SDaniel P. Berrange     if (vs->output.offset < vs->throttle_output_offset) {
12393e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12403e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12413e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
12423e230dd2SCorentin Chary         vnc_write_u32(vs, size);
12433e230dd2SCorentin Chary         vnc_write(vs, buf, size);
12446aa22a29SDaniel P. Berrange     } else {
12456aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1246e2b72cb6SDaniel P. Berrange     }
1247bd023f95SCorentin Chary     vnc_unlock_output(vs);
12483e230dd2SCorentin Chary     vnc_flush(vs);
12493e230dd2SCorentin Chary }
12503e230dd2SCorentin Chary 
12513e230dd2SCorentin Chary static void audio_add(VncState *vs)
12523e230dd2SCorentin Chary {
12533e230dd2SCorentin Chary     struct audio_capture_ops ops;
12543e230dd2SCorentin Chary 
12553e230dd2SCorentin Chary     if (vs->audio_cap) {
1256027a79c3SCole Robinson         error_report("audio already running");
12573e230dd2SCorentin Chary         return;
12583e230dd2SCorentin Chary     }
12593e230dd2SCorentin Chary 
12603e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
12613e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
12623e230dd2SCorentin Chary     ops.capture = audio_capture;
12633e230dd2SCorentin Chary 
1264f0b9f36dSKővágó, Zoltán     vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
12653e230dd2SCorentin Chary     if (!vs->audio_cap) {
1266027a79c3SCole Robinson         error_report("Failed to add audio capture");
12673e230dd2SCorentin Chary     }
12683e230dd2SCorentin Chary }
12693e230dd2SCorentin Chary 
12703e230dd2SCorentin Chary static void audio_del(VncState *vs)
12713e230dd2SCorentin Chary {
12723e230dd2SCorentin Chary     if (vs->audio_cap) {
12733e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
12743e230dd2SCorentin Chary         vs->audio_cap = NULL;
12753e230dd2SCorentin Chary     }
12763e230dd2SCorentin Chary }
12773e230dd2SCorentin Chary 
12783e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
12793e230dd2SCorentin Chary {
128004d2529dSDaniel P. Berrange     if (vs->disconnecting) {
12813e230dd2SCorentin Chary         return;
128204d2529dSDaniel P. Berrange     }
1283ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_start(vs, vs->ioc);
12848cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
128504d2529dSDaniel P. Berrange     if (vs->ioc_tag) {
128604d2529dSDaniel P. Berrange         g_source_remove(vs->ioc_tag);
1287a75d6f07SBrandon Carpenter         vs->ioc_tag = 0;
128804d2529dSDaniel P. Berrange     }
128904d2529dSDaniel P. Berrange     qio_channel_close(vs->ioc, NULL);
129004d2529dSDaniel P. Berrange     vs->disconnecting = TRUE;
12913e230dd2SCorentin Chary }
12923e230dd2SCorentin Chary 
12937536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
12943e230dd2SCorentin Chary {
12957d964c9dSCorentin Chary     int i;
12967d964c9dSCorentin Chary 
1297ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_finish(vs, vs->ioc);
1298ad6374c4SDaniel P. Berrange 
1299bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1300bd023f95SCorentin Chary 
1301bd023f95SCorentin Chary     vnc_lock_output(vs);
1302fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
13033e230dd2SCorentin Chary 
13043e230dd2SCorentin Chary     buffer_free(&vs->input);
13053e230dd2SCorentin Chary     buffer_free(&vs->output);
13063e230dd2SCorentin Chary 
1307fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
13083e230dd2SCorentin Chary 
13093e230dd2SCorentin Chary     vnc_zlib_clear(vs);
13103e230dd2SCorentin Chary     vnc_tight_clear(vs);
1311148954faSCorentin Chary     vnc_zrle_clear(vs);
13123e230dd2SCorentin Chary 
13133e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13143e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
13153e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13163e230dd2SCorentin Chary     audio_del(vs);
1317c2f2ba49SGerd Hoffmann     qkbd_state_lift_all_keys(vs->vd->kbd);
13183e230dd2SCorentin Chary 
131990cd03a3SDaniel P. Berrange     if (vs->mouse_mode_notifier.notify != NULL) {
13206fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
132190cd03a3SDaniel P. Berrange     }
132290cd03a3SDaniel P. Berrange     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1323c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1324c7628bffSGerd Hoffmann         /* last client gone */
1325c7628bffSGerd Hoffmann         vnc_update_server_surface(vs->vd);
1326c7628bffSGerd Hoffmann     }
13273e230dd2SCorentin Chary 
1328bd023f95SCorentin Chary     vnc_unlock_output(vs);
1329bd023f95SCorentin Chary 
1330bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
13316fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1332175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
13336fd8e79aSTim Hardeck     }
1334175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1335175b2a6eSCorentin Chary 
13367d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
13377267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
13387d964c9dSCorentin Chary     }
13397267c094SAnthony Liguori     g_free(vs->lossy_rect);
134004d2529dSDaniel P. Berrange 
134104d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->ioc));
134204d2529dSDaniel P. Berrange     vs->ioc = NULL;
134304d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->sioc));
134404d2529dSDaniel P. Berrange     vs->sioc = NULL;
1345f31f9c10SGerd Hoffmann     vs->magic = 0;
13466bf21f3dSLi Qiang     g_free(vs->zrle);
13476bf21f3dSLi Qiang     g_free(vs->tight);
13487267c094SAnthony Liguori     g_free(vs);
13493e230dd2SCorentin Chary }
13503e230dd2SCorentin Chary 
135134ab29c2SVladimir Sementsov-Ogievskiy size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
13523e230dd2SCorentin Chary {
135304d2529dSDaniel P. Berrange     if (ret <= 0) {
135404d2529dSDaniel P. Berrange         if (ret == 0) {
1355ad6374c4SDaniel P. Berrange             trace_vnc_client_eof(vs, vs->ioc);
1356537848eeSMichael Tokarev             vnc_disconnect_start(vs);
135704d2529dSDaniel P. Berrange         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1358ad6374c4SDaniel P. Berrange             trace_vnc_client_io_error(vs, vs->ioc,
135934ab29c2SVladimir Sementsov-Ogievskiy                                       err ? error_get_pretty(err) : "Unknown");
1360537848eeSMichael Tokarev             vnc_disconnect_start(vs);
13613e230dd2SCorentin Chary         }
13623e230dd2SCorentin Chary 
136334ab29c2SVladimir Sementsov-Ogievskiy         error_free(err);
13643e230dd2SCorentin Chary         return 0;
13653e230dd2SCorentin Chary     }
13663e230dd2SCorentin Chary     return ret;
13673e230dd2SCorentin Chary }
13683e230dd2SCorentin Chary 
13693e230dd2SCorentin Chary 
13703e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
13713e230dd2SCorentin Chary {
13723e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
13733e230dd2SCorentin Chary     vnc_disconnect_start(vs);
13743e230dd2SCorentin Chary }
13753e230dd2SCorentin Chary 
13763e305e4aSDaniel P. Berrange 
13773e230dd2SCorentin Chary /*
13783e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
13793e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
13803e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
13813e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
13823e230dd2SCorentin Chary  *
13833e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
13843e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
13853e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
13863e230dd2SCorentin Chary  * is active
13873e230dd2SCorentin Chary  *
13883e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13893e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
139030b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
13913e230dd2SCorentin Chary  */
139230b80fd5SDaniel P. Berrange size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
13933e230dd2SCorentin Chary {
139404d2529dSDaniel P. Berrange     Error *err = NULL;
1395fdd1ab6aSDaniel P. Berrange     ssize_t ret;
139634ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
13973e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
139834ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
13993e230dd2SCorentin Chary }
14003e230dd2SCorentin Chary 
14013e230dd2SCorentin Chary 
14023e230dd2SCorentin Chary /*
14033e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
14043e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
14053e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
14063e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
14073e230dd2SCorentin Chary  *
14083e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
14093e230dd2SCorentin Chary  * the buffered output data if the socket would block.  Returns
141030b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
14113e230dd2SCorentin Chary  */
141230b80fd5SDaniel P. Berrange static size_t vnc_client_write_plain(VncState *vs)
14133e230dd2SCorentin Chary {
14146aa22a29SDaniel P. Berrange     size_t offset;
141530b80fd5SDaniel P. Berrange     size_t ret;
14163e230dd2SCorentin Chary 
14173e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14183e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
14193e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
14203e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
14213e230dd2SCorentin Chary 
14223e230dd2SCorentin Chary     if (vs->sasl.conn &&
14233e230dd2SCorentin Chary         vs->sasl.runSSF &&
14243e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
14253e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
14263e230dd2SCorentin Chary         if (ret)
14273e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
14283e230dd2SCorentin Chary     } else
14293e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14303e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
14313e230dd2SCorentin Chary     if (!ret)
14323e230dd2SCorentin Chary         return 0;
14333e230dd2SCorentin Chary 
1434ada8d2e4SDaniel P. Berrange     if (ret >= vs->force_update_offset) {
14356aa22a29SDaniel P. Berrange         if (vs->force_update_offset != 0) {
14366aa22a29SDaniel P. Berrange             trace_vnc_client_unthrottle_forced(vs, vs->ioc);
14376aa22a29SDaniel P. Berrange         }
1438ada8d2e4SDaniel P. Berrange         vs->force_update_offset = 0;
1439ada8d2e4SDaniel P. Berrange     } else {
1440ada8d2e4SDaniel P. Berrange         vs->force_update_offset -= ret;
1441ada8d2e4SDaniel P. Berrange     }
14426aa22a29SDaniel P. Berrange     offset = vs->output.offset;
144332ed2680STim Hardeck     buffer_advance(&vs->output, ret);
14446aa22a29SDaniel P. Berrange     if (offset >= vs->throttle_output_offset &&
14456aa22a29SDaniel P. Berrange         vs->output.offset < vs->throttle_output_offset) {
14466aa22a29SDaniel P. Berrange         trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
14476aa22a29SDaniel P. Berrange     }
14483e230dd2SCorentin Chary 
14493e230dd2SCorentin Chary     if (vs->output.offset == 0) {
145004d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
145104d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
145204d2529dSDaniel P. Berrange         }
145304d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
14542ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
14552ddafce7SDing Hui             vnc_client_io, vs, NULL);
14563e230dd2SCorentin Chary     }
14573e230dd2SCorentin Chary 
14583e230dd2SCorentin Chary     return ret;
14593e230dd2SCorentin Chary }
14603e230dd2SCorentin Chary 
14613e230dd2SCorentin Chary 
14623e230dd2SCorentin Chary /*
14633e230dd2SCorentin Chary  * First function called whenever there is data to be written to
14643e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
14653e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
14663e230dd2SCorentin Chary  */
146704d2529dSDaniel P. Berrange static void vnc_client_write_locked(VncState *vs)
14683e230dd2SCorentin Chary {
14693e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14703e230dd2SCorentin Chary     if (vs->sasl.conn &&
14713e230dd2SCorentin Chary         vs->sasl.runSSF &&
14723e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
14733e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
14743e230dd2SCorentin Chary     } else
14753e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14767536ee4bSTim Hardeck     {
14773e230dd2SCorentin Chary         vnc_client_write_plain(vs);
14783e230dd2SCorentin Chary     }
14797536ee4bSTim Hardeck }
14803e230dd2SCorentin Chary 
148104d2529dSDaniel P. Berrange static void vnc_client_write(VncState *vs)
1482bd023f95SCorentin Chary {
1483f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1484bd023f95SCorentin Chary     vnc_lock_output(vs);
1485d5f04223SDaniel P. Berrange     if (vs->output.offset) {
148604d2529dSDaniel P. Berrange         vnc_client_write_locked(vs);
148704d2529dSDaniel P. Berrange     } else if (vs->ioc != NULL) {
148804d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
148904d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
149004d2529dSDaniel P. Berrange         }
149104d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
14922ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
14932ddafce7SDing Hui             vnc_client_io, vs, NULL);
1494bd023f95SCorentin Chary     }
1495bd023f95SCorentin Chary     vnc_unlock_output(vs);
1496bd023f95SCorentin Chary }
1497bd023f95SCorentin Chary 
14983e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
14993e230dd2SCorentin Chary {
15003e230dd2SCorentin Chary     vs->read_handler = func;
15013e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
15023e230dd2SCorentin Chary }
15033e230dd2SCorentin Chary 
15043e230dd2SCorentin Chary 
15053e230dd2SCorentin Chary /*
15063e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
15073e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
15083e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
15093e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
15103e230dd2SCorentin Chary  *
15113e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
15123e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
15133e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
15143e230dd2SCorentin Chary  * is active
15153e230dd2SCorentin Chary  *
15163e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
15173e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
151830b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15193e230dd2SCorentin Chary  */
152030b80fd5SDaniel P. Berrange size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
15213e230dd2SCorentin Chary {
1522fdd1ab6aSDaniel P. Berrange     ssize_t ret;
152304d2529dSDaniel P. Berrange     Error *err = NULL;
152434ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
15253e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
152634ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
15273e230dd2SCorentin Chary }
15283e230dd2SCorentin Chary 
15293e230dd2SCorentin Chary 
15303e230dd2SCorentin Chary /*
15313e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
15323e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
15333e230dd2SCorentin Chary  * data as possible without blocking.
15343e230dd2SCorentin Chary  *
153530b80fd5SDaniel P. Berrange  * Returns the number of bytes read, which may be less than
153630b80fd5SDaniel P. Berrange  * the requested 'datalen' if the socket would block. Returns
153730b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15383e230dd2SCorentin Chary  */
153930b80fd5SDaniel P. Berrange static size_t vnc_client_read_plain(VncState *vs)
15403e230dd2SCorentin Chary {
154130b80fd5SDaniel P. Berrange     size_t ret;
15423e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
15433e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
15443e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
15453e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
15463e230dd2SCorentin Chary     if (!ret)
15473e230dd2SCorentin Chary         return 0;
15483e230dd2SCorentin Chary     vs->input.offset += ret;
15493e230dd2SCorentin Chary     return ret;
15503e230dd2SCorentin Chary }
15513e230dd2SCorentin Chary 
1552175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1553175b2a6eSCorentin Chary {
1554175b2a6eSCorentin Chary     VncState *vs = opaque;
1555175b2a6eSCorentin Chary 
1556f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1557175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1558175b2a6eSCorentin Chary }
15593e230dd2SCorentin Chary 
15603e230dd2SCorentin Chary /*
15613e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
15623e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
15633e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
1564ea697449SDaniel P. Berrange  * Returns 0 on success, -1 if client disconnected
15653e230dd2SCorentin Chary  */
1566ea697449SDaniel P. Berrange static int vnc_client_read(VncState *vs)
15673e230dd2SCorentin Chary {
156830b80fd5SDaniel P. Berrange     size_t ret;
15693e230dd2SCorentin Chary 
15703e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
15713e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
15723e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
15733e230dd2SCorentin Chary     else
15743e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
15753e230dd2SCorentin Chary         ret = vnc_client_read_plain(vs);
15763e230dd2SCorentin Chary     if (!ret) {
157704d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15783e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1579ea697449SDaniel P. Berrange             return -1;
158004d2529dSDaniel P. Berrange         }
1581ea697449SDaniel P. Berrange         return 0;
15823e230dd2SCorentin Chary     }
15833e230dd2SCorentin Chary 
15843e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
15853e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
15863e230dd2SCorentin Chary         int ret;
15873e230dd2SCorentin Chary 
15883e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
158904d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15903e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1591ea697449SDaniel P. Berrange             return -1;
15923e230dd2SCorentin Chary         }
15933e230dd2SCorentin Chary 
15943e230dd2SCorentin Chary         if (!ret) {
159532ed2680STim Hardeck             buffer_advance(&vs->input, len);
15963e230dd2SCorentin Chary         } else {
15973e230dd2SCorentin Chary             vs->read_handler_expect = ret;
15983e230dd2SCorentin Chary         }
15993e230dd2SCorentin Chary     }
1600ea697449SDaniel P. Berrange     return 0;
16013e230dd2SCorentin Chary }
16023e230dd2SCorentin Chary 
160304d2529dSDaniel P. Berrange gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
160404d2529dSDaniel P. Berrange                        GIOCondition condition, void *opaque)
160504d2529dSDaniel P. Berrange {
160604d2529dSDaniel P. Berrange     VncState *vs = opaque;
1607f31f9c10SGerd Hoffmann 
1608f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
16092ddafce7SDing Hui 
16102ddafce7SDing Hui     if (condition & (G_IO_HUP | G_IO_ERR)) {
16112ddafce7SDing Hui         vnc_disconnect_start(vs);
16122ddafce7SDing Hui         return TRUE;
16132ddafce7SDing Hui     }
16142ddafce7SDing Hui 
161504d2529dSDaniel P. Berrange     if (condition & G_IO_IN) {
1616ea697449SDaniel P. Berrange         if (vnc_client_read(vs) < 0) {
16171bc3117aSGerd Hoffmann             /* vs is free()ed here */
16181bc3117aSGerd Hoffmann             return TRUE;
1619ea697449SDaniel P. Berrange         }
162004d2529dSDaniel P. Berrange     }
162104d2529dSDaniel P. Berrange     if (condition & G_IO_OUT) {
162204d2529dSDaniel P. Berrange         vnc_client_write(vs);
162304d2529dSDaniel P. Berrange     }
16241bc3117aSGerd Hoffmann 
1625d49b87f0SKlim Kireev     if (vs->disconnecting) {
1626d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1627d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1628d49b87f0SKlim Kireev         }
1629d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1630d49b87f0SKlim Kireev     }
163104d2529dSDaniel P. Berrange     return TRUE;
163204d2529dSDaniel P. Berrange }
163304d2529dSDaniel P. Berrange 
163404d2529dSDaniel P. Berrange 
1635f887cf16SDaniel P. Berrange /*
1636f887cf16SDaniel P. Berrange  * Scale factor to apply to vs->throttle_output_offset when checking for
1637f887cf16SDaniel P. Berrange  * hard limit. Worst case normal usage could be x2, if we have a complete
1638f887cf16SDaniel P. Berrange  * incremental update and complete forced update in the output buffer.
1639f887cf16SDaniel P. Berrange  * So x3 should be good enough, but we pick x5 to be conservative and thus
1640f887cf16SDaniel P. Berrange  * (hopefully) never trigger incorrectly.
1641f887cf16SDaniel P. Berrange  */
1642f887cf16SDaniel P. Berrange #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1643f887cf16SDaniel P. Berrange 
16443e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
16453e230dd2SCorentin Chary {
1646f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1647f887cf16SDaniel P. Berrange     if (vs->disconnecting) {
1648f887cf16SDaniel P. Berrange         return;
1649f887cf16SDaniel P. Berrange     }
1650f887cf16SDaniel P. Berrange     /* Protection against malicious client/guest to prevent our output
1651f887cf16SDaniel P. Berrange      * buffer growing without bound if client stops reading data. This
1652f887cf16SDaniel P. Berrange      * should rarely trigger, because we have earlier throttling code
1653f887cf16SDaniel P. Berrange      * which stops issuing framebuffer updates and drops audio data
1654f887cf16SDaniel P. Berrange      * if the throttle_output_offset value is exceeded. So we only reach
1655f887cf16SDaniel P. Berrange      * this higher level if a huge number of pseudo-encodings get
1656f887cf16SDaniel P. Berrange      * triggered while data can't be sent on the socket.
1657f887cf16SDaniel P. Berrange      *
1658f887cf16SDaniel P. Berrange      * NB throttle_output_offset can be zero during early protocol
1659f887cf16SDaniel P. Berrange      * handshake, or from the job thread's VncState clone
1660f887cf16SDaniel P. Berrange      */
1661f887cf16SDaniel P. Berrange     if (vs->throttle_output_offset != 0 &&
1662dffa1de0SDaniel P. Berrangé         (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1663dffa1de0SDaniel P. Berrangé         vs->throttle_output_offset) {
16646aa22a29SDaniel P. Berrange         trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
16656aa22a29SDaniel P. Berrange                                       vs->throttle_output_offset);
1666f887cf16SDaniel P. Berrange         vnc_disconnect_start(vs);
1667f887cf16SDaniel P. Berrange         return;
1668f887cf16SDaniel P. Berrange     }
16693e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
16703e230dd2SCorentin Chary 
167104d2529dSDaniel P. Berrange     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
167204d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
167304d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
167404d2529dSDaniel P. Berrange         }
167504d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
16762ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
16772ddafce7SDing Hui             vnc_client_io, vs, NULL);
16783e230dd2SCorentin Chary     }
16793e230dd2SCorentin Chary 
16803e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
16813e230dd2SCorentin Chary }
16823e230dd2SCorentin Chary 
16833e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
16843e230dd2SCorentin Chary {
16853e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
16863e230dd2SCorentin Chary }
16873e230dd2SCorentin Chary 
16883e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
16893e230dd2SCorentin Chary {
16903e230dd2SCorentin Chary     uint8_t buf[4];
16913e230dd2SCorentin Chary 
16923e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
16933e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
16943e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
16953e230dd2SCorentin Chary     buf[3] = value & 0xFF;
16963e230dd2SCorentin Chary 
16973e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
16983e230dd2SCorentin Chary }
16993e230dd2SCorentin Chary 
17003e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
17013e230dd2SCorentin Chary {
17023e230dd2SCorentin Chary     uint8_t buf[2];
17033e230dd2SCorentin Chary 
17043e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
17053e230dd2SCorentin Chary     buf[1] = value & 0xFF;
17063e230dd2SCorentin Chary 
17073e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
17083e230dd2SCorentin Chary }
17093e230dd2SCorentin Chary 
17103e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
17113e230dd2SCorentin Chary {
17123e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
17133e230dd2SCorentin Chary }
17143e230dd2SCorentin Chary 
17153e230dd2SCorentin Chary void vnc_flush(VncState *vs)
17163e230dd2SCorentin Chary {
1717bd023f95SCorentin Chary     vnc_lock_output(vs);
1718d5f04223SDaniel P. Berrange     if (vs->ioc != NULL && vs->output.offset) {
1719bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1720bd023f95SCorentin Chary     }
1721d49b87f0SKlim Kireev     if (vs->disconnecting) {
1722d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1723d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1724d49b87f0SKlim Kireev         }
1725d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1726d49b87f0SKlim Kireev     }
1727bd023f95SCorentin Chary     vnc_unlock_output(vs);
17283e230dd2SCorentin Chary }
17293e230dd2SCorentin Chary 
173071a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
17313e230dd2SCorentin Chary {
17323e230dd2SCorentin Chary     return data[offset];
17333e230dd2SCorentin Chary }
17343e230dd2SCorentin Chary 
173571a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
17363e230dd2SCorentin Chary {
17373e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
17383e230dd2SCorentin Chary }
17393e230dd2SCorentin Chary 
174071a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
17413e230dd2SCorentin Chary {
17423e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
17433e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
17443e230dd2SCorentin Chary }
17453e230dd2SCorentin Chary 
17463e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
17473e230dd2SCorentin Chary {
17483e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
17493e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
17503e230dd2SCorentin Chary }
17513e230dd2SCorentin Chary 
17523e230dd2SCorentin Chary static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
17533e230dd2SCorentin Chary {
17543e230dd2SCorentin Chary }
17553e230dd2SCorentin Chary 
17569e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
17573e230dd2SCorentin Chary {
17583e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
175914768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
17603e230dd2SCorentin Chary 
17613e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1762bd023f95SCorentin Chary         vnc_lock_output(vs);
17633e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
17643e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
17653e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
17663e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1767bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1768bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
17693e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1770bd023f95SCorentin Chary         vnc_unlock_output(vs);
17713e230dd2SCorentin Chary         vnc_flush(vs);
17723e230dd2SCorentin Chary     }
17733e230dd2SCorentin Chary     vs->absolute = absolute;
17743e230dd2SCorentin Chary }
17753e230dd2SCorentin Chary 
17763e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
17773e230dd2SCorentin Chary {
17787fb1cf16SEric Blake     static uint32_t bmap[INPUT_BUTTON__MAX] = {
177914768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
178014768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
178114768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
1782f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1783f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
178414768ebaSGerd Hoffmann     };
178514768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1786bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1787bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
17883e230dd2SCorentin Chary 
178914768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
179014768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
179114768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
179214768ebaSGerd Hoffmann     }
17933e230dd2SCorentin Chary 
17943e230dd2SCorentin Chary     if (vs->absolute) {
17959cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
17969cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
17973e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
179814768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
179914768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
18003e230dd2SCorentin Chary     } else {
180114768ebaSGerd Hoffmann         if (vs->last_x != -1) {
180214768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
180314768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
180414768ebaSGerd Hoffmann         }
18053e230dd2SCorentin Chary         vs->last_x = x;
18063e230dd2SCorentin Chary         vs->last_y = y;
18073e230dd2SCorentin Chary     }
180814768ebaSGerd Hoffmann     qemu_input_event_sync();
18093e230dd2SCorentin Chary }
18103e230dd2SCorentin Chary 
1811c2f2ba49SGerd Hoffmann static void press_key(VncState *vs, QKeyCode qcode)
18123e230dd2SCorentin Chary {
1813c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, true);
1814c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, false);
18153e230dd2SCorentin Chary }
18163e230dd2SCorentin Chary 
1817ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1818ab99e5c1SLei Li {
1819ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1820ab99e5c1SLei Li         return;
1821ab99e5c1SLei Li     }
1822ab99e5c1SLei Li 
1823ab99e5c1SLei Li     vnc_lock_output(vs);
1824ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1825ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1826ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1827ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1828a54f0d2bSPierre Ossman     vnc_write_u8(vs, vs->vd->ledstate);
1829ab99e5c1SLei Li     vnc_unlock_output(vs);
1830ab99e5c1SLei Li     vnc_flush(vs);
1831ab99e5c1SLei Li }
1832ab99e5c1SLei Li 
18333e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
18343e230dd2SCorentin Chary {
1835a54f0d2bSPierre Ossman     VncDisplay *vd = opaque;
1836a54f0d2bSPierre Ossman     VncState *client;
18373e230dd2SCorentin Chary 
183840066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
183940066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
184040066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
184140066175SGerd Hoffmann 
1842a54f0d2bSPierre Ossman     if (ledstate == vd->ledstate) {
1843a54f0d2bSPierre Ossman         return;
184496f3d174SLei Li     }
1845ab99e5c1SLei Li 
1846a54f0d2bSPierre Ossman     vd->ledstate = ledstate;
1847a54f0d2bSPierre Ossman 
1848a54f0d2bSPierre Ossman     QTAILQ_FOREACH(client, &vd->clients, next) {
1849a54f0d2bSPierre Ossman         vnc_led_state_change(client);
1850ab99e5c1SLei Li     }
18513e230dd2SCorentin Chary }
18523e230dd2SCorentin Chary 
18533e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
18543e230dd2SCorentin Chary {
1855c2f2ba49SGerd Hoffmann     QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1856c2f2ba49SGerd Hoffmann 
18573e230dd2SCorentin Chary     /* QEMU console switch */
1858c2f2ba49SGerd Hoffmann     switch (qcode) {
1859c2f2ba49SGerd Hoffmann     case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1860c2f2ba49SGerd Hoffmann         if (vs->vd->dcl.con == NULL && down &&
1861c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1862c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
18633e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
1864c2f2ba49SGerd Hoffmann             qkbd_state_lift_all_keys(vs->vd->kbd);
1865c2f2ba49SGerd Hoffmann             console_select(qcode - Q_KEY_CODE_1);
18663e230dd2SCorentin Chary             return;
18673e230dd2SCorentin Chary         }
1868c2f2ba49SGerd Hoffmann     default:
18693e230dd2SCorentin Chary         break;
18703e230dd2SCorentin Chary     }
18713e230dd2SCorentin Chary 
1872e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1873e7b2aaccSLei Li        state extension.
1874e7b2aaccSLei Li     */
18759892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1876e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18773e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
18783e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
18793e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18803e230dd2SCorentin Chary            toggles numlock away from the VNC window.
18813e230dd2SCorentin Chary         */
18823e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1883c2f2ba49SGerd Hoffmann             if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
188440066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
1885c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
18863e230dd2SCorentin Chary             }
18873e230dd2SCorentin Chary         } else {
1888c2f2ba49SGerd Hoffmann             if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
188940066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
1890c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
18913e230dd2SCorentin Chary             }
18923e230dd2SCorentin Chary         }
18933e230dd2SCorentin Chary     }
18943e230dd2SCorentin Chary 
18959892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1896e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18973e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
18983e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
18993e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
19003e230dd2SCorentin Chary            toggles capslock away from the VNC window.
19013e230dd2SCorentin Chary         */
19023e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1903c2f2ba49SGerd Hoffmann         bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1904c2f2ba49SGerd Hoffmann         bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
19053e230dd2SCorentin Chary         if (capslock) {
19063e230dd2SCorentin Chary             if (uppercase == shift) {
190740066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
1908c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
19093e230dd2SCorentin Chary             }
19103e230dd2SCorentin Chary         } else {
19113e230dd2SCorentin Chary             if (uppercase != shift) {
191240066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
1913c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
19143e230dd2SCorentin Chary             }
19153e230dd2SCorentin Chary         }
19163e230dd2SCorentin Chary     }
19173e230dd2SCorentin Chary 
1918c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, down);
1919c2f2ba49SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
1920c2f2ba49SGerd Hoffmann         bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1921c2f2ba49SGerd Hoffmann         bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
19223e230dd2SCorentin Chary         /* QEMU console emulation */
19233e230dd2SCorentin Chary         if (down) {
19243e230dd2SCorentin Chary             switch (keycode) {
19253e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
19263e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
19273e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
19283e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
19293e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
19303e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
19313e230dd2SCorentin Chary                 break;
19323e230dd2SCorentin Chary             case 0xc8:
19333e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_UP);
19343e230dd2SCorentin Chary                 break;
19353e230dd2SCorentin Chary             case 0xd0:
19363e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DOWN);
19373e230dd2SCorentin Chary                 break;
19383e230dd2SCorentin Chary             case 0xcb:
19393e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_LEFT);
19403e230dd2SCorentin Chary                 break;
19413e230dd2SCorentin Chary             case 0xcd:
19423e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_RIGHT);
19433e230dd2SCorentin Chary                 break;
19443e230dd2SCorentin Chary             case 0xd3:
19453e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DELETE);
19463e230dd2SCorentin Chary                 break;
19473e230dd2SCorentin Chary             case 0xc7:
19483e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_HOME);
19493e230dd2SCorentin Chary                 break;
19503e230dd2SCorentin Chary             case 0xcf:
19513e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_END);
19523e230dd2SCorentin Chary                 break;
19533e230dd2SCorentin Chary             case 0xc9:
19543e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEUP);
19553e230dd2SCorentin Chary                 break;
19563e230dd2SCorentin Chary             case 0xd1:
19573e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
19583e230dd2SCorentin Chary                 break;
19593e230dd2SCorentin Chary 
19603e230dd2SCorentin Chary             case 0x47:
19613e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
19623e230dd2SCorentin Chary                 break;
19633e230dd2SCorentin Chary             case 0x48:
19643e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
19653e230dd2SCorentin Chary                 break;
19663e230dd2SCorentin Chary             case 0x49:
19673e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
19683e230dd2SCorentin Chary                 break;
19693e230dd2SCorentin Chary             case 0x4b:
19703e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
19713e230dd2SCorentin Chary                 break;
19723e230dd2SCorentin Chary             case 0x4c:
19733e230dd2SCorentin Chary                 kbd_put_keysym('5');
19743e230dd2SCorentin Chary                 break;
19753e230dd2SCorentin Chary             case 0x4d:
19763e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
19773e230dd2SCorentin Chary                 break;
19783e230dd2SCorentin Chary             case 0x4f:
19793e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
19803e230dd2SCorentin Chary                 break;
19813e230dd2SCorentin Chary             case 0x50:
19823e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
19833e230dd2SCorentin Chary                 break;
19843e230dd2SCorentin Chary             case 0x51:
19853e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
19863e230dd2SCorentin Chary                 break;
19873e230dd2SCorentin Chary             case 0x52:
19883e230dd2SCorentin Chary                 kbd_put_keysym('0');
19893e230dd2SCorentin Chary                 break;
19903e230dd2SCorentin Chary             case 0x53:
19913e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
19923e230dd2SCorentin Chary                 break;
19933e230dd2SCorentin Chary 
19943e230dd2SCorentin Chary             case 0xb5:
19953e230dd2SCorentin Chary                 kbd_put_keysym('/');
19963e230dd2SCorentin Chary                 break;
19973e230dd2SCorentin Chary             case 0x37:
19983e230dd2SCorentin Chary                 kbd_put_keysym('*');
19993e230dd2SCorentin Chary                 break;
20003e230dd2SCorentin Chary             case 0x4a:
20013e230dd2SCorentin Chary                 kbd_put_keysym('-');
20023e230dd2SCorentin Chary                 break;
20033e230dd2SCorentin Chary             case 0x4e:
20043e230dd2SCorentin Chary                 kbd_put_keysym('+');
20053e230dd2SCorentin Chary                 break;
20063e230dd2SCorentin Chary             case 0x9c:
20073e230dd2SCorentin Chary                 kbd_put_keysym('\n');
20083e230dd2SCorentin Chary                 break;
20093e230dd2SCorentin Chary 
20103e230dd2SCorentin Chary             default:
2011e26437c2SGerd Hoffmann                 if (control) {
2012e26437c2SGerd Hoffmann                     kbd_put_keysym(sym & 0x1f);
2013e26437c2SGerd Hoffmann                 } else {
20143e230dd2SCorentin Chary                     kbd_put_keysym(sym);
2015e26437c2SGerd Hoffmann                 }
20163e230dd2SCorentin Chary                 break;
20173e230dd2SCorentin Chary             }
20183e230dd2SCorentin Chary         }
20193e230dd2SCorentin Chary     }
20203e230dd2SCorentin Chary }
20213e230dd2SCorentin Chary 
202240066175SGerd Hoffmann static const char *code2name(int keycode)
202340066175SGerd Hoffmann {
2024977c736fSMarkus Armbruster     return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
202540066175SGerd Hoffmann }
202640066175SGerd Hoffmann 
20273e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
20283e230dd2SCorentin Chary {
20293e230dd2SCorentin Chary     int keycode;
20303e230dd2SCorentin Chary     int lsym = sym;
20313e230dd2SCorentin Chary 
203281c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
20333e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
20343e230dd2SCorentin Chary     }
20353e230dd2SCorentin Chary 
2036abb4f2c9SGerd Hoffmann     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
203719c1b9fdSGerd Hoffmann                               vs->vd->kbd, down) & SCANCODE_KEYMASK;
203840066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
20393e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
20403e230dd2SCorentin Chary }
20413e230dd2SCorentin Chary 
20423e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
20433e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
20443e230dd2SCorentin Chary {
20453e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
204640066175SGerd Hoffmann     if (keyboard_layout) {
20473e230dd2SCorentin Chary         key_event(vs, down, sym);
204840066175SGerd Hoffmann     } else {
204940066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
20503e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
20513e230dd2SCorentin Chary     }
205240066175SGerd Hoffmann }
20533e230dd2SCorentin Chary 
20543e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
2055bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
20563e230dd2SCorentin Chary {
2057bea60dd7SPeter Lieven     if (incremental) {
2058fef1bbadSDaniel P. Berrange         if (vs->update != VNC_STATE_UPDATE_FORCE) {
2059fef1bbadSDaniel P. Berrange             vs->update = VNC_STATE_UPDATE_INCREMENTAL;
20603e230dd2SCorentin Chary         }
2061fef1bbadSDaniel P. Berrange     } else {
2062fef1bbadSDaniel P. Berrange         vs->update = VNC_STATE_UPDATE_FORCE;
2063f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2064104b8d19SGerd Hoffmann         if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
2065104b8d19SGerd Hoffmann             vnc_desktop_resize_ext(vs, 0);
2066104b8d19SGerd Hoffmann         }
20673e230dd2SCorentin Chary     }
2068fef1bbadSDaniel P. Berrange }
20693e230dd2SCorentin Chary 
20703e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
20713e230dd2SCorentin Chary {
2072bd023f95SCorentin Chary     vnc_lock_output(vs);
20733e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20743e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20753e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2076d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2077bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2078bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20793e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
2080bd023f95SCorentin Chary     vnc_unlock_output(vs);
20813e230dd2SCorentin Chary     vnc_flush(vs);
20823e230dd2SCorentin Chary }
20833e230dd2SCorentin Chary 
20843e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
20853e230dd2SCorentin Chary {
2086bd023f95SCorentin Chary     vnc_lock_output(vs);
20873e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20883e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20893e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2090d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2091bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2092bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20933e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2094bd023f95SCorentin Chary     vnc_unlock_output(vs);
20953e230dd2SCorentin Chary     vnc_flush(vs);
20963e230dd2SCorentin Chary }
20973e230dd2SCorentin Chary 
20987b5fa0b5SDaniel P. Berrangé static void send_xvp_message(VncState *vs, int code)
20997b5fa0b5SDaniel P. Berrangé {
21007b5fa0b5SDaniel P. Berrangé     vnc_lock_output(vs);
21017b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
21027b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 0); /* pad */
21037b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 1); /* version */
21047b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, code);
21057b5fa0b5SDaniel P. Berrangé     vnc_unlock_output(vs);
21067b5fa0b5SDaniel P. Berrangé     vnc_flush(vs);
21077b5fa0b5SDaniel P. Berrangé }
21087b5fa0b5SDaniel P. Berrangé 
21093e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
21103e230dd2SCorentin Chary {
21113e230dd2SCorentin Chary     int i;
21123e230dd2SCorentin Chary     unsigned int enc = 0;
21133e230dd2SCorentin Chary 
21143e230dd2SCorentin Chary     vs->features = 0;
21153e230dd2SCorentin Chary     vs->vnc_encoding = 0;
21166bf21f3dSLi Qiang     vs->tight->compression = 9;
21176bf21f3dSLi Qiang     vs->tight->quality = -1; /* Lossless by default */
21183e230dd2SCorentin Chary     vs->absolute = -1;
21193e230dd2SCorentin Chary 
21203e230dd2SCorentin Chary     /*
21213e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2122e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
21233e230dd2SCorentin Chary      * will be set at the end of the loop.
21243e230dd2SCorentin Chary      */
21253e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
21263e230dd2SCorentin Chary         enc = encodings[i];
21273e230dd2SCorentin Chary         switch (enc) {
21283e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
21293e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21303e230dd2SCorentin Chary             break;
21313e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
21323e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
21333e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21343e230dd2SCorentin Chary             break;
21353e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
21363e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
21373e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21383e230dd2SCorentin Chary             break;
2139fe3e7f2dSJoel Martin #ifdef CONFIG_VNC_PNG
2140efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2141efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2142efe556adSCorentin Chary             vs->vnc_encoding = enc;
2143efe556adSCorentin Chary             break;
2144fe3e7f2dSJoel Martin #endif
21453e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
2146557ba0e5SCameron Esfahani             /*
2147557ba0e5SCameron Esfahani              * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2148557ba0e5SCameron Esfahani              * So prioritize ZRLE, even if the client hints that it prefers
2149557ba0e5SCameron Esfahani              * ZLIB.
2150557ba0e5SCameron Esfahani              */
2151557ba0e5SCameron Esfahani             if ((vs->features & VNC_FEATURE_ZRLE_MASK) == 0) {
21523e230dd2SCorentin Chary                 vs->features |= VNC_FEATURE_ZLIB_MASK;
21533e230dd2SCorentin Chary                 vs->vnc_encoding = enc;
2154557ba0e5SCameron Esfahani             }
21553e230dd2SCorentin Chary             break;
2156148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2157148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2158148954faSCorentin Chary             vs->vnc_encoding = enc;
2159148954faSCorentin Chary             break;
2160148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2161148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2162148954faSCorentin Chary             vs->vnc_encoding = enc;
2163148954faSCorentin Chary             break;
21643e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
21653e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
21663e230dd2SCorentin Chary             break;
2167763deea7SGerd Hoffmann         case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2168763deea7SGerd Hoffmann             vs->features |= VNC_FEATURE_RESIZE_EXT_MASK;
2169763deea7SGerd Hoffmann             break;
21703e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
21713e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
21723e230dd2SCorentin Chary             break;
21733e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
21743e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2175074a86d0SGerd Hoffmann             break;
2176074a86d0SGerd Hoffmann         case VNC_ENCODING_ALPHA_CURSOR:
2177074a86d0SGerd Hoffmann             vs->features |= VNC_FEATURE_ALPHA_CURSOR_MASK;
21783e230dd2SCorentin Chary             break;
21793e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
21803e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
21813e230dd2SCorentin Chary             break;
21823e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
21833e230dd2SCorentin Chary             send_ext_audio_ack(vs);
21843e230dd2SCorentin Chary             break;
21853e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
21863e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
21873e230dd2SCorentin Chary             break;
2188ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2189ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2190ab99e5c1SLei Li             break;
21917b5fa0b5SDaniel P. Berrangé         case VNC_ENCODING_XVP:
21927b5fa0b5SDaniel P. Berrangé             if (vs->vd->power_control) {
21937b5fa0b5SDaniel P. Berrangé                 vs->features |= VNC_FEATURE_XVP;
21947b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_INIT);
21957b5fa0b5SDaniel P. Berrangé             }
21967b5fa0b5SDaniel P. Berrangé             break;
21973e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
21986bf21f3dSLi Qiang             vs->tight->compression = (enc & 0x0F);
21993e230dd2SCorentin Chary             break;
22003e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2201b31f519eSCorentin Chary             if (vs->vd->lossy) {
22026bf21f3dSLi Qiang                 vs->tight->quality = (enc & 0x0F);
2203b31f519eSCorentin Chary             }
22043e230dd2SCorentin Chary             break;
22053e230dd2SCorentin Chary         default:
22063e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
22073e230dd2SCorentin Chary             break;
22083e230dd2SCorentin Chary         }
22093e230dd2SCorentin Chary     }
2210d239726cSGerd Hoffmann     vnc_desktop_resize(vs);
22119e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2212d239726cSGerd Hoffmann     vnc_led_state_change(vs);
2213d239726cSGerd Hoffmann     vnc_cursor_define(vs);
2214074a86d0SGerd Hoffmann }
22153e230dd2SCorentin Chary 
22163e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
22173e230dd2SCorentin Chary {
22189f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
22199f64916dSGerd Hoffmann 
22209f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
22213e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
22223e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
22233e230dd2SCorentin Chary     } else {
22243e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
22253e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
22263e230dd2SCorentin Chary     }
22273e230dd2SCorentin Chary }
22283e230dd2SCorentin Chary 
22290c426e45SAlexander Graf static void send_color_map(VncState *vs)
22300c426e45SAlexander Graf {
22310c426e45SAlexander Graf     int i;
22320c426e45SAlexander Graf 
2233947191b4SPeng Liang     vnc_lock_output(vs);
22340c426e45SAlexander Graf     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
22350c426e45SAlexander Graf     vnc_write_u8(vs,  0);    /* padding     */
22360c426e45SAlexander Graf     vnc_write_u16(vs, 0);    /* first color */
22370c426e45SAlexander Graf     vnc_write_u16(vs, 256);  /* # of colors */
22380c426e45SAlexander Graf 
22390c426e45SAlexander Graf     for (i = 0; i < 256; i++) {
22400c426e45SAlexander Graf         PixelFormat *pf = &vs->client_pf;
22410c426e45SAlexander Graf 
22420c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
22430c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
22440c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
22450c426e45SAlexander Graf     }
2246947191b4SPeng Liang     vnc_unlock_output(vs);
22470c426e45SAlexander Graf }
22480c426e45SAlexander Graf 
2249ec9fb41aSGerd Hoffmann static void set_pixel_format(VncState *vs, int bits_per_pixel,
22503e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
22513e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
22523e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
22533e230dd2SCorentin Chary {
22543e230dd2SCorentin Chary     if (!true_color_flag) {
22550c426e45SAlexander Graf         /* Expose a reasonable default 256 color map */
22560c426e45SAlexander Graf         bits_per_pixel = 8;
22570c426e45SAlexander Graf         red_max = 7;
22580c426e45SAlexander Graf         green_max = 7;
22590c426e45SAlexander Graf         blue_max = 3;
22600c426e45SAlexander Graf         red_shift = 0;
22610c426e45SAlexander Graf         green_shift = 3;
22620c426e45SAlexander Graf         blue_shift = 6;
22633e230dd2SCorentin Chary     }
22643e230dd2SCorentin Chary 
2265e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2266e6908bfeSPetr Matousek     case 8:
2267e6908bfeSPetr Matousek     case 16:
2268e6908bfeSPetr Matousek     case 32:
2269e6908bfeSPetr Matousek         break;
2270e6908bfeSPetr Matousek     default:
2271e6908bfeSPetr Matousek         vnc_client_error(vs);
2272e6908bfeSPetr Matousek         return;
2273e6908bfeSPetr Matousek     }
2274e6908bfeSPetr Matousek 
22754c65fed8SPrasad J Pandit     vs->client_pf.rmax = red_max ? red_max : 0xFF;
22767c9209e7SCédric Le Goater     vs->client_pf.rbits = ctpopl(red_max);
22779f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
22789f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
22794c65fed8SPrasad J Pandit     vs->client_pf.gmax = green_max ? green_max : 0xFF;
22807c9209e7SCédric Le Goater     vs->client_pf.gbits = ctpopl(green_max);
22819f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
22829f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
22834c65fed8SPrasad J Pandit     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
22847c9209e7SCédric Le Goater     vs->client_pf.bbits = ctpopl(blue_max);
22859f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
22869f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
22879f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
22889f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
22899f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
22909f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
22913e230dd2SCorentin Chary 
22920c426e45SAlexander Graf     if (!true_color_flag) {
22930c426e45SAlexander Graf         send_color_map(vs);
22940c426e45SAlexander Graf     }
22950c426e45SAlexander Graf 
22963e230dd2SCorentin Chary     set_pixel_conversion(vs);
22973e230dd2SCorentin Chary 
22981d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
22991d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
23003e230dd2SCorentin Chary }
23013e230dd2SCorentin Chary 
23023e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
23033e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
23043e230dd2SCorentin Chary 
23059f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
23069f64916dSGerd Hoffmann 
23079f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
23089f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
23093e230dd2SCorentin Chary 
23103e230dd2SCorentin Chary #ifdef HOST_WORDS_BIGENDIAN
23113e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
23123e230dd2SCorentin Chary #else
23133e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
23143e230dd2SCorentin Chary #endif
23153e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
23169f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
23179f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
23189f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
23199f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
23209f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
23219f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
23229f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
23233e230dd2SCorentin Chary 
23243e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
23253e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
23263e230dd2SCorentin Chary }
23273e230dd2SCorentin Chary 
23283e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
23293e230dd2SCorentin Chary {
23303e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
23313e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2332bd023f95SCorentin Chary         vnc_lock_output(vs);
23333e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
23343e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
23353e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2336d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
23373d3a528dSDaniel P. Berrangé                                vs->client_width,
23383d3a528dSDaniel P. Berrangé                                vs->client_height,
2339d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
23403e230dd2SCorentin Chary         pixel_format_message(vs);
2341bd023f95SCorentin Chary         vnc_unlock_output(vs);
23423e230dd2SCorentin Chary         vnc_flush(vs);
23433e230dd2SCorentin Chary     } else {
23443e230dd2SCorentin Chary         set_pixel_conversion(vs);
23453e230dd2SCorentin Chary     }
23463e230dd2SCorentin Chary }
23473e230dd2SCorentin Chary 
23483e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
23493e230dd2SCorentin Chary {
23503e230dd2SCorentin Chary     int i;
23513e230dd2SCorentin Chary     uint16_t limit;
2352cf070658SDaniel P. Berrangé     uint32_t freq;
23533e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
23543e230dd2SCorentin Chary 
23553e230dd2SCorentin Chary     if (data[0] > 3) {
23560f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
23573e230dd2SCorentin Chary     }
23583e230dd2SCorentin Chary 
23593e230dd2SCorentin Chary     switch (data[0]) {
23603e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
23613e230dd2SCorentin Chary         if (len == 1)
23623e230dd2SCorentin Chary             return 20;
23633e230dd2SCorentin Chary 
2364ec9fb41aSGerd Hoffmann         set_pixel_format(vs, read_u8(data, 4),
23653e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
23663e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
23673e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
23683e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
23693e230dd2SCorentin Chary         break;
23703e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
23713e230dd2SCorentin Chary         if (len == 1)
23723e230dd2SCorentin Chary             return 4;
23733e230dd2SCorentin Chary 
23743e230dd2SCorentin Chary         if (len == 4) {
23753e230dd2SCorentin Chary             limit = read_u16(data, 2);
23763e230dd2SCorentin Chary             if (limit > 0)
23773e230dd2SCorentin Chary                 return 4 + (limit * 4);
23783e230dd2SCorentin Chary         } else
23793e230dd2SCorentin Chary             limit = read_u16(data, 2);
23803e230dd2SCorentin Chary 
23813e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
23823e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
23833e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
23843e230dd2SCorentin Chary         }
23853e230dd2SCorentin Chary 
23863e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
23873e230dd2SCorentin Chary         break;
23883e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
23893e230dd2SCorentin Chary         if (len == 1)
23903e230dd2SCorentin Chary             return 10;
23913e230dd2SCorentin Chary 
23923e230dd2SCorentin Chary         framebuffer_update_request(vs,
23933e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
23943e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
23953e230dd2SCorentin Chary         break;
23963e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
23973e230dd2SCorentin Chary         if (len == 1)
23983e230dd2SCorentin Chary             return 8;
23993e230dd2SCorentin Chary 
24003e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
24013e230dd2SCorentin Chary         break;
24023e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
24033e230dd2SCorentin Chary         if (len == 1)
24043e230dd2SCorentin Chary             return 6;
24053e230dd2SCorentin Chary 
24063e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
24073e230dd2SCorentin Chary         break;
24083e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2409f9a70e79SPeter Lieven         if (len == 1) {
24103e230dd2SCorentin Chary             return 8;
2411f9a70e79SPeter Lieven         }
24123e230dd2SCorentin Chary         if (len == 8) {
24133e230dd2SCorentin Chary             uint32_t dlen = read_u32(data, 4);
2414f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2415f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2416f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2417f9a70e79SPeter Lieven                 vnc_client_error(vs);
2418f9a70e79SPeter Lieven                 break;
2419f9a70e79SPeter Lieven             }
2420f9a70e79SPeter Lieven             if (dlen > 0) {
24213e230dd2SCorentin Chary                 return 8 + dlen;
24223e230dd2SCorentin Chary             }
2423f9a70e79SPeter Lieven         }
24243e230dd2SCorentin Chary 
24253e230dd2SCorentin Chary         client_cut_text(vs, read_u32(data, 4), data + 8);
24263e230dd2SCorentin Chary         break;
24277b5fa0b5SDaniel P. Berrangé     case VNC_MSG_CLIENT_XVP:
24287b5fa0b5SDaniel P. Berrangé         if (!(vs->features & VNC_FEATURE_XVP)) {
24297b5fa0b5SDaniel P. Berrangé             error_report("vnc: xvp client message while disabled");
24307b5fa0b5SDaniel P. Berrangé             vnc_client_error(vs);
24317b5fa0b5SDaniel P. Berrangé             break;
24327b5fa0b5SDaniel P. Berrangé         }
24337b5fa0b5SDaniel P. Berrangé         if (len == 1) {
24347b5fa0b5SDaniel P. Berrangé             return 4;
24357b5fa0b5SDaniel P. Berrangé         }
24367b5fa0b5SDaniel P. Berrangé         if (len == 4) {
24377b5fa0b5SDaniel P. Berrangé             uint8_t version = read_u8(data, 2);
24387b5fa0b5SDaniel P. Berrangé             uint8_t action = read_u8(data, 3);
24397b5fa0b5SDaniel P. Berrangé 
24407b5fa0b5SDaniel P. Berrangé             if (version != 1) {
24417b5fa0b5SDaniel P. Berrangé                 error_report("vnc: xvp client message version %d != 1",
24427b5fa0b5SDaniel P. Berrangé                              version);
24437b5fa0b5SDaniel P. Berrangé                 vnc_client_error(vs);
24447b5fa0b5SDaniel P. Berrangé                 break;
24457b5fa0b5SDaniel P. Berrangé             }
24467b5fa0b5SDaniel P. Berrangé 
24477b5fa0b5SDaniel P. Berrangé             switch (action) {
24487b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_SHUTDOWN:
24497b5fa0b5SDaniel P. Berrangé                 qemu_system_powerdown_request();
24507b5fa0b5SDaniel P. Berrangé                 break;
24517b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_REBOOT:
24527b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24537b5fa0b5SDaniel P. Berrangé                 break;
24547b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_RESET:
24557b5fa0b5SDaniel P. Berrangé                 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
24567b5fa0b5SDaniel P. Berrangé                 break;
24577b5fa0b5SDaniel P. Berrangé             default:
24587b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24597b5fa0b5SDaniel P. Berrangé                 break;
24607b5fa0b5SDaniel P. Berrangé             }
24617b5fa0b5SDaniel P. Berrangé         }
24627b5fa0b5SDaniel P. Berrangé         break;
24633e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
24643e230dd2SCorentin Chary         if (len == 1)
24653e230dd2SCorentin Chary             return 2;
24663e230dd2SCorentin Chary 
24673e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
24683e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
24693e230dd2SCorentin Chary             if (len == 2)
24703e230dd2SCorentin Chary                 return 12;
24713e230dd2SCorentin Chary 
24723e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
24733e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
24743e230dd2SCorentin Chary             break;
24753e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
24763e230dd2SCorentin Chary             if (len == 2)
24773e230dd2SCorentin Chary                 return 4;
24783e230dd2SCorentin Chary 
24793e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
24803e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2481adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_enable(vs, vs->ioc);
24823e230dd2SCorentin Chary                 audio_add(vs);
24833e230dd2SCorentin Chary                 break;
24843e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2485adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_disable(vs, vs->ioc);
24863e230dd2SCorentin Chary                 audio_del(vs);
24873e230dd2SCorentin Chary                 break;
24883e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
24893e230dd2SCorentin Chary                 if (len == 4)
24903e230dd2SCorentin Chary                     return 10;
24913e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
249285bc5852SKővágó, Zoltán                 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
249385bc5852SKővágó, Zoltán                 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
249485bc5852SKővágó, Zoltán                 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
249585bc5852SKővágó, Zoltán                 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
249685bc5852SKővágó, Zoltán                 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
249785bc5852SKővágó, Zoltán                 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
24983e230dd2SCorentin Chary                 default:
2499153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
25003e230dd2SCorentin Chary                     vnc_client_error(vs);
25013e230dd2SCorentin Chary                     break;
25023e230dd2SCorentin Chary                 }
25033e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
25043e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2505090fdc83SMarc-André Lureau                     VNC_DEBUG("Invalid audio channel count %d\n",
25063e230dd2SCorentin Chary                               read_u8(data, 5));
25073e230dd2SCorentin Chary                     vnc_client_error(vs);
25083e230dd2SCorentin Chary                     break;
25093e230dd2SCorentin Chary                 }
2510cf070658SDaniel P. Berrangé                 freq = read_u32(data, 6);
2511cf070658SDaniel P. Berrangé                 /* No official limit for protocol, but 48khz is a sensible
2512cf070658SDaniel P. Berrangé                  * upper bound for trustworthy clients, and this limit
2513cf070658SDaniel P. Berrangé                  * protects calculations involving 'vs->as.freq' later.
2514cf070658SDaniel P. Berrangé                  */
2515cf070658SDaniel P. Berrangé                 if (freq > 48000) {
2516cf070658SDaniel P. Berrangé                     VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2517cf070658SDaniel P. Berrangé                     vnc_client_error(vs);
2518cf070658SDaniel P. Berrangé                     break;
2519cf070658SDaniel P. Berrangé                 }
2520cf070658SDaniel P. Berrangé                 vs->as.freq = freq;
2521adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_format(
2522adc8fce8SDaniel P. Berrangé                     vs, vs->ioc, vs->as.fmt, vs->as.nchannels, vs->as.freq);
25233e230dd2SCorentin Chary                 break;
25243e230dd2SCorentin Chary             default:
2525153130cdSDaniel P. Berrange                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
25263e230dd2SCorentin Chary                 vnc_client_error(vs);
25273e230dd2SCorentin Chary                 break;
25283e230dd2SCorentin Chary             }
25293e230dd2SCorentin Chary             break;
25303e230dd2SCorentin Chary 
25313e230dd2SCorentin Chary         default:
2532153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
25333e230dd2SCorentin Chary             vnc_client_error(vs);
25343e230dd2SCorentin Chary             break;
25353e230dd2SCorentin Chary         }
25363e230dd2SCorentin Chary         break;
2537763deea7SGerd Hoffmann     case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2538763deea7SGerd Hoffmann     {
2539763deea7SGerd Hoffmann         size_t size;
2540763deea7SGerd Hoffmann         uint8_t screens;
2541adc8fce8SDaniel P. Berrangé         int w, h;
2542763deea7SGerd Hoffmann 
2543763deea7SGerd Hoffmann         if (len < 8) {
2544763deea7SGerd Hoffmann             return 8;
2545763deea7SGerd Hoffmann         }
2546763deea7SGerd Hoffmann 
2547763deea7SGerd Hoffmann         screens = read_u8(data, 6);
2548763deea7SGerd Hoffmann         size    = 8 + screens * 16;
2549763deea7SGerd Hoffmann         if (len < size) {
2550763deea7SGerd Hoffmann             return size;
2551763deea7SGerd Hoffmann         }
2552adc8fce8SDaniel P. Berrangé         w = read_u16(data, 2);
2553adc8fce8SDaniel P. Berrangé         h = read_u16(data, 4);
2554763deea7SGerd Hoffmann 
2555adc8fce8SDaniel P. Berrangé         trace_vnc_msg_client_set_desktop_size(vs, vs->ioc, w, h, screens);
2556763deea7SGerd Hoffmann         if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2557763deea7SGerd Hoffmann             QemuUIInfo info;
2558763deea7SGerd Hoffmann             memset(&info, 0, sizeof(info));
2559adc8fce8SDaniel P. Berrangé             info.width = w;
2560adc8fce8SDaniel P. Berrangé             info.height = h;
2561763deea7SGerd Hoffmann             dpy_set_ui_info(vs->vd->dcl.con, &info);
2562763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2563763deea7SGerd Hoffmann         } else {
2564763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2565763deea7SGerd Hoffmann         }
2566763deea7SGerd Hoffmann 
2567763deea7SGerd Hoffmann         break;
2568763deea7SGerd Hoffmann     }
25693e230dd2SCorentin Chary     default:
2570153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
25713e230dd2SCorentin Chary         vnc_client_error(vs);
25723e230dd2SCorentin Chary         break;
25733e230dd2SCorentin Chary     }
25743e230dd2SCorentin Chary 
2575e2b72cb6SDaniel P. Berrange     vnc_update_throttle_offset(vs);
25763e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
25773e230dd2SCorentin Chary     return 0;
25783e230dd2SCorentin Chary }
25793e230dd2SCorentin Chary 
25803e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
25813e230dd2SCorentin Chary {
25823e230dd2SCorentin Chary     char buf[1024];
25838cf36489SGerd Hoffmann     VncShareMode mode;
25843e230dd2SCorentin Chary     int size;
25853e230dd2SCorentin Chary 
25868cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
25878cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
25888cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
25898cf36489SGerd Hoffmann         /*
25908cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
25918cf36489SGerd Hoffmann          *
25928cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
25938cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
25948cf36489SGerd Hoffmann          * reasons.
25958cf36489SGerd Hoffmann          */
25968cf36489SGerd Hoffmann         break;
25978cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
25988cf36489SGerd Hoffmann         /*
25998cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
26008cf36489SGerd Hoffmann          *
26018cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
26028cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
26038cf36489SGerd Hoffmann          * as no exclusive connection exists.
26048cf36489SGerd Hoffmann          *
26058cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
26068cf36489SGerd Hoffmann          */
26078cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
26088cf36489SGerd Hoffmann             VncState *client;
26098cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
26108cf36489SGerd Hoffmann                 if (vs == client) {
26118cf36489SGerd Hoffmann                     continue;
26128cf36489SGerd Hoffmann                 }
26138cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
26148cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
26158cf36489SGerd Hoffmann                     continue;
26168cf36489SGerd Hoffmann                 }
26178cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
26188cf36489SGerd Hoffmann             }
26198cf36489SGerd Hoffmann         }
26208cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
26218cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
26228cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
26238cf36489SGerd Hoffmann                 return 0;
26248cf36489SGerd Hoffmann             }
26258cf36489SGerd Hoffmann         }
26268cf36489SGerd Hoffmann         break;
26278cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
26288cf36489SGerd Hoffmann         /*
26298cf36489SGerd Hoffmann          * Policy: Shared connects only.
26308cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
26318cf36489SGerd Hoffmann          *
26328cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
26338cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
26348cf36489SGerd Hoffmann          * client disconnect everybody else.
26358cf36489SGerd Hoffmann          */
26368cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
26378cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
26388cf36489SGerd Hoffmann             return 0;
26398cf36489SGerd Hoffmann         }
26408cf36489SGerd Hoffmann         break;
26418cf36489SGerd Hoffmann     }
26428cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
26438cf36489SGerd Hoffmann 
2644e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2645e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2646e5f34cddSGerd Hoffmann         return 0;
2647e5f34cddSGerd Hoffmann     }
2648e5f34cddSGerd Hoffmann 
26494c956bd8SDaniel P. Berrange     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
26504c956bd8SDaniel P. Berrange            pixman_image_get_width(vs->vd->server) >= 0);
26514c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
26524c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
2653bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2654bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
26553e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
26563e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
26573e230dd2SCorentin Chary 
26583e230dd2SCorentin Chary     pixel_format_message(vs);
26593e230dd2SCorentin Chary 
266097efe4f9SThomas Huth     if (qemu_name) {
26613e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
266297efe4f9SThomas Huth         if (size > sizeof(buf)) {
266397efe4f9SThomas Huth             size = sizeof(buf);
266497efe4f9SThomas Huth         }
266597efe4f9SThomas Huth     } else {
26663e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
266797efe4f9SThomas Huth     }
26683e230dd2SCorentin Chary 
26693e230dd2SCorentin Chary     vnc_write_u32(vs, size);
26703e230dd2SCorentin Chary     vnc_write(vs, buf, size);
26713e230dd2SCorentin Chary     vnc_flush(vs);
26723e230dd2SCorentin Chary 
26733e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2674fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
26753e230dd2SCorentin Chary 
26763e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
26773e230dd2SCorentin Chary 
26783e230dd2SCorentin Chary     return 0;
26793e230dd2SCorentin Chary }
26803e230dd2SCorentin Chary 
26813e230dd2SCorentin Chary void start_client_init(VncState *vs)
26823e230dd2SCorentin Chary {
26833e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
26843e230dd2SCorentin Chary }
26853e230dd2SCorentin Chary 
26864347e638SRichard Henderson static void authentication_failed(VncState *vs)
26874347e638SRichard Henderson {
26884347e638SRichard Henderson     vnc_write_u32(vs, 1); /* Reject auth */
26894347e638SRichard Henderson     if (vs->minor >= 8) {
26904347e638SRichard Henderson         static const char err[] = "Authentication failed";
26914347e638SRichard Henderson         vnc_write_u32(vs, sizeof(err));
26924347e638SRichard Henderson         vnc_write(vs, err, sizeof(err));
26934347e638SRichard Henderson     }
26944347e638SRichard Henderson     vnc_flush(vs);
26954347e638SRichard Henderson     vnc_client_error(vs);
26964347e638SRichard Henderson }
26974347e638SRichard Henderson 
26983e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
26993e230dd2SCorentin Chary {
27003e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2701800567a6SDaniel P. Berrange     size_t i, pwlen;
27023e230dd2SCorentin Chary     unsigned char key[8];
27033c9405a0SGerd Hoffmann     time_t now = time(NULL);
270460928458SGonglei     QCryptoCipher *cipher = NULL;
2705800567a6SDaniel P. Berrange     Error *err = NULL;
27063e230dd2SCorentin Chary 
27071cd20f8bSAnthony Liguori     if (!vs->vd->password) {
27087364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
27096bffdf0fSGerd Hoffmann         goto reject;
27103e230dd2SCorentin Chary     }
27113c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
27127364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
27133c9405a0SGerd Hoffmann         goto reject;
27143c9405a0SGerd Hoffmann     }
27153e230dd2SCorentin Chary 
27163e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
27173e230dd2SCorentin Chary 
27183e230dd2SCorentin Chary     /* Calculate the expected challenge response */
27193e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
27203e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
27213e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2722800567a6SDaniel P. Berrange 
2723800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
2724800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_DES_RFB,
2725800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2726800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2727800567a6SDaniel P. Berrange         &err);
2728800567a6SDaniel P. Berrange     if (!cipher) {
27297364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2730800567a6SDaniel P. Berrange                             error_get_pretty(err));
2731800567a6SDaniel P. Berrange         error_free(err);
2732800567a6SDaniel P. Berrange         goto reject;
2733800567a6SDaniel P. Berrange     }
2734800567a6SDaniel P. Berrange 
2735a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2736800567a6SDaniel P. Berrange                                vs->challenge,
2737800567a6SDaniel P. Berrange                                response,
2738800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2739800567a6SDaniel P. Berrange                                &err) < 0) {
27407364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2741800567a6SDaniel P. Berrange                             error_get_pretty(err));
2742800567a6SDaniel P. Berrange         error_free(err);
2743800567a6SDaniel P. Berrange         goto reject;
2744800567a6SDaniel P. Berrange     }
27453e230dd2SCorentin Chary 
27463e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
27473e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
27487364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
27496bffdf0fSGerd Hoffmann         goto reject;
27506bffdf0fSGerd Hoffmann     } else {
27517364dbdaSDaniel P. Berrange         trace_vnc_auth_pass(vs, vs->auth);
27526bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
27536bffdf0fSGerd Hoffmann         vnc_flush(vs);
27546bffdf0fSGerd Hoffmann 
27556bffdf0fSGerd Hoffmann         start_client_init(vs);
27566bffdf0fSGerd Hoffmann     }
275760928458SGonglei 
275860928458SGonglei     qcrypto_cipher_free(cipher);
27596bffdf0fSGerd Hoffmann     return 0;
27606bffdf0fSGerd Hoffmann 
27616bffdf0fSGerd Hoffmann reject:
27624347e638SRichard Henderson     authentication_failed(vs);
276360928458SGonglei     qcrypto_cipher_free(cipher);
27643e230dd2SCorentin Chary     return 0;
27653e230dd2SCorentin Chary }
27663e230dd2SCorentin Chary 
27673e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
27683e230dd2SCorentin Chary {
2769f7b2502cSRichard Henderson     Error *err = NULL;
2770f7b2502cSRichard Henderson 
2771f7b2502cSRichard Henderson     if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2772f7b2502cSRichard Henderson         trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2773f7b2502cSRichard Henderson                             error_get_pretty(err));
2774f7b2502cSRichard Henderson         error_free(err);
2775f7b2502cSRichard Henderson         authentication_failed(vs);
2776f7b2502cSRichard Henderson         return;
2777f7b2502cSRichard Henderson     }
2778f7b2502cSRichard Henderson 
27793e230dd2SCorentin Chary     /* Send client a 'random' challenge */
27803e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
27813e230dd2SCorentin Chary     vnc_flush(vs);
27823e230dd2SCorentin Chary 
27833e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
27843e230dd2SCorentin Chary }
27853e230dd2SCorentin Chary 
27863e230dd2SCorentin Chary 
27873e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
27883e230dd2SCorentin Chary {
27893e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
27903e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
27917e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
27927364dbdaSDaniel P. Berrange        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
27934347e638SRichard Henderson        authentication_failed(vs);
27943e230dd2SCorentin Chary     } else { /* Accept requested auth */
27957364dbdaSDaniel P. Berrange        trace_vnc_auth_start(vs, vs->auth);
27967e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
27973e230dd2SCorentin Chary        case VNC_AUTH_NONE:
27983e230dd2SCorentin Chary            if (vs->minor >= 8) {
27993e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
28003e230dd2SCorentin Chary                vnc_flush(vs);
28013e230dd2SCorentin Chary            }
28027364dbdaSDaniel P. Berrange            trace_vnc_auth_pass(vs, vs->auth);
28033e230dd2SCorentin Chary            start_client_init(vs);
28043e230dd2SCorentin Chary            break;
28053e230dd2SCorentin Chary 
28063e230dd2SCorentin Chary        case VNC_AUTH_VNC:
28073e230dd2SCorentin Chary            start_auth_vnc(vs);
28083e230dd2SCorentin Chary            break;
28093e230dd2SCorentin Chary 
28103e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
28113e230dd2SCorentin Chary            start_auth_vencrypt(vs);
28123e230dd2SCorentin Chary            break;
28133e230dd2SCorentin Chary 
28143e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
28153e230dd2SCorentin Chary        case VNC_AUTH_SASL:
28163e230dd2SCorentin Chary            start_auth_sasl(vs);
28173e230dd2SCorentin Chary            break;
28183e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
28193e230dd2SCorentin Chary 
28203e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
28217364dbdaSDaniel P. Berrange            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
28224347e638SRichard Henderson            authentication_failed(vs);
28233e230dd2SCorentin Chary        }
28243e230dd2SCorentin Chary     }
28253e230dd2SCorentin Chary     return 0;
28263e230dd2SCorentin Chary }
28273e230dd2SCorentin Chary 
28283e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
28293e230dd2SCorentin Chary {
28303e230dd2SCorentin Chary     char local[13];
28313e230dd2SCorentin Chary 
28323e230dd2SCorentin Chary     memcpy(local, version, 12);
28333e230dd2SCorentin Chary     local[12] = 0;
28343e230dd2SCorentin Chary 
28353e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
28363e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
28373e230dd2SCorentin Chary         vnc_client_error(vs);
28383e230dd2SCorentin Chary         return 0;
28393e230dd2SCorentin Chary     }
28403e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
28413e230dd2SCorentin Chary     if (vs->major != 3 ||
28423e230dd2SCorentin Chary         (vs->minor != 3 &&
28433e230dd2SCorentin Chary          vs->minor != 4 &&
28443e230dd2SCorentin Chary          vs->minor != 5 &&
28453e230dd2SCorentin Chary          vs->minor != 7 &&
28463e230dd2SCorentin Chary          vs->minor != 8)) {
28473e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
28483e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
28493e230dd2SCorentin Chary         vnc_flush(vs);
28503e230dd2SCorentin Chary         vnc_client_error(vs);
28513e230dd2SCorentin Chary         return 0;
28523e230dd2SCorentin Chary     }
28533e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
28543e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
28553e230dd2SCorentin Chary      */
28563e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
28573e230dd2SCorentin Chary         vs->minor = 3;
28583e230dd2SCorentin Chary 
28593e230dd2SCorentin Chary     if (vs->minor == 3) {
28607364dbdaSDaniel P. Berrange         trace_vnc_auth_start(vs, vs->auth);
28617e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
28627e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
28633e230dd2SCorentin Chary             vnc_flush(vs);
28647364dbdaSDaniel P. Berrange             trace_vnc_auth_pass(vs, vs->auth);
28653e230dd2SCorentin Chary             start_client_init(vs);
28667e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
28673e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
28687e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
28693e230dd2SCorentin Chary             vnc_flush(vs);
28703e230dd2SCorentin Chary             start_auth_vnc(vs);
28713e230dd2SCorentin Chary        } else {
28727364dbdaSDaniel P. Berrange             trace_vnc_auth_fail(vs, vs->auth,
28737364dbdaSDaniel P. Berrange                                 "Unsupported auth method for v3.3", "");
28743e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
28753e230dd2SCorentin Chary             vnc_flush(vs);
28763e230dd2SCorentin Chary             vnc_client_error(vs);
28773e230dd2SCorentin Chary        }
28783e230dd2SCorentin Chary     } else {
28793e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
28807e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
28813e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
28823e230dd2SCorentin Chary         vnc_flush(vs);
28833e230dd2SCorentin Chary     }
28843e230dd2SCorentin Chary 
28853e230dd2SCorentin Chary     return 0;
28863e230dd2SCorentin Chary }
28873e230dd2SCorentin Chary 
2888999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2889999342a0SCorentin Chary {
2890999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2891999342a0SCorentin Chary 
2892999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2893999342a0SCorentin Chary }
2894999342a0SCorentin Chary 
28957d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
28967d964c9dSCorentin Chary {
28977d964c9dSCorentin Chary     int i, j;
28987d964c9dSCorentin Chary 
28997d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
29007d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
29017d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
29027d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
29037d964c9dSCorentin Chary 
2904207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2905207f328aSCorentin Chary         for (i = x; i <= w; i++) {
29067d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
29077d964c9dSCorentin Chary         }
29087d964c9dSCorentin Chary     }
29097d964c9dSCorentin Chary }
29107d964c9dSCorentin Chary 
29117d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
29127d964c9dSCorentin Chary {
29137d964c9dSCorentin Chary     VncState *vs;
29147d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
29157d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
29167d964c9dSCorentin Chary     int has_dirty = 0;
29177d964c9dSCorentin Chary 
29185a3804dbSMarc-André Lureau     y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
29195a3804dbSMarc-André Lureau     x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
29207d964c9dSCorentin Chary 
29217d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2922bc2429b9SCorentin Chary         int j;
29237d964c9dSCorentin Chary 
29247d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
29257d964c9dSCorentin Chary         if (vs->output.offset) {
29267d964c9dSCorentin Chary             continue;
29277d964c9dSCorentin Chary         }
29287d964c9dSCorentin Chary 
29297d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
29307d964c9dSCorentin Chary             continue;
29317d964c9dSCorentin Chary         }
2932207f328aSCorentin Chary 
29337d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
29347d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2935b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2936b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2937b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
29387d964c9dSCorentin Chary         }
29397d964c9dSCorentin Chary         has_dirty++;
29407d964c9dSCorentin Chary     }
2941207f328aSCorentin Chary 
29427d964c9dSCorentin Chary     return has_dirty;
29437d964c9dSCorentin Chary }
29447d964c9dSCorentin Chary 
29457d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2946999342a0SCorentin Chary {
2947eebe0b79SGerd Hoffmann     int width = MIN(pixman_image_get_width(vd->guest.fb),
2948eebe0b79SGerd Hoffmann                     pixman_image_get_width(vd->server));
2949eebe0b79SGerd Hoffmann     int height = MIN(pixman_image_get_height(vd->guest.fb),
2950eebe0b79SGerd Hoffmann                      pixman_image_get_height(vd->server));
2951999342a0SCorentin Chary     int x, y;
2952999342a0SCorentin Chary     struct timeval res;
29537d964c9dSCorentin Chary     int has_dirty = 0;
2954999342a0SCorentin Chary 
29559f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
29569f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2957999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2958999342a0SCorentin Chary 
2959999342a0SCorentin Chary             rect->updated = false;
2960999342a0SCorentin Chary         }
2961999342a0SCorentin Chary     }
2962999342a0SCorentin Chary 
2963ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2964999342a0SCorentin Chary 
2965999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
29667d964c9dSCorentin Chary         return has_dirty;
2967999342a0SCorentin Chary     }
2968999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
2969999342a0SCorentin Chary 
29709f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
29719f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2972999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2973999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
2974999342a0SCorentin Chary             struct timeval min, max;
2975999342a0SCorentin Chary 
2976999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
2977999342a0SCorentin Chary                 continue ;
2978999342a0SCorentin Chary             }
2979999342a0SCorentin Chary 
2980999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2981ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
2982999342a0SCorentin Chary 
2983999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2984999342a0SCorentin Chary                 rect->freq = 0;
29857d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2986999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
2987999342a0SCorentin Chary                 continue ;
2988999342a0SCorentin Chary             }
2989999342a0SCorentin Chary 
2990999342a0SCorentin Chary             min = rect->times[rect->idx];
2991999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2992ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
2993999342a0SCorentin Chary 
2994999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2995999342a0SCorentin Chary             rect->freq /= count;
2996999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
2997999342a0SCorentin Chary         }
2998999342a0SCorentin Chary     }
29997d964c9dSCorentin Chary     return has_dirty;
3000999342a0SCorentin Chary }
3001999342a0SCorentin Chary 
3002999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
3003999342a0SCorentin Chary {
3004999342a0SCorentin Chary     int i, j;
3005999342a0SCorentin Chary     double total = 0;
3006999342a0SCorentin Chary     int num = 0;
3007999342a0SCorentin Chary 
30085a3804dbSMarc-André Lureau     x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
30095a3804dbSMarc-André Lureau     y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
3010999342a0SCorentin Chary 
3011999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
3012999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
3013999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
3014999342a0SCorentin Chary             num++;
3015999342a0SCorentin Chary         }
3016999342a0SCorentin Chary     }
3017999342a0SCorentin Chary 
3018999342a0SCorentin Chary     if (num) {
3019999342a0SCorentin Chary         return total / num;
3020999342a0SCorentin Chary     } else {
3021999342a0SCorentin Chary         return 0;
3022999342a0SCorentin Chary     }
3023999342a0SCorentin Chary }
3024999342a0SCorentin Chary 
3025999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
3026999342a0SCorentin Chary {
3027999342a0SCorentin Chary     VncRectStat *rect;
3028999342a0SCorentin Chary 
3029999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
3030999342a0SCorentin Chary     if (rect->updated) {
3031999342a0SCorentin Chary         return ;
3032999342a0SCorentin Chary     }
3033999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
3034999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3035999342a0SCorentin Chary     rect->updated = true;
3036999342a0SCorentin Chary }
3037999342a0SCorentin Chary 
30383e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
30393e230dd2SCorentin Chary {
3040bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
3041bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
3042bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
3043bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
3044eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
304512b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
30463e230dd2SCorentin Chary     VncState *vs;
30473e230dd2SCorentin Chary     int has_dirty = 0;
30489f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
30493e230dd2SCorentin Chary 
305080e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
3051999342a0SCorentin Chary 
305280e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
3053999342a0SCorentin Chary         gettimeofday(&tv, NULL);
30547d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
305580e0c8c3SCorentin Chary     }
3056999342a0SCorentin Chary 
30573e230dd2SCorentin Chary     /*
30583e230dd2SCorentin Chary      * Walk through the guest dirty map.
30593e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
30603e230dd2SCorentin Chary      * Update server dirty map.
30613e230dd2SCorentin Chary      */
3062bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3063eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
3064eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
3065bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3066bea60dd7SPeter Lieven                     server_stride);
30679f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
30689f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
30699f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
307012b316d4SPeter Lieven     } else {
3071eb8934b0SGerd Hoffmann         int guest_bpp =
3072eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
307312b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
307412b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
3075949ed4c2SPhilippe Mathieu-Daudé         guest_ll = pixman_image_get_width(vd->guest.fb)
3076949ed4c2SPhilippe Mathieu-Daudé                    * DIV_ROUND_UP(guest_bpp, 8);
30779f64916dSGerd Hoffmann     }
3078eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
307912b316d4SPeter Lieven 
308012b316d4SPeter Lieven     for (;;) {
30813e230dd2SCorentin Chary         int x;
308212b316d4SPeter Lieven         uint8_t *guest_ptr, *server_ptr;
308312b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
308412b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(&vd->guest),
308512b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(&vd->guest));
308612b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
308712b316d4SPeter Lieven             /* no more dirty bits */
308812b316d4SPeter Lieven             break;
308912b316d4SPeter Lieven         }
309012b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
309112b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
309212b316d4SPeter Lieven 
309312b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
30943e230dd2SCorentin Chary 
30959f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3096bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
30979f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
30989f64916dSGerd Hoffmann         } else {
309912b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
31009f64916dSGerd Hoffmann         }
310112b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
31023e230dd2SCorentin Chary 
310312b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
310412b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3105bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
310612b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
31073e230dd2SCorentin Chary                 continue;
3108b4c85ddcSPeter Lieven             }
3109eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
3110eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
3111bea60dd7SPeter Lieven             }
3112eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
3113bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
31143e230dd2SCorentin Chary                 continue;
3115b4c85ddcSPeter Lieven             }
3116bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
311712b316d4SPeter Lieven             if (!vd->non_adaptive) {
311812b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
311912b316d4SPeter Lieven                                  y, &tv);
312012b316d4SPeter Lieven             }
31213e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
312212b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
31233e230dd2SCorentin Chary             }
31243e230dd2SCorentin Chary             has_dirty++;
31253e230dd2SCorentin Chary         }
312612b316d4SPeter Lieven 
312712b316d4SPeter Lieven         y++;
31283e230dd2SCorentin Chary     }
31299f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
31303e230dd2SCorentin Chary     return has_dirty;
31313e230dd2SCorentin Chary }
31323e230dd2SCorentin Chary 
31330f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
31343e230dd2SCorentin Chary {
31350f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
31363e230dd2SCorentin Chary     VncState *vs, *vn;
31373e230dd2SCorentin Chary     int has_dirty, rects = 0;
31383e230dd2SCorentin Chary 
31399d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
31409d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
31419d6b2070SChenLiang         return;
31429d6b2070SChenLiang     }
31439d6b2070SChenLiang 
31441d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
31453e230dd2SCorentin Chary 
3146bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
31470f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3148bd023f95SCorentin Chary         return;
3149bd023f95SCorentin Chary     }
3150bd023f95SCorentin Chary 
31513e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
3152bd023f95SCorentin Chary     vnc_unlock_display(vd);
31533e230dd2SCorentin Chary 
31543e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
31556af998dbSDaniel P. Berrange         rects += vnc_update_client(vs, has_dirty);
31563e230dd2SCorentin Chary         /* vs might be free()ed here */
31573e230dd2SCorentin Chary     }
3158bd023f95SCorentin Chary 
31593e230dd2SCorentin Chary     if (has_dirty && rects) {
31600f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
31610f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
31620f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
31630f7b2864SGerd Hoffmann         }
31643e230dd2SCorentin Chary     } else {
31650f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
31660f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
31670f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
31683e230dd2SCorentin Chary         }
31693e230dd2SCorentin Chary     }
31703e230dd2SCorentin Chary }
31713e230dd2SCorentin Chary 
317204d2529dSDaniel P. Berrange static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
31732c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
31743e230dd2SCorentin Chary {
3175fedf0d35SMarkus Armbruster     VncState *vs = g_new0(VncState, 1);
317690cd03a3SDaniel P. Berrange     bool first_client = QTAILQ_EMPTY(&vd->clients);
31777d964c9dSCorentin Chary     int i;
31787d964c9dSCorentin Chary 
3179ad6374c4SDaniel P. Berrange     trace_vnc_client_connect(vs, sioc);
31806bf21f3dSLi Qiang     vs->zrle = g_new0(VncZrle, 1);
31816bf21f3dSLi Qiang     vs->tight = g_new0(VncTight, 1);
3182f31f9c10SGerd Hoffmann     vs->magic = VNC_MAGIC;
318304d2529dSDaniel P. Berrange     vs->sioc = sioc;
318404d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->sioc));
318504d2529dSDaniel P. Berrange     vs->ioc = QIO_CHANNEL(sioc);
318604d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->ioc));
3187d616ccc5SGerd Hoffmann     vs->vd = vd;
31887e7e2ebcSDaniel P. Berrange 
318904d2529dSDaniel P. Berrange     buffer_init(&vs->input,          "vnc-input/%p", sioc);
319004d2529dSDaniel P. Berrange     buffer_init(&vs->output,         "vnc-output/%p", sioc);
319104d2529dSDaniel P. Berrange     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3192543b9580SGerd Hoffmann 
31936bf21f3dSLi Qiang     buffer_init(&vs->tight->tight,    "vnc-tight/%p", sioc);
31946bf21f3dSLi Qiang     buffer_init(&vs->tight->zlib,     "vnc-tight-zlib/%p", sioc);
31956bf21f3dSLi Qiang     buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3196543b9580SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
31976bf21f3dSLi Qiang     buffer_init(&vs->tight->jpeg,     "vnc-tight-jpeg/%p", sioc);
3198543b9580SGerd Hoffmann #endif
3199543b9580SGerd Hoffmann #ifdef CONFIG_VNC_PNG
32006bf21f3dSLi Qiang     buffer_init(&vs->tight->png,      "vnc-tight-png/%p", sioc);
3201543b9580SGerd Hoffmann #endif
320204d2529dSDaniel P. Berrange     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
32036bf21f3dSLi Qiang     buffer_init(&vs->zrle->zrle,      "vnc-zrle/%p", sioc);
32046bf21f3dSLi Qiang     buffer_init(&vs->zrle->fb,        "vnc-zrle-fb/%p", sioc);
32056bf21f3dSLi Qiang     buffer_init(&vs->zrle->zlib,      "vnc-zrle-zlib/%p", sioc);
3206543b9580SGerd Hoffmann 
32077e7e2ebcSDaniel P. Berrange     if (skipauth) {
32087e7e2ebcSDaniel P. Berrange         vs->auth = VNC_AUTH_NONE;
32097e7e2ebcSDaniel P. Berrange         vs->subauth = VNC_AUTH_INVALID;
32107e7e2ebcSDaniel P. Berrange     } else {
3211f9148c8aSDaniel P. Berrange         if (websocket) {
3212f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
3213f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
3214f9148c8aSDaniel P. Berrange         } else {
32157e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
32167e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
32177e7e2ebcSDaniel P. Berrange         }
3218f9148c8aSDaniel P. Berrange     }
321904d2529dSDaniel P. Berrange     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
322004d2529dSDaniel P. Berrange               sioc, websocket, vs->auth, vs->subauth);
32217e7e2ebcSDaniel P. Berrange 
32227267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
32237d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3224fedf0d35SMarkus Armbruster         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
32257d964c9dSCorentin Chary     }
32263e230dd2SCorentin Chary 
322704d2529dSDaniel P. Berrange     VNC_DEBUG("New client on socket %p\n", vs->sioc);
32280f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
322904d2529dSDaniel P. Berrange     qio_channel_set_blocking(vs->ioc, false, NULL);
3230a75d6f07SBrandon Carpenter     if (vs->ioc_tag) {
3231a75d6f07SBrandon Carpenter         g_source_remove(vs->ioc_tag);
3232a75d6f07SBrandon Carpenter     }
32337536ee4bSTim Hardeck     if (websocket) {
32347536ee4bSTim Hardeck         vs->websocket = 1;
323538e5756aSDaniel P. Berrange         if (vd->tlscreds) {
323604d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
32372ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32382ddafce7SDing Hui                 vncws_tls_handshake_io, vs, NULL);
32393e305e4aSDaniel P. Berrange         } else {
324004d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
32412ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32422ddafce7SDing Hui                 vncws_handshake_io, vs, NULL);
32430057a0d5STim Hardeck         }
324404d2529dSDaniel P. Berrange     } else {
324504d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
32462ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32472ddafce7SDing Hui             vnc_client_io, vs, NULL);
32487536ee4bSTim Hardeck     }
32493e230dd2SCorentin Chary 
32503e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3251fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
32528cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
32533e230dd2SCorentin Chary 
32543e230dd2SCorentin Chary     vs->last_x = -1;
32553e230dd2SCorentin Chary     vs->last_y = -1;
32563e230dd2SCorentin Chary 
32573e230dd2SCorentin Chary     vs->as.freq = 44100;
32583e230dd2SCorentin Chary     vs->as.nchannels = 2;
325985bc5852SKővágó, Zoltán     vs->as.fmt = AUDIO_FORMAT_S16;
32603e230dd2SCorentin Chary     vs->as.endianness = 0;
32613e230dd2SCorentin Chary 
3262bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3263175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3264bd023f95SCorentin Chary 
3265e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3266c7628bffSGerd Hoffmann     if (first_client) {
3267c7628bffSGerd Hoffmann         vnc_update_server_surface(vd);
3268c7628bffSGerd Hoffmann     }
32693e230dd2SCorentin Chary 
32701d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
32713e230dd2SCorentin Chary 
327290cd03a3SDaniel P. Berrange     if (!vs->websocket) {
3273dbee9897SDaniel P. Berrange         vnc_start_protocol(vs);
327490cd03a3SDaniel P. Berrange     }
327590cd03a3SDaniel P. Berrange 
327690cd03a3SDaniel P. Berrange     if (vd->num_connecting > vd->connections_limit) {
327790cd03a3SDaniel P. Berrange         QTAILQ_FOREACH(vs, &vd->clients, next) {
327890cd03a3SDaniel P. Berrange             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
327990cd03a3SDaniel P. Berrange                 vnc_disconnect_start(vs);
328090cd03a3SDaniel P. Berrange                 return;
328190cd03a3SDaniel P. Berrange             }
328290cd03a3SDaniel P. Berrange         }
328390cd03a3SDaniel P. Berrange     }
328490cd03a3SDaniel P. Berrange }
328590cd03a3SDaniel P. Berrange 
3286dbee9897SDaniel P. Berrange void vnc_start_protocol(VncState *vs)
328790cd03a3SDaniel P. Berrange {
32883e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
32893e230dd2SCorentin Chary     vnc_flush(vs);
32903e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
32913e230dd2SCorentin Chary 
32923e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
32933e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
32943e230dd2SCorentin Chary }
32953e230dd2SCorentin Chary 
329613e1d0e7SDaniel P. Berrange static void vnc_listen_io(QIONetListener *listener,
329713e1d0e7SDaniel P. Berrange                           QIOChannelSocket *cioc,
329804d2529dSDaniel P. Berrange                           void *opaque)
32993e230dd2SCorentin Chary {
3300bf01c179SDaniel P. Berrange     VncDisplay *vd = opaque;
330113e1d0e7SDaniel P. Berrange     bool isWebsock = listener == vd->wslistener;
33024ee74fa7SDaniel P. Berrange 
330313e1d0e7SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(cioc),
33044ee74fa7SDaniel P. Berrange                          isWebsock ? "vnc-ws-server" : "vnc-server");
330513e1d0e7SDaniel P. Berrange     qio_channel_set_delay(QIO_CHANNEL(cioc), false);
330613e1d0e7SDaniel P. Berrange     vnc_connect(vd, cioc, false, isWebsock);
33077536ee4bSTim Hardeck }
33087536ee4bSTim Hardeck 
33097c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
33107c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
33110f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
33127c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3313c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
331434da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
33157c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
33167c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
33177c20b4a3SGerd Hoffmann };
33187c20b4a3SGerd Hoffmann 
3319ab4f931eSFei Li void vnc_display_init(const char *id, Error **errp)
33203e230dd2SCorentin Chary {
3321bf01c179SDaniel P. Berrange     VncDisplay *vd;
33224db14629SGerd Hoffmann 
33234db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
33244db14629SGerd Hoffmann         return;
33254db14629SGerd Hoffmann     }
3326bf01c179SDaniel P. Berrange     vd = g_malloc0(sizeof(*vd));
33273e230dd2SCorentin Chary 
3328bf01c179SDaniel P. Berrange     vd->id = strdup(id);
3329bf01c179SDaniel P. Berrange     QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
33303e230dd2SCorentin Chary 
3331bf01c179SDaniel P. Berrange     QTAILQ_INIT(&vd->clients);
3332bf01c179SDaniel P. Berrange     vd->expires = TIME_MAX;
33333e230dd2SCorentin Chary 
333440066175SGerd Hoffmann     if (keyboard_layout) {
333540066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
3336ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym,
3337ab4f931eSFei Li                                               keyboard_layout, errp);
333840066175SGerd Hoffmann     } else {
3339ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
334040066175SGerd Hoffmann     }
33413e230dd2SCorentin Chary 
3342bf01c179SDaniel P. Berrange     if (!vd->kbd_layout) {
3343ab4f931eSFei Li         return;
3344bf01c179SDaniel P. Berrange     }
33453e230dd2SCorentin Chary 
3346bf01c179SDaniel P. Berrange     vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3347bf01c179SDaniel P. Berrange     vd->connections_limit = 32;
334812e29b16SDaniel P. Berrange 
3349bf01c179SDaniel P. Berrange     qemu_mutex_init(&vd->mutex);
3350bd023f95SCorentin Chary     vnc_start_worker_thread();
3351bd023f95SCorentin Chary 
3352bf01c179SDaniel P. Berrange     vd->dcl.ops = &dcl_ops;
3353bf01c179SDaniel P. Berrange     register_displaychangelistener(&vd->dcl);
3354c2f2ba49SGerd Hoffmann     vd->kbd = qkbd_state_init(vd->dcl.con);
33553e230dd2SCorentin Chary }
33563e230dd2SCorentin Chary 
33573e230dd2SCorentin Chary 
3358bf01c179SDaniel P. Berrange static void vnc_display_close(VncDisplay *vd)
33593e230dd2SCorentin Chary {
3360bf01c179SDaniel P. Berrange     if (!vd) {
33613e230dd2SCorentin Chary         return;
336204d2529dSDaniel P. Berrange     }
3363bf01c179SDaniel P. Berrange     vd->is_unix = false;
33644ee74fa7SDaniel P. Berrange 
336513e1d0e7SDaniel P. Berrange     if (vd->listener) {
336613e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->listener);
336713e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->listener));
336804d2529dSDaniel P. Berrange     }
336913e1d0e7SDaniel P. Berrange     vd->listener = NULL;
337013e1d0e7SDaniel P. Berrange 
337113e1d0e7SDaniel P. Berrange     if (vd->wslistener) {
337213e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->wslistener);
337313e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->wslistener));
33747536ee4bSTim Hardeck     }
337513e1d0e7SDaniel P. Berrange     vd->wslistener = NULL;
33764ee74fa7SDaniel P. Berrange 
3377bf01c179SDaniel P. Berrange     vd->auth = VNC_AUTH_INVALID;
3378bf01c179SDaniel P. Berrange     vd->subauth = VNC_AUTH_INVALID;
3379bf01c179SDaniel P. Berrange     if (vd->tlscreds) {
3380521534dfSZihao Chang         object_unref(OBJECT(vd->tlscreds));
3381bf01c179SDaniel P. Berrange         vd->tlscreds = NULL;
3382bf01c179SDaniel P. Berrange     }
3383b76806d4SDaniel P. Berrange     if (vd->tlsauthz) {
3384b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->tlsauthz));
3385b76806d4SDaniel P. Berrange         vd->tlsauthz = NULL;
3386b76806d4SDaniel P. Berrange     }
3387b76806d4SDaniel P. Berrange     g_free(vd->tlsauthzid);
3388b76806d4SDaniel P. Berrange     vd->tlsauthzid = NULL;
3389a54f0d2bSPierre Ossman     if (vd->lock_key_sync) {
3390a54f0d2bSPierre Ossman         qemu_remove_led_event_handler(vd->led);
33912dc120beSGerd Hoffmann         vd->led = NULL;
3392a54f0d2bSPierre Ossman     }
3393b76806d4SDaniel P. Berrange #ifdef CONFIG_VNC_SASL
3394b76806d4SDaniel P. Berrange     if (vd->sasl.authz) {
3395b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->sasl.authz));
3396b76806d4SDaniel P. Berrange         vd->sasl.authz = NULL;
3397b76806d4SDaniel P. Berrange     }
3398b76806d4SDaniel P. Berrange     g_free(vd->sasl.authzid);
3399b76806d4SDaniel P. Berrange     vd->sasl.authzid = NULL;
3400b76806d4SDaniel P. Berrange #endif
34013e230dd2SCorentin Chary }
34023e230dd2SCorentin Chary 
340314f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
34041cd20f8bSAnthony Liguori {
3405bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
34061cd20f8bSAnthony Liguori 
3407bf01c179SDaniel P. Berrange     if (!vd) {
3408a6aa9d3eSLuiz Capitulino         return -EINVAL;
34091cd20f8bSAnthony Liguori     }
3410bf01c179SDaniel P. Berrange     if (vd->auth == VNC_AUTH_NONE) {
3411cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
34127ea7d36eSMarkus Armbruster                                 "password auth using '-vnc ${dpy},password'.\n");
3413cf864569SGerd Hoffmann         return -EINVAL;
34141cd20f8bSAnthony Liguori     }
34151cd20f8bSAnthony Liguori 
3416bf01c179SDaniel P. Berrange     g_free(vd->password);
3417bf01c179SDaniel P. Berrange     vd->password = g_strdup(password);
3418a6aa9d3eSLuiz Capitulino 
3419a6aa9d3eSLuiz Capitulino     return 0;
34203e230dd2SCorentin Chary }
34213e230dd2SCorentin Chary 
342214f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
34233c9405a0SGerd Hoffmann {
3424bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
34253c9405a0SGerd Hoffmann 
3426bf01c179SDaniel P. Berrange     if (!vd) {
34271643f2b2SGerd Hoffmann         return -EINVAL;
34281643f2b2SGerd Hoffmann     }
34291643f2b2SGerd Hoffmann 
3430bf01c179SDaniel P. Berrange     vd->expires = expires;
34313c9405a0SGerd Hoffmann     return 0;
34323c9405a0SGerd Hoffmann }
34333c9405a0SGerd Hoffmann 
3434bf01c179SDaniel P. Berrange static void vnc_display_print_local_addr(VncDisplay *vd)
34353e230dd2SCorentin Chary {
3436bd269ebcSMarkus Armbruster     SocketAddress *addr;
34373e230dd2SCorentin Chary 
343813e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
34394ee74fa7SDaniel P. Berrange         return;
34404ee74fa7SDaniel P. Berrange     }
34414ee74fa7SDaniel P. Berrange 
3442b94b3c02SMarkus Armbruster     addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
344304d2529dSDaniel P. Berrange     if (!addr) {
344433df7bf3SPaolo Bonzini         return;
344504d2529dSDaniel P. Berrange     }
344604d2529dSDaniel P. Berrange 
3447bd269ebcSMarkus Armbruster     if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3448bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
344933df7bf3SPaolo Bonzini         return;
345004d2529dSDaniel P. Berrange     }
345133df7bf3SPaolo Bonzini     error_printf_unless_qmp("VNC server running on %s:%s\n",
3452bd269ebcSMarkus Armbruster                             addr->u.inet.host,
3453bd269ebcSMarkus Armbruster                             addr->u.inet.port);
3454bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
34553e230dd2SCorentin Chary }
34563e230dd2SCorentin Chary 
34574db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
34584db14629SGerd Hoffmann     .name = "vnc",
34594db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
34604db14629SGerd Hoffmann     .implied_opt_name = "vnc",
34614db14629SGerd Hoffmann     .desc = {
34624db14629SGerd Hoffmann         {
34634db14629SGerd Hoffmann             .name = "vnc",
34644db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
34654db14629SGerd Hoffmann         },{
34664db14629SGerd Hoffmann             .name = "websocket",
34674db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
34684db14629SGerd Hoffmann         },{
34693e305e4aSDaniel P. Berrange             .name = "tls-creds",
34703e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
34713e305e4aSDaniel P. Berrange         },{
34724db14629SGerd Hoffmann             .name = "share",
34734db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
34744db14629SGerd Hoffmann         },{
34751d0d59feSGerd Hoffmann             .name = "display",
34761d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
34771d0d59feSGerd Hoffmann         },{
34781d0d59feSGerd Hoffmann             .name = "head",
34791d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
34801d0d59feSGerd Hoffmann         },{
3481e5f34cddSGerd Hoffmann             .name = "connections",
3482e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3483e5f34cddSGerd Hoffmann         },{
348488428b7aSGonglei             .name = "to",
348588428b7aSGonglei             .type = QEMU_OPT_NUMBER,
348688428b7aSGonglei         },{
348788428b7aSGonglei             .name = "ipv4",
348888428b7aSGonglei             .type = QEMU_OPT_BOOL,
348988428b7aSGonglei         },{
349088428b7aSGonglei             .name = "ipv6",
349188428b7aSGonglei             .type = QEMU_OPT_BOOL,
349288428b7aSGonglei         },{
34934db14629SGerd Hoffmann             .name = "password",
34944db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
34954db14629SGerd Hoffmann         },{
34966c6840e9SDaniel P. Berrangé             .name = "password-secret",
34976c6840e9SDaniel P. Berrangé             .type = QEMU_OPT_STRING,
34986c6840e9SDaniel P. Berrangé         },{
34994db14629SGerd Hoffmann             .name = "reverse",
35004db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35014db14629SGerd Hoffmann         },{
35024db14629SGerd Hoffmann             .name = "lock-key-sync",
35034db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35044db14629SGerd Hoffmann         },{
3505c5ce8333SGerd Hoffmann             .name = "key-delay-ms",
3506c5ce8333SGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3507c5ce8333SGerd Hoffmann         },{
35084db14629SGerd Hoffmann             .name = "sasl",
35094db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35104db14629SGerd Hoffmann         },{
35114db14629SGerd Hoffmann             .name = "acl",
35124db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35134db14629SGerd Hoffmann         },{
351455cf09a0SDaniel P. Berrange             .name = "tls-authz",
351555cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
351655cf09a0SDaniel P. Berrange         },{
351755cf09a0SDaniel P. Berrange             .name = "sasl-authz",
351855cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
351955cf09a0SDaniel P. Berrange         },{
35204db14629SGerd Hoffmann             .name = "lossy",
35214db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35224db14629SGerd Hoffmann         },{
35234db14629SGerd Hoffmann             .name = "non-adaptive",
35244db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
3525f0b9f36dSKővágó, Zoltán         },{
3526f0b9f36dSKővágó, Zoltán             .name = "audiodev",
3527f0b9f36dSKővágó, Zoltán             .type = QEMU_OPT_STRING,
35287b5fa0b5SDaniel P. Berrangé         },{
35297b5fa0b5SDaniel P. Berrangé             .name = "power-control",
35307b5fa0b5SDaniel P. Berrangé             .type = QEMU_OPT_BOOL,
35314db14629SGerd Hoffmann         },
35324db14629SGerd Hoffmann         { /* end of list */ }
35334db14629SGerd Hoffmann     },
35344db14629SGerd Hoffmann };
35354db14629SGerd Hoffmann 
35360dd72e15SDaniel P. Berrange 
35373e305e4aSDaniel P. Berrange static int
3538eda24e18SDaniel P. Berrange vnc_display_setup_auth(int *auth,
3539eda24e18SDaniel P. Berrange                        int *subauth,
3540eda24e18SDaniel P. Berrange                        QCryptoTLSCreds *tlscreds,
35410dd72e15SDaniel P. Berrange                        bool password,
35420dd72e15SDaniel P. Berrange                        bool sasl,
35433e305e4aSDaniel P. Berrange                        bool websocket,
35443e305e4aSDaniel P. Berrange                        Error **errp)
35450dd72e15SDaniel P. Berrange {
35460dd72e15SDaniel P. Berrange     /*
35470dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
35480dd72e15SDaniel P. Berrange      *
35490dd72e15SDaniel P. Berrange      *   1. none
35500dd72e15SDaniel P. Berrange      *   2. vnc
35510dd72e15SDaniel P. Berrange      *   3. sasl
35520dd72e15SDaniel P. Berrange      *
35530dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
35540dd72e15SDaniel P. Berrange      *
35550dd72e15SDaniel P. Berrange      *   1. clear
35560dd72e15SDaniel P. Berrange      *   2. tls
35570dd72e15SDaniel P. Berrange      *
35580dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
35590dd72e15SDaniel P. Berrange      *
35600dd72e15SDaniel P. Berrange      *   1. anon
35610dd72e15SDaniel P. Berrange      *   2. x509
35620dd72e15SDaniel P. Berrange      *
35630dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
35640dd72e15SDaniel P. Berrange      *
35650dd72e15SDaniel P. Berrange      *   1. clear + none
35660dd72e15SDaniel P. Berrange      *   2. clear + vnc
35670dd72e15SDaniel P. Berrange      *   3. clear + sasl
35680dd72e15SDaniel P. Berrange      *   4. tls + anon + none
35690dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
35700dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
35710dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
35720dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
35730dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
35740dd72e15SDaniel P. Berrange      *
35750dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
35760dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
35770dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
35780dd72e15SDaniel P. Berrange      * sub-auth types.
3579f9148c8aSDaniel P. Berrange      *
3580f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3581f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3582f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3583f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3584f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3585f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3586f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3587f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3588f9148c8aSDaniel P. Berrange      *
3589f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3590f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3591f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
35920dd72e15SDaniel P. Berrange      */
3593eda24e18SDaniel P. Berrange     if (websocket || !tlscreds) {
35940dd72e15SDaniel P. Berrange         if (password) {
35950dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
3596eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_VNC;
35970dd72e15SDaniel P. Berrange         } else if (sasl) {
35980dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3599eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_SASL;
36000dd72e15SDaniel P. Berrange         } else {
36010dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
3602eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_NONE;
36030dd72e15SDaniel P. Berrange         }
3604eda24e18SDaniel P. Berrange         *subauth = VNC_AUTH_INVALID;
3605f9148c8aSDaniel P. Berrange     } else {
3606eda24e18SDaniel P. Berrange         bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3607eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3608eda24e18SDaniel P. Berrange         bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3609eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3610eda24e18SDaniel P. Berrange 
3611eda24e18SDaniel P. Berrange         if (!is_x509 && !is_anon) {
3612eda24e18SDaniel P. Berrange             error_setg(errp,
3613eda24e18SDaniel P. Berrange                        "Unsupported TLS cred type %s",
3614eda24e18SDaniel P. Berrange                        object_get_typename(OBJECT(tlscreds)));
3615eda24e18SDaniel P. Berrange             return -1;
3616eda24e18SDaniel P. Berrange         }
3617eda24e18SDaniel P. Berrange         *auth = VNC_AUTH_VENCRYPT;
3618eda24e18SDaniel P. Berrange         if (password) {
3619eda24e18SDaniel P. Berrange             if (is_x509) {
3620eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3621eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3622eda24e18SDaniel P. Berrange             } else {
3623eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3624eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3625eda24e18SDaniel P. Berrange             }
3626eda24e18SDaniel P. Berrange 
3627eda24e18SDaniel P. Berrange         } else if (sasl) {
3628eda24e18SDaniel P. Berrange             if (is_x509) {
3629eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3630eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3631eda24e18SDaniel P. Berrange             } else {
3632eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3633eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3634eda24e18SDaniel P. Berrange             }
3635eda24e18SDaniel P. Berrange         } else {
3636eda24e18SDaniel P. Berrange             if (is_x509) {
3637eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3638eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3639eda24e18SDaniel P. Berrange             } else {
3640eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3641eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3642eda24e18SDaniel P. Berrange             }
3643f9148c8aSDaniel P. Berrange         }
36440dd72e15SDaniel P. Berrange     }
36453e305e4aSDaniel P. Berrange     return 0;
36460dd72e15SDaniel P. Berrange }
36470dd72e15SDaniel P. Berrange 
36483e305e4aSDaniel P. Berrange 
3649275e0d61SDaniel P. Berrange static int vnc_display_get_address(const char *addrstr,
3650275e0d61SDaniel P. Berrange                                    bool websocket,
3651e5766eb4SGerd Hoffmann                                    bool reverse,
3652275e0d61SDaniel P. Berrange                                    int displaynum,
3653275e0d61SDaniel P. Berrange                                    int to,
3654275e0d61SDaniel P. Berrange                                    bool has_ipv4,
3655275e0d61SDaniel P. Berrange                                    bool has_ipv6,
3656275e0d61SDaniel P. Berrange                                    bool ipv4,
3657275e0d61SDaniel P. Berrange                                    bool ipv6,
3658bd269ebcSMarkus Armbruster                                    SocketAddress **retaddr,
3659275e0d61SDaniel P. Berrange                                    Error **errp)
3660275e0d61SDaniel P. Berrange {
3661275e0d61SDaniel P. Berrange     int ret = -1;
3662bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3663275e0d61SDaniel P. Berrange 
3664bd269ebcSMarkus Armbruster     addr = g_new0(SocketAddress, 1);
3665275e0d61SDaniel P. Berrange 
3666275e0d61SDaniel P. Berrange     if (strncmp(addrstr, "unix:", 5) == 0) {
3667bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3668bd269ebcSMarkus Armbruster         addr->u.q_unix.path = g_strdup(addrstr + 5);
3669275e0d61SDaniel P. Berrange 
3670275e0d61SDaniel P. Berrange         if (websocket) {
3671275e0d61SDaniel P. Berrange             error_setg(errp, "UNIX sockets not supported with websock");
3672275e0d61SDaniel P. Berrange             goto cleanup;
3673275e0d61SDaniel P. Berrange         }
3674275e0d61SDaniel P. Berrange 
3675275e0d61SDaniel P. Berrange         if (to) {
3676275e0d61SDaniel P. Berrange             error_setg(errp, "Port range not support with UNIX socket");
3677275e0d61SDaniel P. Berrange             goto cleanup;
3678275e0d61SDaniel P. Berrange         }
3679275e0d61SDaniel P. Berrange         ret = 0;
3680275e0d61SDaniel P. Berrange     } else {
3681275e0d61SDaniel P. Berrange         const char *port;
3682275e0d61SDaniel P. Berrange         size_t hostlen;
3683275e0d61SDaniel P. Berrange         unsigned long long baseport = 0;
3684275e0d61SDaniel P. Berrange         InetSocketAddress *inet;
3685275e0d61SDaniel P. Berrange 
3686275e0d61SDaniel P. Berrange         port = strrchr(addrstr, ':');
3687275e0d61SDaniel P. Berrange         if (!port) {
3688275e0d61SDaniel P. Berrange             if (websocket) {
3689275e0d61SDaniel P. Berrange                 hostlen = 0;
3690275e0d61SDaniel P. Berrange                 port = addrstr;
3691275e0d61SDaniel P. Berrange             } else {
3692275e0d61SDaniel P. Berrange                 error_setg(errp, "no vnc port specified");
3693275e0d61SDaniel P. Berrange                 goto cleanup;
3694275e0d61SDaniel P. Berrange             }
3695275e0d61SDaniel P. Berrange         } else {
3696275e0d61SDaniel P. Berrange             hostlen = port - addrstr;
3697275e0d61SDaniel P. Berrange             port++;
3698275e0d61SDaniel P. Berrange             if (*port == '\0') {
3699275e0d61SDaniel P. Berrange                 error_setg(errp, "vnc port cannot be empty");
3700275e0d61SDaniel P. Berrange                 goto cleanup;
3701275e0d61SDaniel P. Berrange             }
3702275e0d61SDaniel P. Berrange         }
3703275e0d61SDaniel P. Berrange 
3704bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_INET;
3705bd269ebcSMarkus Armbruster         inet = &addr->u.inet;
3706275e0d61SDaniel P. Berrange         if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3707275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr + 1, hostlen - 2);
3708275e0d61SDaniel P. Berrange         } else {
3709275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr, hostlen);
3710275e0d61SDaniel P. Berrange         }
3711275e0d61SDaniel P. Berrange         /* plain VNC port is just an offset, for websocket
3712275e0d61SDaniel P. Berrange          * port is absolute */
3713275e0d61SDaniel P. Berrange         if (websocket) {
3714275e0d61SDaniel P. Berrange             if (g_str_equal(addrstr, "") ||
3715275e0d61SDaniel P. Berrange                 g_str_equal(addrstr, "on")) {
3716396f935aSDaniel P. Berrange                 if (displaynum == -1) {
3717396f935aSDaniel P. Berrange                     error_setg(errp, "explicit websocket port is required");
3718396f935aSDaniel P. Berrange                     goto cleanup;
3719396f935aSDaniel P. Berrange                 }
3720275e0d61SDaniel P. Berrange                 inet->port = g_strdup_printf(
3721275e0d61SDaniel P. Berrange                     "%d", displaynum + 5700);
3722275e0d61SDaniel P. Berrange                 if (to) {
3723275e0d61SDaniel P. Berrange                     inet->has_to = true;
3724275e0d61SDaniel P. Berrange                     inet->to = to + 5700;
3725275e0d61SDaniel P. Berrange                 }
3726275e0d61SDaniel P. Berrange             } else {
3727275e0d61SDaniel P. Berrange                 inet->port = g_strdup(port);
3728275e0d61SDaniel P. Berrange             }
3729275e0d61SDaniel P. Berrange         } else {
3730e5766eb4SGerd Hoffmann             int offset = reverse ? 0 : 5900;
3731275e0d61SDaniel P. Berrange             if (parse_uint_full(port, &baseport, 10) < 0) {
3732275e0d61SDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", port);
3733275e0d61SDaniel P. Berrange                 goto cleanup;
3734275e0d61SDaniel P. Berrange             }
3735275e0d61SDaniel P. Berrange             if (baseport > 65535 ||
3736e5766eb4SGerd Hoffmann                 baseport + offset > 65535) {
3737275e0d61SDaniel P. Berrange                 error_setg(errp, "port %s out of range", port);
3738275e0d61SDaniel P. Berrange                 goto cleanup;
3739275e0d61SDaniel P. Berrange             }
3740275e0d61SDaniel P. Berrange             inet->port = g_strdup_printf(
3741e5766eb4SGerd Hoffmann                 "%d", (int)baseport + offset);
3742275e0d61SDaniel P. Berrange 
3743275e0d61SDaniel P. Berrange             if (to) {
3744275e0d61SDaniel P. Berrange                 inet->has_to = true;
3745e5766eb4SGerd Hoffmann                 inet->to = to + offset;
3746275e0d61SDaniel P. Berrange             }
3747275e0d61SDaniel P. Berrange         }
3748275e0d61SDaniel P. Berrange 
3749275e0d61SDaniel P. Berrange         inet->ipv4 = ipv4;
3750275e0d61SDaniel P. Berrange         inet->has_ipv4 = has_ipv4;
3751275e0d61SDaniel P. Berrange         inet->ipv6 = ipv6;
3752275e0d61SDaniel P. Berrange         inet->has_ipv6 = has_ipv6;
3753275e0d61SDaniel P. Berrange 
3754275e0d61SDaniel P. Berrange         ret = baseport;
3755275e0d61SDaniel P. Berrange     }
3756275e0d61SDaniel P. Berrange 
3757275e0d61SDaniel P. Berrange     *retaddr = addr;
3758275e0d61SDaniel P. Berrange 
3759275e0d61SDaniel P. Berrange  cleanup:
3760275e0d61SDaniel P. Berrange     if (ret < 0) {
3761bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
3762275e0d61SDaniel P. Berrange     }
3763275e0d61SDaniel P. Berrange     return ret;
3764275e0d61SDaniel P. Berrange }
3765275e0d61SDaniel P. Berrange 
37669f26f325SPhilippe Mathieu-Daudé static void vnc_free_addresses(SocketAddress ***retsaddr,
37679f26f325SPhilippe Mathieu-Daudé                                size_t *retnsaddr)
37689f26f325SPhilippe Mathieu-Daudé {
37699f26f325SPhilippe Mathieu-Daudé     size_t i;
37709f26f325SPhilippe Mathieu-Daudé 
37719f26f325SPhilippe Mathieu-Daudé     for (i = 0; i < *retnsaddr; i++) {
37729f26f325SPhilippe Mathieu-Daudé         qapi_free_SocketAddress((*retsaddr)[i]);
37739f26f325SPhilippe Mathieu-Daudé     }
37749f26f325SPhilippe Mathieu-Daudé     g_free(*retsaddr);
37759f26f325SPhilippe Mathieu-Daudé 
37769f26f325SPhilippe Mathieu-Daudé     *retsaddr = NULL;
37779f26f325SPhilippe Mathieu-Daudé     *retnsaddr = 0;
37789f26f325SPhilippe Mathieu-Daudé }
37799f26f325SPhilippe Mathieu-Daudé 
3780275e0d61SDaniel P. Berrange static int vnc_display_get_addresses(QemuOpts *opts,
3781e5766eb4SGerd Hoffmann                                      bool reverse,
3782bd269ebcSMarkus Armbruster                                      SocketAddress ***retsaddr,
3783396f935aSDaniel P. Berrange                                      size_t *retnsaddr,
3784bd269ebcSMarkus Armbruster                                      SocketAddress ***retwsaddr,
3785396f935aSDaniel P. Berrange                                      size_t *retnwsaddr,
3786275e0d61SDaniel P. Berrange                                      Error **errp)
3787275e0d61SDaniel P. Berrange {
3788bd269ebcSMarkus Armbruster     SocketAddress *saddr = NULL;
3789bd269ebcSMarkus Armbruster     SocketAddress *wsaddr = NULL;
3790396f935aSDaniel P. Berrange     QemuOptsIter addriter;
3791396f935aSDaniel P. Berrange     const char *addr;
3792275e0d61SDaniel P. Berrange     int to = qemu_opt_get_number(opts, "to", 0);
3793275e0d61SDaniel P. Berrange     bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3794275e0d61SDaniel P. Berrange     bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3795275e0d61SDaniel P. Berrange     bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3796275e0d61SDaniel P. Berrange     bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3797396f935aSDaniel P. Berrange     int displaynum = -1;
3798396f935aSDaniel P. Berrange     int ret = -1;
3799275e0d61SDaniel P. Berrange 
3800275e0d61SDaniel P. Berrange     *retsaddr = NULL;
3801396f935aSDaniel P. Berrange     *retnsaddr = 0;
3802275e0d61SDaniel P. Berrange     *retwsaddr = NULL;
3803396f935aSDaniel P. Berrange     *retnwsaddr = 0;
3804275e0d61SDaniel P. Berrange 
3805396f935aSDaniel P. Berrange     addr = qemu_opt_get(opts, "vnc");
3806396f935aSDaniel P. Berrange     if (addr == NULL || g_str_equal(addr, "none")) {
3807396f935aSDaniel P. Berrange         ret = 0;
3808396f935aSDaniel P. Berrange         goto cleanup;
3809396f935aSDaniel P. Berrange     }
3810396f935aSDaniel P. Berrange     if (qemu_opt_get(opts, "websocket") &&
3811275e0d61SDaniel P. Berrange         !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3812275e0d61SDaniel P. Berrange         error_setg(errp,
3813275e0d61SDaniel P. Berrange                    "SHA1 hash support is required for websockets");
3814396f935aSDaniel P. Berrange         goto cleanup;
3815275e0d61SDaniel P. Berrange     }
3816275e0d61SDaniel P. Berrange 
3817396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "vnc");
3818396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3819396f935aSDaniel P. Berrange         int rv;
3820e5766eb4SGerd Hoffmann         rv = vnc_display_get_address(addr, false, reverse, 0, to,
3821275e0d61SDaniel P. Berrange                                      has_ipv4, has_ipv6,
3822275e0d61SDaniel P. Berrange                                      ipv4, ipv6,
3823275e0d61SDaniel P. Berrange                                      &saddr, errp);
3824396f935aSDaniel P. Berrange         if (rv < 0) {
3825396f935aSDaniel P. Berrange             goto cleanup;
3826275e0d61SDaniel P. Berrange         }
3827396f935aSDaniel P. Berrange         /* Historical compat - first listen address can be used
3828396f935aSDaniel P. Berrange          * to set the default websocket port
3829396f935aSDaniel P. Berrange          */
3830396f935aSDaniel P. Berrange         if (displaynum == -1) {
3831396f935aSDaniel P. Berrange             displaynum = rv;
3832396f935aSDaniel P. Berrange         }
3833bd269ebcSMarkus Armbruster         *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3834396f935aSDaniel P. Berrange         (*retsaddr)[(*retnsaddr)++] = saddr;
3835396f935aSDaniel P. Berrange     }
3836396f935aSDaniel P. Berrange 
3837396f935aSDaniel P. Berrange     /* If we had multiple primary displays, we don't do defaults
3838396f935aSDaniel P. Berrange      * for websocket, and require explicit config instead. */
3839396f935aSDaniel P. Berrange     if (*retnsaddr > 1) {
3840396f935aSDaniel P. Berrange         displaynum = -1;
3841396f935aSDaniel P. Berrange     }
3842396f935aSDaniel P. Berrange 
3843396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "websocket");
3844396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3845e5766eb4SGerd Hoffmann         if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3846275e0d61SDaniel P. Berrange                                     has_ipv4, has_ipv6,
3847275e0d61SDaniel P. Berrange                                     ipv4, ipv6,
3848275e0d61SDaniel P. Berrange                                     &wsaddr, errp) < 0) {
3849396f935aSDaniel P. Berrange             goto cleanup;
3850275e0d61SDaniel P. Berrange         }
3851396f935aSDaniel P. Berrange 
3852396f935aSDaniel P. Berrange         /* Historical compat - if only a single listen address was
3853396f935aSDaniel P. Berrange          * provided, then this is used to set the default listen
3854396f935aSDaniel P. Berrange          * address for websocket too
3855396f935aSDaniel P. Berrange          */
3856396f935aSDaniel P. Berrange         if (*retnsaddr == 1 &&
3857bd269ebcSMarkus Armbruster             (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3858bd269ebcSMarkus Armbruster             wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3859bd269ebcSMarkus Armbruster             g_str_equal(wsaddr->u.inet.host, "") &&
3860bd269ebcSMarkus Armbruster             !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3861bd269ebcSMarkus Armbruster             g_free(wsaddr->u.inet.host);
3862bd269ebcSMarkus Armbruster             wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3863275e0d61SDaniel P. Berrange         }
3864275e0d61SDaniel P. Berrange 
3865bd269ebcSMarkus Armbruster         *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3866396f935aSDaniel P. Berrange         (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3867396f935aSDaniel P. Berrange     }
3868396f935aSDaniel P. Berrange 
3869396f935aSDaniel P. Berrange     ret = 0;
3870396f935aSDaniel P. Berrange  cleanup:
3871396f935aSDaniel P. Berrange     if (ret < 0) {
38729f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retsaddr, retnsaddr);
38739f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retwsaddr, retnwsaddr);
3874396f935aSDaniel P. Berrange     }
3875396f935aSDaniel P. Berrange     return ret;
3876275e0d61SDaniel P. Berrange }
3877275e0d61SDaniel P. Berrange 
38788bd22f47SDaniel P. Berrange static int vnc_display_connect(VncDisplay *vd,
3879bd269ebcSMarkus Armbruster                                SocketAddress **saddr,
3880396f935aSDaniel P. Berrange                                size_t nsaddr,
3881bd269ebcSMarkus Armbruster                                SocketAddress **wsaddr,
3882396f935aSDaniel P. Berrange                                size_t nwsaddr,
38838bd22f47SDaniel P. Berrange                                Error **errp)
38848bd22f47SDaniel P. Berrange {
38858bd22f47SDaniel P. Berrange     /* connect to viewer */
38868bd22f47SDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
3887396f935aSDaniel P. Berrange     if (nwsaddr != 0) {
38888bd22f47SDaniel P. Berrange         error_setg(errp, "Cannot use websockets in reverse mode");
38898bd22f47SDaniel P. Berrange         return -1;
38908bd22f47SDaniel P. Berrange     }
3891396f935aSDaniel P. Berrange     if (nsaddr != 1) {
3892396f935aSDaniel P. Berrange         error_setg(errp, "Expected a single address in reverse mode");
3893396f935aSDaniel P. Berrange         return -1;
3894396f935aSDaniel P. Berrange     }
3895bd269ebcSMarkus Armbruster     /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3896bd269ebcSMarkus Armbruster     vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
38978bd22f47SDaniel P. Berrange     sioc = qio_channel_socket_new();
38988bd22f47SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3899396f935aSDaniel P. Berrange     if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
39005f8679feSAlex Chen         object_unref(OBJECT(sioc));
39018bd22f47SDaniel P. Berrange         return -1;
39028bd22f47SDaniel P. Berrange     }
39038bd22f47SDaniel P. Berrange     vnc_connect(vd, sioc, false, false);
39048bd22f47SDaniel P. Berrange     object_unref(OBJECT(sioc));
39058bd22f47SDaniel P. Berrange     return 0;
39068bd22f47SDaniel P. Berrange }
39078bd22f47SDaniel P. Berrange 
39088bd22f47SDaniel P. Berrange 
39098bd22f47SDaniel P. Berrange static int vnc_display_listen(VncDisplay *vd,
3910bd269ebcSMarkus Armbruster                               SocketAddress **saddr,
3911396f935aSDaniel P. Berrange                               size_t nsaddr,
3912bd269ebcSMarkus Armbruster                               SocketAddress **wsaddr,
3913396f935aSDaniel P. Berrange                               size_t nwsaddr,
39148bd22f47SDaniel P. Berrange                               Error **errp)
39158bd22f47SDaniel P. Berrange {
3916396f935aSDaniel P. Berrange     size_t i;
39178bd22f47SDaniel P. Berrange 
391813e1d0e7SDaniel P. Berrange     if (nsaddr) {
391913e1d0e7SDaniel P. Berrange         vd->listener = qio_net_listener_new();
392013e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->listener, "vnc-listen");
3921396f935aSDaniel P. Berrange         for (i = 0; i < nsaddr; i++) {
392213e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->listener,
3923fc8135c6SJuan Quintela                                            saddr[i], 1,
39248bd22f47SDaniel P. Berrange                                            errp) < 0)  {
39258bd22f47SDaniel P. Berrange                 return -1;
39268bd22f47SDaniel P. Berrange             }
3927396f935aSDaniel P. Berrange         }
392813e1d0e7SDaniel P. Berrange 
392913e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->listener,
393013e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
393113e1d0e7SDaniel P. Berrange     }
393213e1d0e7SDaniel P. Berrange 
393313e1d0e7SDaniel P. Berrange     if (nwsaddr) {
393413e1d0e7SDaniel P. Berrange         vd->wslistener = qio_net_listener_new();
393513e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3936396f935aSDaniel P. Berrange         for (i = 0; i < nwsaddr; i++) {
393713e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->wslistener,
3938fc8135c6SJuan Quintela                                            wsaddr[i], 1,
39398bd22f47SDaniel P. Berrange                                            errp) < 0)  {
39408bd22f47SDaniel P. Berrange                 return -1;
39418bd22f47SDaniel P. Berrange             }
3942396f935aSDaniel P. Berrange         }
39438bd22f47SDaniel P. Berrange 
394413e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->wslistener,
394513e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
394613e1d0e7SDaniel P. Berrange     }
394713e1d0e7SDaniel P. Berrange 
39488bd22f47SDaniel P. Berrange     return 0;
39498bd22f47SDaniel P. Berrange }
39508bd22f47SDaniel P. Berrange 
39518bd22f47SDaniel P. Berrange 
39524db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
39533e230dd2SCorentin Chary {
3954bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
39554db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3956bd269ebcSMarkus Armbruster     SocketAddress **saddr = NULL, **wsaddr = NULL;
3957396f935aSDaniel P. Berrange     size_t nsaddr, nwsaddr;
3958e2a11d9dSGonglei     const char *share, *device_id;
39591d0d59feSGerd Hoffmann     QemuConsole *con;
3960a2c72de0SGonglei     bool password = false;
3961a2c72de0SGonglei     bool reverse = false;
39623e305e4aSDaniel P. Berrange     const char *credid;
3963a2c72de0SGonglei     bool sasl = false;
39643e230dd2SCorentin Chary     int acl = 0;
396555cf09a0SDaniel P. Berrange     const char *tlsauthz;
396655cf09a0SDaniel P. Berrange     const char *saslauthz;
39673e230dd2SCorentin Chary     int lock_key_sync = 1;
3968c5ce8333SGerd Hoffmann     int key_delay_ms;
3969f0b9f36dSKővágó, Zoltán     const char *audiodev;
39706c6840e9SDaniel P. Berrangé     const char *passwordSecret;
39713e230dd2SCorentin Chary 
3972bf01c179SDaniel P. Berrange     if (!vd) {
39732d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
39742d55f0e8SPaolo Bonzini         return;
39752d55f0e8SPaolo Bonzini     }
3976bf01c179SDaniel P. Berrange     vnc_display_close(vd);
39774db14629SGerd Hoffmann 
39784db14629SGerd Hoffmann     if (!opts) {
39792d55f0e8SPaolo Bonzini         return;
39804db14629SGerd Hoffmann     }
3981275e0d61SDaniel P. Berrange 
3982e5766eb4SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
3983e5766eb4SGerd Hoffmann     if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3984396f935aSDaniel P. Berrange                                   &wsaddr, &nwsaddr, errp) < 0) {
3985275e0d61SDaniel P. Berrange         goto fail;
3986275e0d61SDaniel P. Berrange     }
3987275e0d61SDaniel P. Berrange 
39886c6840e9SDaniel P. Berrangé 
39896c6840e9SDaniel P. Berrangé     passwordSecret = qemu_opt_get(opts, "password-secret");
39906c6840e9SDaniel P. Berrangé     if (passwordSecret) {
39916c6840e9SDaniel P. Berrangé         if (qemu_opt_get(opts, "password")) {
39926c6840e9SDaniel P. Berrangé             error_setg(errp,
39936c6840e9SDaniel P. Berrangé                        "'password' flag is redundant with 'password-secret'");
39946c6840e9SDaniel P. Berrangé             goto fail;
39956c6840e9SDaniel P. Berrangé         }
39966c6840e9SDaniel P. Berrangé         vd->password = qcrypto_secret_lookup_as_utf8(passwordSecret,
39976c6840e9SDaniel P. Berrangé                                                      errp);
39986c6840e9SDaniel P. Berrangé         if (!vd->password) {
39996c6840e9SDaniel P. Berrangé             goto fail;
40006c6840e9SDaniel P. Berrangé         }
40016c6840e9SDaniel P. Berrangé         password = true;
40026c6840e9SDaniel P. Berrangé     } else {
40034db14629SGerd Hoffmann         password = qemu_opt_get_bool(opts, "password", false);
40046c6840e9SDaniel P. Berrangé     }
4005800567a6SDaniel P. Berrange     if (password) {
4006800567a6SDaniel P. Berrange         if (fips_get_state()) {
40072d55f0e8SPaolo Bonzini             error_setg(errp,
40080f66998fSPaul Moore                        "VNC password auth disabled due to FIPS mode, "
40090f66998fSPaul Moore                        "consider using the VeNCrypt or SASL authentication "
40102d55f0e8SPaolo Bonzini                        "methods as an alternative");
40111ce52c78SPaolo Bonzini             goto fail;
40120f66998fSPaul Moore         }
4013800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
4014f844836dSGonglei                 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
4015800567a6SDaniel P. Berrange             error_setg(errp,
4016800567a6SDaniel P. Berrange                        "Cipher backend does not support DES RFB algorithm");
4017800567a6SDaniel P. Berrange             goto fail;
4018800567a6SDaniel P. Berrange         }
4019800567a6SDaniel P. Berrange     }
40204db14629SGerd Hoffmann 
40214db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
4022d3b0db6dSAlexander Graf     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
40234db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
4024d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
4025d169f04bSDaniel P. Berrange     if (sasl) {
4026d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
4027d169f04bSDaniel P. Berrange         goto fail;
4028d169f04bSDaniel P. Berrange     }
4029d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
40303e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
40313e305e4aSDaniel P. Berrange     if (credid) {
40323e305e4aSDaniel P. Berrange         Object *creds;
40333e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
40343e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
40353e305e4aSDaniel P. Berrange         if (!creds) {
40363e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
40373e305e4aSDaniel P. Berrange                        credid);
40383e305e4aSDaniel P. Berrange             goto fail;
40393e305e4aSDaniel P. Berrange         }
4040bf01c179SDaniel P. Berrange         vd->tlscreds = (QCryptoTLSCreds *)
40413e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
40423e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
4043bf01c179SDaniel P. Berrange         if (!vd->tlscreds) {
40443e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
40453e305e4aSDaniel P. Berrange                        credid);
40463e305e4aSDaniel P. Berrange             goto fail;
40473e305e4aSDaniel P. Berrange         }
4048bf01c179SDaniel P. Berrange         object_ref(OBJECT(vd->tlscreds));
40493e305e4aSDaniel P. Berrange 
4050bf01c179SDaniel P. Berrange         if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
40513e305e4aSDaniel P. Berrange             error_setg(errp,
40523e305e4aSDaniel P. Berrange                        "Expecting TLS credentials with a server endpoint");
40533e305e4aSDaniel P. Berrange             goto fail;
40543e305e4aSDaniel P. Berrange         }
4055d169f04bSDaniel P. Berrange     }
405655cf09a0SDaniel P. Berrange     if (qemu_opt_get(opts, "acl")) {
405755cf09a0SDaniel P. Berrange         error_report("The 'acl' option to -vnc is deprecated. "
405855cf09a0SDaniel P. Berrange                      "Please use the 'tls-authz' and 'sasl-authz' "
405955cf09a0SDaniel P. Berrange                      "options instead");
406055cf09a0SDaniel P. Berrange     }
40614db14629SGerd Hoffmann     acl = qemu_opt_get_bool(opts, "acl", false);
406255cf09a0SDaniel P. Berrange     tlsauthz = qemu_opt_get(opts, "tls-authz");
406355cf09a0SDaniel P. Berrange     if (acl && tlsauthz) {
406455cf09a0SDaniel P. Berrange         error_setg(errp, "'acl' option is mutually exclusive with the "
406555cf09a0SDaniel P. Berrange                    "'tls-authz' option");
406655cf09a0SDaniel P. Berrange         goto fail;
406755cf09a0SDaniel P. Berrange     }
406855cf09a0SDaniel P. Berrange     if (tlsauthz && !vd->tlscreds) {
406955cf09a0SDaniel P. Berrange         error_setg(errp, "'tls-authz' provided but TLS is not enabled");
407055cf09a0SDaniel P. Berrange         goto fail;
407155cf09a0SDaniel P. Berrange     }
407255cf09a0SDaniel P. Berrange 
407355cf09a0SDaniel P. Berrange     saslauthz = qemu_opt_get(opts, "sasl-authz");
407455cf09a0SDaniel P. Berrange     if (acl && saslauthz) {
407555cf09a0SDaniel P. Berrange         error_setg(errp, "'acl' option is mutually exclusive with the "
407655cf09a0SDaniel P. Berrange                    "'sasl-authz' option");
407755cf09a0SDaniel P. Berrange         goto fail;
407855cf09a0SDaniel P. Berrange     }
407955cf09a0SDaniel P. Berrange     if (saslauthz && !sasl) {
408055cf09a0SDaniel P. Berrange         error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
408155cf09a0SDaniel P. Berrange         goto fail;
408255cf09a0SDaniel P. Berrange     }
40834db14629SGerd Hoffmann 
40844db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
40854db14629SGerd Hoffmann     if (share) {
40864db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
4087bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_IGNORE;
40884db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
4089bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
40904db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
4091bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
40928cf36489SGerd Hoffmann         } else {
40932d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
40941ce52c78SPaolo Bonzini             goto fail;
40958cf36489SGerd Hoffmann         }
40964db14629SGerd Hoffmann     } else {
4097bf01c179SDaniel P. Berrange         vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
40983e230dd2SCorentin Chary     }
4099bf01c179SDaniel P. Berrange     vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
41003e230dd2SCorentin Chary 
41014db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
4102bf01c179SDaniel P. Berrange     vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
41034db14629SGerd Hoffmann #endif
4104bf01c179SDaniel P. Berrange     vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4105e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
4106e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
4107e22492d3SPeter Lieven      * calculations otherwise */
4108bf01c179SDaniel P. Berrange     if (!vd->lossy) {
4109bf01c179SDaniel P. Berrange         vd->non_adaptive = true;
4110e22492d3SPeter Lieven     }
4111e22492d3SPeter Lieven 
41127b5fa0b5SDaniel P. Berrangé     vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
41137b5fa0b5SDaniel P. Berrangé 
411455cf09a0SDaniel P. Berrange     if (tlsauthz) {
411555cf09a0SDaniel P. Berrange         vd->tlsauthzid = g_strdup(tlsauthz);
411655cf09a0SDaniel P. Berrange     } else if (acl) {
4117bf01c179SDaniel P. Berrange         if (strcmp(vd->id, "default") == 0) {
4118b76806d4SDaniel P. Berrange             vd->tlsauthzid = g_strdup("vnc.x509dname");
4119c8496408SGerd Hoffmann         } else {
4120b76806d4SDaniel P. Berrange             vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
4121c8496408SGerd Hoffmann         }
4122b76806d4SDaniel P. Berrange         vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
4123b76806d4SDaniel P. Berrange                                               QAUTHZ_LIST_POLICY_DENY,
4124b76806d4SDaniel P. Berrange                                               &error_abort));
41253e230dd2SCorentin Chary     }
41263e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
412755cf09a0SDaniel P. Berrange     if (sasl) {
412855cf09a0SDaniel P. Berrange         if (saslauthz) {
412955cf09a0SDaniel P. Berrange             vd->sasl.authzid = g_strdup(saslauthz);
413055cf09a0SDaniel P. Berrange         } else if (acl) {
4131bf01c179SDaniel P. Berrange             if (strcmp(vd->id, "default") == 0) {
4132b76806d4SDaniel P. Berrange                 vd->sasl.authzid = g_strdup("vnc.username");
4133c8496408SGerd Hoffmann             } else {
4134b76806d4SDaniel P. Berrange                 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
4135c8496408SGerd Hoffmann             }
4136b76806d4SDaniel P. Berrange             vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
4137b76806d4SDaniel P. Berrange                                                     QAUTHZ_LIST_POLICY_DENY,
4138b76806d4SDaniel P. Berrange                                                     &error_abort));
41393e230dd2SCorentin Chary         }
414055cf09a0SDaniel P. Berrange     }
41413e230dd2SCorentin Chary #endif
41423e230dd2SCorentin Chary 
4143eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4144eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4145eda24e18SDaniel P. Berrange                                sasl, false, errp) < 0) {
4146eda24e18SDaniel P. Berrange         goto fail;
4147eda24e18SDaniel P. Berrange     }
41487364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4149eda24e18SDaniel P. Berrange 
4150eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4151eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4152eda24e18SDaniel P. Berrange                                sasl, true, errp) < 0) {
41533e305e4aSDaniel P. Berrange         goto fail;
41543e305e4aSDaniel P. Berrange     }
41557364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
41563e230dd2SCorentin Chary 
41573e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
4158b5dc0d7dSMarc-André Lureau     if (sasl) {
4159b5dc0d7dSMarc-André Lureau         int saslErr = sasl_server_init(NULL, "qemu");
4160b5dc0d7dSMarc-André Lureau 
4161b5dc0d7dSMarc-André Lureau         if (saslErr != SASL_OK) {
41622d55f0e8SPaolo Bonzini             error_setg(errp, "Failed to initialize SASL auth: %s",
41633e230dd2SCorentin Chary                        sasl_errstring(saslErr, NULL, NULL));
41641ce52c78SPaolo Bonzini             goto fail;
41653e230dd2SCorentin Chary         }
4166b5dc0d7dSMarc-André Lureau     }
41673e230dd2SCorentin Chary #endif
4168bf01c179SDaniel P. Berrange     vd->lock_key_sync = lock_key_sync;
4169a54f0d2bSPierre Ossman     if (lock_key_sync) {
4170a54f0d2bSPierre Ossman         vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4171a54f0d2bSPierre Ossman     }
4172a54f0d2bSPierre Ossman     vd->ledstate = 0;
41733e230dd2SCorentin Chary 
4174f0b9f36dSKővágó, Zoltán     audiodev = qemu_opt_get(opts, "audiodev");
4175f0b9f36dSKővágó, Zoltán     if (audiodev) {
4176f0b9f36dSKővágó, Zoltán         vd->audio_state = audio_state_by_name(audiodev);
4177f0b9f36dSKővágó, Zoltán         if (!vd->audio_state) {
4178f0b9f36dSKővágó, Zoltán             error_setg(errp, "Audiodev '%s' not found", audiodev);
4179f0b9f36dSKővágó, Zoltán             goto fail;
4180f0b9f36dSKővágó, Zoltán         }
4181f0b9f36dSKővágó, Zoltán     }
4182f0b9f36dSKővágó, Zoltán 
41831d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
41841d0d59feSGerd Hoffmann     if (device_id) {
41851d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
4186f2c1d54cSGerd Hoffmann         Error *err = NULL;
41871d0d59feSGerd Hoffmann 
4188f2c1d54cSGerd Hoffmann         con = qemu_console_lookup_by_device_name(device_id, head, &err);
4189f2c1d54cSGerd Hoffmann         if (err) {
4190f2c1d54cSGerd Hoffmann             error_propagate(errp, err);
41911d0d59feSGerd Hoffmann             goto fail;
41921d0d59feSGerd Hoffmann         }
41931d0d59feSGerd Hoffmann     } else {
41941d0d59feSGerd Hoffmann         con = NULL;
41951d0d59feSGerd Hoffmann     }
41961d0d59feSGerd Hoffmann 
4197bf01c179SDaniel P. Berrange     if (con != vd->dcl.con) {
4198c2f2ba49SGerd Hoffmann         qkbd_state_free(vd->kbd);
4199bf01c179SDaniel P. Berrange         unregister_displaychangelistener(&vd->dcl);
4200bf01c179SDaniel P. Berrange         vd->dcl.con = con;
4201bf01c179SDaniel P. Berrange         register_displaychangelistener(&vd->dcl);
4202c2f2ba49SGerd Hoffmann         vd->kbd = qkbd_state_init(vd->dcl.con);
42031d0d59feSGerd Hoffmann     }
4204c2f2ba49SGerd Hoffmann     qkbd_state_set_delay(vd->kbd, key_delay_ms);
42051d0d59feSGerd Hoffmann 
4206fa03cb7fSMarc-André Lureau     if (saddr == NULL) {
4207fa03cb7fSMarc-André Lureau         goto cleanup;
4208fa03cb7fSMarc-André Lureau     }
4209fa03cb7fSMarc-André Lureau 
42103e230dd2SCorentin Chary     if (reverse) {
4211396f935aSDaniel P. Berrange         if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4212e0d03b8cSDaniel P. Berrange             goto fail;
42133e230dd2SCorentin Chary         }
42143e230dd2SCorentin Chary     } else {
4215396f935aSDaniel P. Berrange         if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
42163d00ac1aSCole Robinson             goto fail;
42173d00ac1aSCole Robinson         }
42183e230dd2SCorentin Chary     }
4219e0d03b8cSDaniel P. Berrange 
4220275e0d61SDaniel P. Berrange     if (qemu_opt_get(opts, "to")) {
4221bf01c179SDaniel P. Berrange         vnc_display_print_local_addr(vd);
422233df7bf3SPaolo Bonzini     }
422333df7bf3SPaolo Bonzini 
4224396f935aSDaniel P. Berrange  cleanup:
42259f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&saddr, &nsaddr);
42269f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&wsaddr, &nwsaddr);
42272d55f0e8SPaolo Bonzini     return;
42281ce52c78SPaolo Bonzini 
42291ce52c78SPaolo Bonzini fail:
42304ee74fa7SDaniel P. Berrange     vnc_display_close(vd);
4231396f935aSDaniel P. Berrange     goto cleanup;
42323e230dd2SCorentin Chary }
423313661089SDaniel P. Berrange 
423414f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
423513661089SDaniel P. Berrange {
4236bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
423704d2529dSDaniel P. Berrange     QIOChannelSocket *sioc;
423813661089SDaniel P. Berrange 
4239bf01c179SDaniel P. Berrange     if (!vd) {
4240d616ccc5SGerd Hoffmann         return;
4241d616ccc5SGerd Hoffmann     }
424204d2529dSDaniel P. Berrange 
424304d2529dSDaniel P. Berrange     sioc = qio_channel_socket_new_fd(csock, NULL);
424404d2529dSDaniel P. Berrange     if (sioc) {
424510bcfe58SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4246bf01c179SDaniel P. Berrange         vnc_connect(vd, sioc, skipauth, false);
424704d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
424804d2529dSDaniel P. Berrange     }
424913661089SDaniel P. Berrange }
42504db14629SGerd Hoffmann 
42519634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
42522779672fSGonglei {
42532779672fSGonglei     int i = 2;
42542779672fSGonglei     char *id;
42552779672fSGonglei 
42562779672fSGonglei     id = g_strdup("default");
42572779672fSGonglei     while (qemu_opts_find(olist, id)) {
42582779672fSGonglei         g_free(id);
42592779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
42602779672fSGonglei     }
42612779672fSGonglei     qemu_opts_set_id(opts, id);
42622779672fSGonglei }
42632779672fSGonglei 
4264653c9747SPaolo Bonzini void vnc_parse(const char *str)
42654db14629SGerd Hoffmann {
42664db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
4267653c9747SPaolo Bonzini     QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
426881607cbfSGonglei     const char *id;
42694db14629SGerd Hoffmann 
427081607cbfSGonglei     if (!opts) {
4271653c9747SPaolo Bonzini         exit(1);
427281607cbfSGonglei     }
427381607cbfSGonglei 
427481607cbfSGonglei     id = qemu_opts_id(opts);
42754db14629SGerd Hoffmann     if (!id) {
42764db14629SGerd Hoffmann         /* auto-assign id if not present */
42772779672fSGonglei         vnc_auto_assign_id(olist, opts);
42789634f4e3SGerd Hoffmann     }
42794db14629SGerd Hoffmann }
42804db14629SGerd Hoffmann 
428128d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
42829634f4e3SGerd Hoffmann {
42839634f4e3SGerd Hoffmann     Error *local_err = NULL;
42849634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
42859634f4e3SGerd Hoffmann 
42869634f4e3SGerd Hoffmann     assert(id);
4287ab4f931eSFei Li     vnc_display_init(id, &local_err);
4288ab4f931eSFei Li     if (local_err) {
4289612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4290612aea20SMarkus Armbruster         return -1;
4291ab4f931eSFei Li     }
42924db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
42934db14629SGerd Hoffmann     if (local_err != NULL) {
4294612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4295612aea20SMarkus Armbruster         return -1;
42964db14629SGerd Hoffmann     }
42974db14629SGerd Hoffmann     return 0;
42984db14629SGerd Hoffmann }
42994db14629SGerd Hoffmann 
43004db14629SGerd Hoffmann static void vnc_register_config(void)
43014db14629SGerd Hoffmann {
43024db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
43034db14629SGerd Hoffmann }
430434294e2fSEduardo Habkost opts_init(vnc_register_config);
4305