xref: /openbmc/qemu/ui/vnc.c (revision d239726c53fd9d3b5e6a89c5a22ed57d8ab0a9aa)
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"
513e305e4aSDaniel P. Berrange #include "qom/object_interfaces.h"
52f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
53653c9747SPaolo Bonzini #include "qemu/help_option.h"
5457a6d6d5SDaniel P. Berrange #include "io/dns-resolver.h"
553e230dd2SCorentin Chary 
560f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
573e230dd2SCorentin Chary #define VNC_REFRESH_INTERVAL_INC  50
580f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
59999342a0SCorentin Chary static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
60999342a0SCorentin Chary static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
613e230dd2SCorentin Chary 
623e230dd2SCorentin Chary #include "vnc_keysym.h"
63800567a6SDaniel P. Berrange #include "crypto/cipher.h"
643e230dd2SCorentin Chary 
65d616ccc5SGerd Hoffmann static QTAILQ_HEAD(, VncDisplay) vnc_displays =
66d616ccc5SGerd Hoffmann     QTAILQ_HEAD_INITIALIZER(vnc_displays);
673e230dd2SCorentin Chary 
683e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs);
69e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs);
703e230dd2SCorentin Chary 
718cf36489SGerd Hoffmann static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
728cf36489SGerd Hoffmann {
738cf36489SGerd Hoffmann #ifdef _VNC_DEBUG
748cf36489SGerd Hoffmann     static const char *mn[] = {
758cf36489SGerd Hoffmann         [0]                           = "undefined",
768cf36489SGerd Hoffmann         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
778cf36489SGerd Hoffmann         [VNC_SHARE_MODE_SHARED]       = "shared",
788cf36489SGerd Hoffmann         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
798cf36489SGerd Hoffmann         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
808cf36489SGerd Hoffmann     };
8104d2529dSDaniel P. Berrange     fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
8204d2529dSDaniel P. Berrange             vs->ioc, mn[vs->share_mode], mn[mode]);
838cf36489SGerd Hoffmann #endif
848cf36489SGerd Hoffmann 
85e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
86e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
87e5f34cddSGerd Hoffmann         vs->vd->num_connecting--;
88e5f34cddSGerd Hoffmann         break;
89e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
90e5f34cddSGerd Hoffmann         vs->vd->num_shared--;
91e5f34cddSGerd Hoffmann         break;
92e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
938cf36489SGerd Hoffmann         vs->vd->num_exclusive--;
94e5f34cddSGerd Hoffmann         break;
95e5f34cddSGerd Hoffmann     default:
96e5f34cddSGerd Hoffmann         break;
978cf36489SGerd Hoffmann     }
98e5f34cddSGerd Hoffmann 
998cf36489SGerd Hoffmann     vs->share_mode = mode;
100e5f34cddSGerd Hoffmann 
101e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
102e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
103e5f34cddSGerd Hoffmann         vs->vd->num_connecting++;
104e5f34cddSGerd Hoffmann         break;
105e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
106e5f34cddSGerd Hoffmann         vs->vd->num_shared++;
107e5f34cddSGerd Hoffmann         break;
108e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
1098cf36489SGerd Hoffmann         vs->vd->num_exclusive++;
110e5f34cddSGerd Hoffmann         break;
111e5f34cddSGerd Hoffmann     default:
112e5f34cddSGerd Hoffmann         break;
1138cf36489SGerd Hoffmann     }
1148cf36489SGerd Hoffmann }
1158cf36489SGerd Hoffmann 
1163e230dd2SCorentin Chary 
117bd269ebcSMarkus Armbruster static void vnc_init_basic_info(SocketAddress *addr,
11898481bfcSEric Blake                                 VncBasicInfo *info,
11998481bfcSEric Blake                                 Error **errp)
1203e230dd2SCorentin Chary {
12104d2529dSDaniel P. Berrange     switch (addr->type) {
122bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_INET:
123bd269ebcSMarkus Armbruster         info->host = g_strdup(addr->u.inet.host);
124bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.inet.port);
125bd269ebcSMarkus Armbruster         if (addr->u.inet.ipv6) {
12604d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
12704d2529dSDaniel P. Berrange         } else {
12804d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
12904d2529dSDaniel P. Berrange         }
13004d2529dSDaniel P. Berrange         break;
1313e230dd2SCorentin Chary 
132bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_UNIX:
13304d2529dSDaniel P. Berrange         info->host = g_strdup("");
134bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.q_unix.path);
13504d2529dSDaniel P. Berrange         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
13604d2529dSDaniel P. Berrange         break;
13704d2529dSDaniel P. Berrange 
138bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_VSOCK:
139bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_FD:
140a6c76285SMarkus Armbruster         error_setg(errp, "Unsupported socket address type %s",
141977c736fSMarkus Armbruster                    SocketAddressType_str(addr->type));
14204d2529dSDaniel P. Berrange         break;
143a6c76285SMarkus Armbruster     default:
144a6c76285SMarkus Armbruster         abort();
14504d2529dSDaniel P. Berrange     }
14604d2529dSDaniel P. Berrange 
14798481bfcSEric Blake     return;
1483e230dd2SCorentin Chary }
1493e230dd2SCorentin Chary 
15004d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
15104d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
15298481bfcSEric Blake                                                  Error **errp)
1533e230dd2SCorentin Chary {
154bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1553e230dd2SCorentin Chary 
156624cdd46SDaniel P. Berrange     if (!ioc) {
157624cdd46SDaniel P. Berrange         error_setg(errp, "No listener socket available");
158624cdd46SDaniel P. Berrange         return;
159624cdd46SDaniel P. Berrange     }
160624cdd46SDaniel P. Berrange 
16104d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, errp);
16204d2529dSDaniel P. Berrange     if (!addr) {
16398481bfcSEric Blake         return;
1643e230dd2SCorentin Chary     }
1653e230dd2SCorentin Chary 
16604d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
167bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1683e230dd2SCorentin Chary }
1693e230dd2SCorentin Chary 
17004d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
17104d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
17298481bfcSEric Blake                                                  Error **errp)
1733e230dd2SCorentin Chary {
174bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1753e230dd2SCorentin Chary 
17604d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_remote_address(ioc, errp);
17704d2529dSDaniel P. Berrange     if (!addr) {
17898481bfcSEric Blake         return;
1793e230dd2SCorentin Chary     }
1803e230dd2SCorentin Chary 
18104d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
182bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1833e230dd2SCorentin Chary }
1843e230dd2SCorentin Chary 
1853e230dd2SCorentin Chary static const char *vnc_auth_name(VncDisplay *vd) {
1863e230dd2SCorentin Chary     switch (vd->auth) {
1873e230dd2SCorentin Chary     case VNC_AUTH_INVALID:
1883e230dd2SCorentin Chary         return "invalid";
1893e230dd2SCorentin Chary     case VNC_AUTH_NONE:
1903e230dd2SCorentin Chary         return "none";
1913e230dd2SCorentin Chary     case VNC_AUTH_VNC:
1923e230dd2SCorentin Chary         return "vnc";
1933e230dd2SCorentin Chary     case VNC_AUTH_RA2:
1943e230dd2SCorentin Chary         return "ra2";
1953e230dd2SCorentin Chary     case VNC_AUTH_RA2NE:
1963e230dd2SCorentin Chary         return "ra2ne";
1973e230dd2SCorentin Chary     case VNC_AUTH_TIGHT:
1983e230dd2SCorentin Chary         return "tight";
1993e230dd2SCorentin Chary     case VNC_AUTH_ULTRA:
2003e230dd2SCorentin Chary         return "ultra";
2013e230dd2SCorentin Chary     case VNC_AUTH_TLS:
2023e230dd2SCorentin Chary         return "tls";
2033e230dd2SCorentin Chary     case VNC_AUTH_VENCRYPT:
2043e230dd2SCorentin Chary         switch (vd->subauth) {
2053e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_PLAIN:
2063e230dd2SCorentin Chary             return "vencrypt+plain";
2073e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSNONE:
2083e230dd2SCorentin Chary             return "vencrypt+tls+none";
2093e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSVNC:
2103e230dd2SCorentin Chary             return "vencrypt+tls+vnc";
2113e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSPLAIN:
2123e230dd2SCorentin Chary             return "vencrypt+tls+plain";
2133e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509NONE:
2143e230dd2SCorentin Chary             return "vencrypt+x509+none";
2153e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509VNC:
2163e230dd2SCorentin Chary             return "vencrypt+x509+vnc";
2173e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509PLAIN:
2183e230dd2SCorentin Chary             return "vencrypt+x509+plain";
2193e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSSASL:
2203e230dd2SCorentin Chary             return "vencrypt+tls+sasl";
2213e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509SASL:
2223e230dd2SCorentin Chary             return "vencrypt+x509+sasl";
2233e230dd2SCorentin Chary         default:
2243e230dd2SCorentin Chary             return "vencrypt";
2253e230dd2SCorentin Chary         }
2263e230dd2SCorentin Chary     case VNC_AUTH_SASL:
2273e230dd2SCorentin Chary         return "sasl";
2283e230dd2SCorentin Chary     }
2293e230dd2SCorentin Chary     return "unknown";
2303e230dd2SCorentin Chary }
2313e230dd2SCorentin Chary 
232d616ccc5SGerd Hoffmann static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
2333e230dd2SCorentin Chary {
234fb6ba0d5SWenchao Xia     VncServerInfo *info;
23598481bfcSEric Blake     Error *err = NULL;
2363e230dd2SCorentin Chary 
23713e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
2384ee74fa7SDaniel P. Berrange         return NULL;
2394ee74fa7SDaniel P. Berrange     }
2404ee74fa7SDaniel P. Berrange 
2413e7f136dSDaniel P. Berrange     info = g_malloc0(sizeof(*info));
24213e1d0e7SDaniel P. Berrange     vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
243ddf21908SEric Blake                                          qapi_VncServerInfo_base(info), &err);
244fb6ba0d5SWenchao Xia     info->has_auth = true;
245d616ccc5SGerd Hoffmann     info->auth = g_strdup(vnc_auth_name(vd));
24698481bfcSEric Blake     if (err) {
24798481bfcSEric Blake         qapi_free_VncServerInfo(info);
24898481bfcSEric Blake         info = NULL;
24998481bfcSEric Blake         error_free(err);
25098481bfcSEric Blake     }
251fb6ba0d5SWenchao Xia     return info;
2523e230dd2SCorentin Chary }
2533e230dd2SCorentin Chary 
2543e230dd2SCorentin Chary static void vnc_client_cache_auth(VncState *client)
2553e230dd2SCorentin Chary {
2563e230dd2SCorentin Chary     if (!client->info) {
2573e230dd2SCorentin Chary         return;
2583e230dd2SCorentin Chary     }
2593e230dd2SCorentin Chary 
2603e305e4aSDaniel P. Berrange     if (client->tls) {
2613e305e4aSDaniel P. Berrange         client->info->x509_dname =
2623e305e4aSDaniel P. Berrange             qcrypto_tls_session_get_peer_name(client->tls);
2633e305e4aSDaniel P. Berrange         client->info->has_x509_dname =
2643e305e4aSDaniel P. Berrange             client->info->x509_dname != NULL;
2653e230dd2SCorentin Chary     }
2663e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
2673e230dd2SCorentin Chary     if (client->sasl.conn &&
2683e230dd2SCorentin Chary         client->sasl.username) {
269fb6ba0d5SWenchao Xia         client->info->has_sasl_username = true;
270fb6ba0d5SWenchao Xia         client->info->sasl_username = g_strdup(client->sasl.username);
2713e230dd2SCorentin Chary     }
2723e230dd2SCorentin Chary #endif
2733e230dd2SCorentin Chary }
2743e230dd2SCorentin Chary 
2753e230dd2SCorentin Chary static void vnc_client_cache_addr(VncState *client)
2763e230dd2SCorentin Chary {
27798481bfcSEric Blake     Error *err = NULL;
2783e230dd2SCorentin Chary 
279fb6ba0d5SWenchao Xia     client->info = g_malloc0(sizeof(*client->info));
28004d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
281ddf21908SEric Blake                                          qapi_VncClientInfo_base(client->info),
28298481bfcSEric Blake                                          &err);
283e1b3d477SGerd Hoffmann     client->info->websocket = client->websocket;
28498481bfcSEric Blake     if (err) {
28598481bfcSEric Blake         qapi_free_VncClientInfo(client->info);
28698481bfcSEric Blake         client->info = NULL;
28798481bfcSEric Blake         error_free(err);
288fb6ba0d5SWenchao Xia     }
2893e230dd2SCorentin Chary }
2903e230dd2SCorentin Chary 
291fb6ba0d5SWenchao Xia static void vnc_qmp_event(VncState *vs, QAPIEvent event)
2923e230dd2SCorentin Chary {
293fb6ba0d5SWenchao Xia     VncServerInfo *si;
2943e230dd2SCorentin Chary 
2953e230dd2SCorentin Chary     if (!vs->info) {
2963e230dd2SCorentin Chary         return;
2973e230dd2SCorentin Chary     }
2983e230dd2SCorentin Chary 
299d616ccc5SGerd Hoffmann     si = vnc_server_info_get(vs->vd);
300fb6ba0d5SWenchao Xia     if (!si) {
3013e230dd2SCorentin Chary         return;
3023e230dd2SCorentin Chary     }
3033e230dd2SCorentin Chary 
304fb6ba0d5SWenchao Xia     switch (event) {
305fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_CONNECTED:
3063ab72385SPeter Xu         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
307fb6ba0d5SWenchao Xia         break;
308fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_INITIALIZED:
3093ab72385SPeter Xu         qapi_event_send_vnc_initialized(si, vs->info);
310fb6ba0d5SWenchao Xia         break;
311fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_DISCONNECTED:
3123ab72385SPeter Xu         qapi_event_send_vnc_disconnected(si, vs->info);
313fb6ba0d5SWenchao Xia         break;
314fb6ba0d5SWenchao Xia     default:
315fb6ba0d5SWenchao Xia         break;
316fb6ba0d5SWenchao Xia     }
3173e230dd2SCorentin Chary 
318fb6ba0d5SWenchao Xia     qapi_free_VncServerInfo(si);
3193e230dd2SCorentin Chary }
3203e230dd2SCorentin Chary 
3212b54aa87SLuiz Capitulino static VncClientInfo *qmp_query_vnc_client(const VncState *client)
3223e230dd2SCorentin Chary {
3232b54aa87SLuiz Capitulino     VncClientInfo *info;
32404d2529dSDaniel P. Berrange     Error *err = NULL;
3252b54aa87SLuiz Capitulino 
3262b54aa87SLuiz Capitulino     info = g_malloc0(sizeof(*info));
32704d2529dSDaniel P. Berrange 
32804d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
32904d2529dSDaniel P. Berrange                                          qapi_VncClientInfo_base(info),
33004d2529dSDaniel P. Berrange                                          &err);
33104d2529dSDaniel P. Berrange     if (err) {
33204d2529dSDaniel P. Berrange         error_free(err);
33304d2529dSDaniel P. Berrange         qapi_free_VncClientInfo(info);
33404d2529dSDaniel P. Berrange         return NULL;
33504d2529dSDaniel P. Berrange     }
33604d2529dSDaniel P. Berrange 
337ddf21908SEric Blake     info->websocket = client->websocket;
3383e230dd2SCorentin Chary 
3393e305e4aSDaniel P. Berrange     if (client->tls) {
3403e305e4aSDaniel P. Berrange         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
3413e305e4aSDaniel P. Berrange         info->has_x509_dname = info->x509_dname != NULL;
3422b54aa87SLuiz Capitulino     }
3433e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
3442b54aa87SLuiz Capitulino     if (client->sasl.conn && client->sasl.username) {
3452b54aa87SLuiz Capitulino         info->has_sasl_username = true;
3462b54aa87SLuiz Capitulino         info->sasl_username = g_strdup(client->sasl.username);
3472b54aa87SLuiz Capitulino     }
3483e230dd2SCorentin Chary #endif
3492b54aa87SLuiz Capitulino 
3502b54aa87SLuiz Capitulino     return info;
3513e230dd2SCorentin Chary }
3523e230dd2SCorentin Chary 
353d616ccc5SGerd Hoffmann static VncDisplay *vnc_display_find(const char *id)
354d616ccc5SGerd Hoffmann {
355d616ccc5SGerd Hoffmann     VncDisplay *vd;
356d616ccc5SGerd Hoffmann 
357d616ccc5SGerd Hoffmann     if (id == NULL) {
358d616ccc5SGerd Hoffmann         return QTAILQ_FIRST(&vnc_displays);
359d616ccc5SGerd Hoffmann     }
360d616ccc5SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
361d616ccc5SGerd Hoffmann         if (strcmp(id, vd->id) == 0) {
362d616ccc5SGerd Hoffmann             return vd;
363d616ccc5SGerd Hoffmann         }
364d616ccc5SGerd Hoffmann     }
365d616ccc5SGerd Hoffmann     return NULL;
366d616ccc5SGerd Hoffmann }
367d616ccc5SGerd Hoffmann 
3682d29a436SGerd Hoffmann static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
3692d29a436SGerd Hoffmann {
37054aa3de7SEric Blake     VncClientInfoList *prev = NULL;
3712d29a436SGerd Hoffmann     VncState *client;
3722d29a436SGerd Hoffmann 
3732d29a436SGerd Hoffmann     QTAILQ_FOREACH(client, &vd->clients, next) {
37454aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, qmp_query_vnc_client(client));
3752d29a436SGerd Hoffmann     }
3762d29a436SGerd Hoffmann     return prev;
3772d29a436SGerd Hoffmann }
3782d29a436SGerd Hoffmann 
3792b54aa87SLuiz Capitulino VncInfo *qmp_query_vnc(Error **errp)
3803e230dd2SCorentin Chary {
3812b54aa87SLuiz Capitulino     VncInfo *info = g_malloc0(sizeof(*info));
382d616ccc5SGerd Hoffmann     VncDisplay *vd = vnc_display_find(NULL);
383bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3843e230dd2SCorentin Chary 
38513e1d0e7SDaniel P. Berrange     if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
3862b54aa87SLuiz Capitulino         info->enabled = false;
3873e230dd2SCorentin Chary     } else {
3882b54aa87SLuiz Capitulino         info->enabled = true;
3892b54aa87SLuiz Capitulino 
3902b54aa87SLuiz Capitulino         /* for compatibility with the original command */
3912b54aa87SLuiz Capitulino         info->has_clients = true;
3922d29a436SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
3933e230dd2SCorentin Chary 
39413e1d0e7SDaniel P. Berrange         addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
39513e1d0e7SDaniel P. Berrange                                                     errp);
39604d2529dSDaniel P. Berrange         if (!addr) {
3972b54aa87SLuiz Capitulino             goto out_error;
3982b54aa87SLuiz Capitulino         }
3993e230dd2SCorentin Chary 
40004d2529dSDaniel P. Berrange         switch (addr->type) {
401bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_INET:
402bd269ebcSMarkus Armbruster             info->host = g_strdup(addr->u.inet.host);
403bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.inet.port);
404bd269ebcSMarkus Armbruster             if (addr->u.inet.ipv6) {
40504d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
40604d2529dSDaniel P. Berrange             } else {
40704d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
40804d2529dSDaniel P. Berrange             }
40904d2529dSDaniel P. Berrange             break;
41004d2529dSDaniel P. Berrange 
411bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_UNIX:
41204d2529dSDaniel P. Berrange             info->host = g_strdup("");
413bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.q_unix.path);
41404d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
41504d2529dSDaniel P. Berrange             break;
41604d2529dSDaniel P. Berrange 
417bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_VSOCK:
418bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_FD:
419a6c76285SMarkus Armbruster             error_setg(errp, "Unsupported socket address type %s",
420977c736fSMarkus Armbruster                        SocketAddressType_str(addr->type));
4212b54aa87SLuiz Capitulino             goto out_error;
422a6c76285SMarkus Armbruster         default:
423a6c76285SMarkus Armbruster             abort();
4243e230dd2SCorentin Chary         }
4252b54aa87SLuiz Capitulino 
4262b54aa87SLuiz Capitulino         info->has_host = true;
4272b54aa87SLuiz Capitulino         info->has_service = true;
4282b54aa87SLuiz Capitulino         info->has_family = true;
4292b54aa87SLuiz Capitulino 
4302b54aa87SLuiz Capitulino         info->has_auth = true;
431d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4323e230dd2SCorentin Chary     }
4332b54aa87SLuiz Capitulino 
434bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4352b54aa87SLuiz Capitulino     return info;
4362b54aa87SLuiz Capitulino 
4372b54aa87SLuiz Capitulino out_error:
438bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4392b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4402b54aa87SLuiz Capitulino     return NULL;
4413e230dd2SCorentin Chary }
4423e230dd2SCorentin Chary 
4432a7e6857SDaniel P. Berrange 
4442a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4452a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4462a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4472a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt);
4482a7e6857SDaniel P. Berrange 
4492a7e6857SDaniel P. Berrange static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
4504478aa76SGerd Hoffmann                                                   bool websocket,
4512a7e6857SDaniel P. Berrange                                                   int auth,
4522a7e6857SDaniel P. Berrange                                                   int subauth,
4532a7e6857SDaniel P. Berrange                                                   VncServerInfo2List *prev)
454df887684SGerd Hoffmann {
4552a7e6857SDaniel P. Berrange     VncServerInfo2 *info;
45604d2529dSDaniel P. Berrange     Error *err = NULL;
457bd269ebcSMarkus Armbruster     SocketAddress *addr;
458df887684SGerd Hoffmann 
4599261ef5eSMarkus Armbruster     addr = qio_channel_socket_get_local_address(ioc, NULL);
46004d2529dSDaniel P. Berrange     if (!addr) {
461df887684SGerd Hoffmann         return prev;
462df887684SGerd Hoffmann     }
463df887684SGerd Hoffmann 
4642a7e6857SDaniel P. Berrange     info = g_new0(VncServerInfo2, 1);
4652a7e6857SDaniel P. Berrange     vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
466bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
46704d2529dSDaniel P. Berrange     if (err) {
4682a7e6857SDaniel P. Berrange         qapi_free_VncServerInfo2(info);
46904d2529dSDaniel P. Berrange         error_free(err);
47004d2529dSDaniel P. Berrange         return prev;
47104d2529dSDaniel P. Berrange     }
4724478aa76SGerd Hoffmann     info->websocket = websocket;
473df887684SGerd Hoffmann 
4742a7e6857SDaniel P. Berrange     qmp_query_auth(auth, subauth, &info->auth,
4752a7e6857SDaniel P. Berrange                    &info->vencrypt, &info->has_vencrypt);
4762a7e6857SDaniel P. Berrange 
47754aa3de7SEric Blake     QAPI_LIST_PREPEND(prev, info);
47854aa3de7SEric Blake     return prev;
479df887684SGerd Hoffmann }
480df887684SGerd Hoffmann 
4812a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4822a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4832a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4842a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt)
485df887684SGerd Hoffmann {
4862a7e6857SDaniel P. Berrange     switch (auth) {
487df887684SGerd Hoffmann     case VNC_AUTH_VNC:
4882a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VNC;
489df887684SGerd Hoffmann         break;
490df887684SGerd Hoffmann     case VNC_AUTH_RA2:
4912a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2;
492df887684SGerd Hoffmann         break;
493df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
4942a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
495df887684SGerd Hoffmann         break;
496df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
4972a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
498df887684SGerd Hoffmann         break;
499df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
5002a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
501df887684SGerd Hoffmann         break;
502df887684SGerd Hoffmann     case VNC_AUTH_TLS:
5032a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TLS;
504df887684SGerd Hoffmann         break;
505df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
5062a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
5072a7e6857SDaniel P. Berrange         *qmp_has_vencrypt = true;
5082a7e6857SDaniel P. Berrange         switch (subauth) {
509df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
5102a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
511df887684SGerd Hoffmann             break;
512df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
5132a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
514df887684SGerd Hoffmann             break;
515df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
5162a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
517df887684SGerd Hoffmann             break;
518df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
5192a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
520df887684SGerd Hoffmann             break;
521df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
5222a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
523df887684SGerd Hoffmann             break;
524df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
5252a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
526df887684SGerd Hoffmann             break;
527df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
5282a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
529df887684SGerd Hoffmann             break;
530df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
5312a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
532df887684SGerd Hoffmann             break;
533df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
5342a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
535df887684SGerd Hoffmann             break;
536df887684SGerd Hoffmann         default:
5372a7e6857SDaniel P. Berrange             *qmp_has_vencrypt = false;
538df887684SGerd Hoffmann             break;
539df887684SGerd Hoffmann         }
540df887684SGerd Hoffmann         break;
541df887684SGerd Hoffmann     case VNC_AUTH_SASL:
5422a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_SASL;
543df887684SGerd Hoffmann         break;
544df887684SGerd Hoffmann     case VNC_AUTH_NONE:
545df887684SGerd Hoffmann     default:
5462a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_NONE;
547df887684SGerd Hoffmann         break;
548df887684SGerd Hoffmann     }
549df887684SGerd Hoffmann }
550df887684SGerd Hoffmann 
551df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
552df887684SGerd Hoffmann {
55354aa3de7SEric Blake     VncInfo2List *prev = NULL;
554df887684SGerd Hoffmann     VncInfo2 *info;
555df887684SGerd Hoffmann     VncDisplay *vd;
556df887684SGerd Hoffmann     DeviceState *dev;
5574ee74fa7SDaniel P. Berrange     size_t i;
558df887684SGerd Hoffmann 
559df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
560df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
561df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
562df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
5632a7e6857SDaniel P. Berrange         qmp_query_auth(vd->auth, vd->subauth, &info->auth,
5642a7e6857SDaniel P. Berrange                        &info->vencrypt, &info->has_vencrypt);
565df887684SGerd Hoffmann         if (vd->dcl.con) {
566df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
567552d7f49SMarkus Armbruster                                                   "device", &error_abort));
568df887684SGerd Hoffmann             info->has_display = true;
569df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
570df887684SGerd Hoffmann         }
57113e1d0e7SDaniel P. Berrange         for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
57204d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57313e1d0e7SDaniel P. Berrange                 vd->listener->sioc[i], false, vd->auth, vd->subauth,
57413e1d0e7SDaniel P. Berrange                 info->server);
575df887684SGerd Hoffmann         }
57613e1d0e7SDaniel P. Berrange         for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
57704d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57813e1d0e7SDaniel P. Berrange                 vd->wslistener->sioc[i], true, vd->ws_auth,
5794ee74fa7SDaniel P. Berrange                 vd->ws_subauth, info->server);
580df887684SGerd Hoffmann         }
581df887684SGerd Hoffmann 
58254aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, info);
583df887684SGerd Hoffmann     }
584df887684SGerd Hoffmann     return prev;
585df887684SGerd Hoffmann }
586df887684SGerd Hoffmann 
5873e230dd2SCorentin Chary /* TODO
5883e230dd2SCorentin Chary    1) Get the queue working for IO.
5893e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
5903e230dd2SCorentin Chary       and not totally invalidated
5913e230dd2SCorentin Chary    3) resolutions > 1024
5923e230dd2SCorentin Chary */
5933e230dd2SCorentin Chary 
5946af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty);
5953e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
5963e230dd2SCorentin Chary 
5973e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
5983e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
5993e230dd2SCorentin Chary                                        int x_position, int y_position,
6003e230dd2SCorentin Chary                                        int w, int h);
6010f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
6023e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
6033e230dd2SCorentin Chary 
604d05959c2SGerd Hoffmann static int vnc_width(VncDisplay *vd)
605d05959c2SGerd Hoffmann {
606d05959c2SGerd Hoffmann     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
607d05959c2SGerd Hoffmann                                        VNC_DIRTY_PIXELS_PER_BIT));
608d05959c2SGerd Hoffmann }
609d05959c2SGerd Hoffmann 
610d05959c2SGerd Hoffmann static int vnc_height(VncDisplay *vd)
611d05959c2SGerd Hoffmann {
612d05959c2SGerd Hoffmann     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
613d05959c2SGerd Hoffmann }
614d05959c2SGerd Hoffmann 
615bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
616bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
617f7b3d68cSGerd Hoffmann                                VncDisplay *vd,
618f7b3d68cSGerd Hoffmann                                int x, int y, int w, int h)
619f7b3d68cSGerd Hoffmann {
620f7b3d68cSGerd Hoffmann     int width = vnc_width(vd);
621f7b3d68cSGerd Hoffmann     int height = vnc_height(vd);
622f7b3d68cSGerd Hoffmann 
62391937225SPeter Lieven     /* this is needed this to ensure we updated all affected
62491937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
625b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
626b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6273e230dd2SCorentin Chary 
6289f64916dSGerd Hoffmann     x = MIN(x, width);
6299f64916dSGerd Hoffmann     y = MIN(y, height);
6309f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
63191937225SPeter Lieven     h = MIN(y + h, height);
6323e230dd2SCorentin Chary 
633b4c85ddcSPeter Lieven     for (; y < h; y++) {
634bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
63591937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
636b4c85ddcSPeter Lieven     }
6373e230dd2SCorentin Chary }
6383e230dd2SCorentin Chary 
639bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
640bea60dd7SPeter Lieven                            int x, int y, int w, int h)
641bea60dd7SPeter Lieven {
642bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
643bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
644bea60dd7SPeter Lieven 
645f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
646bea60dd7SPeter Lieven }
647bea60dd7SPeter Lieven 
6483e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6493e230dd2SCorentin Chary                             int32_t encoding)
6503e230dd2SCorentin Chary {
6513e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6523e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6533e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6543e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6553e230dd2SCorentin Chary 
6563e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6573e230dd2SCorentin Chary }
6583e230dd2SCorentin Chary 
659763deea7SGerd Hoffmann static void vnc_desktop_resize_ext(VncState *vs, int reject_reason)
660763deea7SGerd Hoffmann {
661763deea7SGerd Hoffmann     vnc_lock_output(vs);
662763deea7SGerd Hoffmann     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
663763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);
664763deea7SGerd Hoffmann     vnc_write_u16(vs, 1); /* number of rects */
665763deea7SGerd Hoffmann     vnc_framebuffer_update(vs,
666763deea7SGerd Hoffmann                            reject_reason ? 1 : 0,
667763deea7SGerd Hoffmann                            reject_reason,
668763deea7SGerd Hoffmann                            vs->client_width, vs->client_height,
669763deea7SGerd Hoffmann                            VNC_ENCODING_DESKTOP_RESIZE_EXT);
670763deea7SGerd Hoffmann     vnc_write_u8(vs, 1);  /* number of screens */
671763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
672763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
673763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
674763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen id */
675763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen x-pos */
676763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen y-pos */
677763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_width);
678763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_height);
679763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen flags */
680763deea7SGerd Hoffmann     vnc_unlock_output(vs);
681763deea7SGerd Hoffmann     vnc_flush(vs);
682763deea7SGerd Hoffmann }
68332ed2680STim Hardeck 
6843e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
6853e230dd2SCorentin Chary {
686763deea7SGerd Hoffmann     if (vs->ioc == NULL || (!vnc_has_feature(vs, VNC_FEATURE_RESIZE) &&
687763deea7SGerd Hoffmann                             !vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT))) {
6883e230dd2SCorentin Chary         return;
6893e230dd2SCorentin Chary     }
690*d239726cSGerd Hoffmann     if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
691*d239726cSGerd Hoffmann         vs->client_height == pixman_image_get_height(vs->vd->server)) {
692*d239726cSGerd Hoffmann         return;
693*d239726cSGerd Hoffmann     }
6944c956bd8SDaniel P. Berrange 
6954c956bd8SDaniel P. Berrange     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
6964c956bd8SDaniel P. Berrange            pixman_image_get_width(vs->vd->server) >= 0);
6974c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
6984c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
699bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
700bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
701763deea7SGerd Hoffmann 
702763deea7SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
703763deea7SGerd Hoffmann         vnc_desktop_resize_ext(vs, 0);
704763deea7SGerd Hoffmann         return;
705763deea7SGerd Hoffmann     }
706763deea7SGerd Hoffmann 
707bd023f95SCorentin Chary     vnc_lock_output(vs);
7083e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
7093e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
7103e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
7113e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
7123e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
713bd023f95SCorentin Chary     vnc_unlock_output(vs);
7143e230dd2SCorentin Chary     vnc_flush(vs);
7153e230dd2SCorentin Chary }
7163e230dd2SCorentin Chary 
717bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
718bd023f95SCorentin Chary {
719bd023f95SCorentin Chary     VncState *vs;
720bd023f95SCorentin Chary 
721bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
722bd023f95SCorentin Chary         vnc_lock_output(vs);
723bd023f95SCorentin Chary         vs->abort = true;
724bd023f95SCorentin Chary         vnc_unlock_output(vs);
725bd023f95SCorentin Chary     }
726bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
727bd023f95SCorentin Chary         vnc_jobs_join(vs);
728bd023f95SCorentin Chary     }
729bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
730bd023f95SCorentin Chary         vnc_lock_output(vs);
731bbcdeb62SGerd Hoffmann         if (vs->update == VNC_STATE_UPDATE_NONE &&
732bbcdeb62SGerd Hoffmann             vs->job_update != VNC_STATE_UPDATE_NONE) {
733bbcdeb62SGerd Hoffmann             /* job aborted before completion */
734bbcdeb62SGerd Hoffmann             vs->update = vs->job_update;
735bbcdeb62SGerd Hoffmann             vs->job_update = VNC_STATE_UPDATE_NONE;
736bbcdeb62SGerd Hoffmann         }
737bd023f95SCorentin Chary         vs->abort = false;
738bd023f95SCorentin Chary         vnc_unlock_output(vs);
739bd023f95SCorentin Chary     }
740bd023f95SCorentin Chary }
741bd023f95SCorentin Chary 
7429f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
7439f64916dSGerd Hoffmann {
7449f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
7459f64916dSGerd Hoffmann }
7469f64916dSGerd Hoffmann 
7479f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
7489f64916dSGerd Hoffmann {
7499f64916dSGerd Hoffmann     uint8_t *ptr;
7509f64916dSGerd Hoffmann 
7519f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
7529f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
7539f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
7549f64916dSGerd Hoffmann     return ptr;
7559f64916dSGerd Hoffmann }
7569f64916dSGerd Hoffmann 
757453f842bSGerd Hoffmann static void vnc_update_server_surface(VncDisplay *vd)
758453f842bSGerd Hoffmann {
759b69a553bSDaniel P. Berrange     int width, height;
760b69a553bSDaniel P. Berrange 
761453f842bSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
762453f842bSGerd Hoffmann     vd->server = NULL;
763453f842bSGerd Hoffmann 
764c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vd->clients)) {
765c7628bffSGerd Hoffmann         return;
766c7628bffSGerd Hoffmann     }
767c7628bffSGerd Hoffmann 
768b69a553bSDaniel P. Berrange     width = vnc_width(vd);
769b69a553bSDaniel P. Berrange     height = vnc_height(vd);
770453f842bSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
771b69a553bSDaniel P. Berrange                                           width, height,
772453f842bSGerd Hoffmann                                           NULL, 0);
773b69a553bSDaniel P. Berrange 
774b69a553bSDaniel P. Berrange     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
775b69a553bSDaniel P. Berrange     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
776b69a553bSDaniel P. Berrange                        width, height);
777453f842bSGerd Hoffmann }
778453f842bSGerd Hoffmann 
77961e77a5fSGerd Hoffmann static bool vnc_check_pageflip(DisplaySurface *s1,
78061e77a5fSGerd Hoffmann                                DisplaySurface *s2)
78161e77a5fSGerd Hoffmann {
78261e77a5fSGerd Hoffmann     return (s1 != NULL &&
78361e77a5fSGerd Hoffmann             s2 != NULL &&
78461e77a5fSGerd Hoffmann             surface_width(s1) == surface_width(s2) &&
78561e77a5fSGerd Hoffmann             surface_height(s1) == surface_height(s2) &&
78661e77a5fSGerd Hoffmann             surface_format(s1) == surface_format(s2));
78761e77a5fSGerd Hoffmann 
78861e77a5fSGerd Hoffmann }
78961e77a5fSGerd Hoffmann 
790c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
791c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
7923e230dd2SCorentin Chary {
7932e5567c9SGerd Hoffmann     static const char placeholder_msg[] =
7942e5567c9SGerd Hoffmann         "Display output is not active.";
7952e5567c9SGerd Hoffmann     static DisplaySurface *placeholder;
79621ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
79761e77a5fSGerd Hoffmann     bool pageflip = vnc_check_pageflip(vd->ds, surface);
7983e230dd2SCorentin Chary     VncState *vs;
7993e230dd2SCorentin Chary 
8002e5567c9SGerd Hoffmann     if (surface == NULL) {
8012e5567c9SGerd Hoffmann         if (placeholder == NULL) {
8022e5567c9SGerd Hoffmann             placeholder = qemu_create_message_surface(640, 480, placeholder_msg);
8032e5567c9SGerd Hoffmann         }
8042e5567c9SGerd Hoffmann         surface = placeholder;
8052e5567c9SGerd Hoffmann     }
8062e5567c9SGerd Hoffmann 
807bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
808453f842bSGerd Hoffmann     vd->ds = surface;
809bd023f95SCorentin Chary 
8103e230dd2SCorentin Chary     /* guest surface */
8119f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
812d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
813d39fa6d8SGerd Hoffmann     vd->guest.format = surface->format;
8143e230dd2SCorentin Chary 
81561e77a5fSGerd Hoffmann     if (pageflip) {
81661e77a5fSGerd Hoffmann         vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
81761e77a5fSGerd Hoffmann                            surface_width(surface),
81861e77a5fSGerd Hoffmann                            surface_height(surface));
81961e77a5fSGerd Hoffmann         return;
82061e77a5fSGerd Hoffmann     }
82161e77a5fSGerd Hoffmann 
82261e77a5fSGerd Hoffmann     /* server surface */
82361e77a5fSGerd Hoffmann     vnc_update_server_surface(vd);
82461e77a5fSGerd Hoffmann 
8253e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
8263e230dd2SCorentin Chary         vnc_colordepth(vs);
8273e230dd2SCorentin Chary         vnc_desktop_resize(vs);
8283e230dd2SCorentin Chary         vnc_cursor_define(vs);
829bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
830f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
831b69a553bSDaniel P. Berrange                            vnc_width(vd),
832b69a553bSDaniel P. Berrange                            vnc_height(vd));
833e2b72cb6SDaniel P. Berrange         vnc_update_throttle_offset(vs);
8343e230dd2SCorentin Chary     }
8353e230dd2SCorentin Chary }
8363e230dd2SCorentin Chary 
8373e230dd2SCorentin Chary /* fastest code */
8389f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
8393e230dd2SCorentin Chary                                   void *pixels, int size)
8403e230dd2SCorentin Chary {
8413e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
8423e230dd2SCorentin Chary }
8433e230dd2SCorentin Chary 
8443e230dd2SCorentin Chary /* slowest but generic code. */
8453e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
8463e230dd2SCorentin Chary {
8473e230dd2SCorentin Chary     uint8_t r, g, b;
8483e230dd2SCorentin Chary 
8499f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
8509f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
8519f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
8529f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
8539f64916dSGerd Hoffmann #else
8549f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
8559f64916dSGerd Hoffmann #endif
8569f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
8579f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
8589f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
8599f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
8603e230dd2SCorentin Chary     case 1:
8613e230dd2SCorentin Chary         buf[0] = v;
8623e230dd2SCorentin Chary         break;
8633e230dd2SCorentin Chary     case 2:
8649f64916dSGerd Hoffmann         if (vs->client_be) {
8653e230dd2SCorentin Chary             buf[0] = v >> 8;
8663e230dd2SCorentin Chary             buf[1] = v;
8673e230dd2SCorentin Chary         } else {
8683e230dd2SCorentin Chary             buf[1] = v >> 8;
8693e230dd2SCorentin Chary             buf[0] = v;
8703e230dd2SCorentin Chary         }
8713e230dd2SCorentin Chary         break;
8723e230dd2SCorentin Chary     default:
8733e230dd2SCorentin Chary     case 4:
8749f64916dSGerd Hoffmann         if (vs->client_be) {
8753e230dd2SCorentin Chary             buf[0] = v >> 24;
8763e230dd2SCorentin Chary             buf[1] = v >> 16;
8773e230dd2SCorentin Chary             buf[2] = v >> 8;
8783e230dd2SCorentin Chary             buf[3] = v;
8793e230dd2SCorentin Chary         } else {
8803e230dd2SCorentin Chary             buf[3] = v >> 24;
8813e230dd2SCorentin Chary             buf[2] = v >> 16;
8823e230dd2SCorentin Chary             buf[1] = v >> 8;
8833e230dd2SCorentin Chary             buf[0] = v;
8843e230dd2SCorentin Chary         }
8853e230dd2SCorentin Chary         break;
8863e230dd2SCorentin Chary     }
8873e230dd2SCorentin Chary }
8883e230dd2SCorentin Chary 
8899f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
8903e230dd2SCorentin Chary                                      void *pixels1, int size)
8913e230dd2SCorentin Chary {
8923e230dd2SCorentin Chary     uint8_t buf[4];
8933e230dd2SCorentin Chary 
8949f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
8953e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
8963e230dd2SCorentin Chary         int n, i;
8973e230dd2SCorentin Chary         n = size >> 2;
8983e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
8993e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
9009f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
9013e230dd2SCorentin Chary         }
9023e230dd2SCorentin Chary     }
9033e230dd2SCorentin Chary }
9043e230dd2SCorentin Chary 
9053e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9063e230dd2SCorentin Chary {
9073e230dd2SCorentin Chary     int i;
9083e230dd2SCorentin Chary     uint8_t *row;
9093e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
9103e230dd2SCorentin Chary 
9119f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
9123e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
9139f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
9149f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
9153e230dd2SCorentin Chary     }
9163e230dd2SCorentin Chary     return 1;
9173e230dd2SCorentin Chary }
9183e230dd2SCorentin Chary 
919bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9203e230dd2SCorentin Chary {
9213e230dd2SCorentin Chary     int n = 0;
9223e230dd2SCorentin Chary 
9233e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
9243e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
9253e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
9263e230dd2SCorentin Chary             break;
9273e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
9283e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
9293e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
9303e230dd2SCorentin Chary             break;
9313e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
9323e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
9333e230dd2SCorentin Chary             break;
934efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
935efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
936efe556adSCorentin Chary             break;
937148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
938148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
939148954faSCorentin Chary             break;
940148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
941148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
942148954faSCorentin Chary             break;
9433e230dd2SCorentin Chary         default:
944de3f7de7SPeter Lieven             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
945de3f7de7SPeter Lieven             n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
9460780ec7bSGerd Hoffmann             break;
947de3f7de7SPeter Lieven     }
9483e230dd2SCorentin Chary     return n;
9493e230dd2SCorentin Chary }
9503e230dd2SCorentin Chary 
9517c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9527c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9533e230dd2SCorentin Chary {
9543e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9553e230dd2SCorentin Chary }
9563e230dd2SCorentin Chary 
9573e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
9583e230dd2SCorentin Chary {
9593e230dd2SCorentin Chary     QEMUCursor *c = vs->vd->cursor;
9603e230dd2SCorentin Chary     int isize;
9613e230dd2SCorentin Chary 
962b3c2de9cSGerd Hoffmann     if (!vs->vd->cursor) {
963b3c2de9cSGerd Hoffmann         return -1;
964b3c2de9cSGerd Hoffmann     }
965b3c2de9cSGerd Hoffmann 
966074a86d0SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
967074a86d0SGerd Hoffmann         vnc_lock_output(vs);
968074a86d0SGerd Hoffmann         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
969074a86d0SGerd Hoffmann         vnc_write_u8(vs,  0);  /*  padding     */
970074a86d0SGerd Hoffmann         vnc_write_u16(vs, 1);  /*  # of rects  */
971074a86d0SGerd Hoffmann         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
972074a86d0SGerd Hoffmann                                VNC_ENCODING_ALPHA_CURSOR);
973074a86d0SGerd Hoffmann         vnc_write_s32(vs, VNC_ENCODING_RAW);
974074a86d0SGerd Hoffmann         vnc_write(vs, c->data, c->width * c->height * 4);
975074a86d0SGerd Hoffmann         vnc_unlock_output(vs);
976074a86d0SGerd Hoffmann         return 0;
977074a86d0SGerd Hoffmann     }
9783e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
979d01f9595SCorentin Chary         vnc_lock_output(vs);
9803e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
9813e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
9823e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
9833e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
9843e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
9859f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
9869f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
9873e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
988d01f9595SCorentin Chary         vnc_unlock_output(vs);
9893e230dd2SCorentin Chary         return 0;
9903e230dd2SCorentin Chary     }
9913e230dd2SCorentin Chary     return -1;
9923e230dd2SCorentin Chary }
9933e230dd2SCorentin Chary 
9947c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
9957c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
9963e230dd2SCorentin Chary {
997d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
9983e230dd2SCorentin Chary     VncState *vs;
9993e230dd2SCorentin Chary 
10003e230dd2SCorentin Chary     cursor_put(vd->cursor);
10017267c094SAnthony Liguori     g_free(vd->cursor_mask);
10023e230dd2SCorentin Chary 
10033e230dd2SCorentin Chary     vd->cursor = c;
10043e230dd2SCorentin Chary     cursor_get(vd->cursor);
10053e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
10067267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
10073e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
10083e230dd2SCorentin Chary 
10093e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
10103e230dd2SCorentin Chary         vnc_cursor_define(vs);
10113e230dd2SCorentin Chary     }
10123e230dd2SCorentin Chary }
10133e230dd2SCorentin Chary 
10144769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
10156c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
10163e230dd2SCorentin Chary {
10173e230dd2SCorentin Chary     int h;
10183e230dd2SCorentin Chary 
10196c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
1020bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
10213e230dd2SCorentin Chary             break;
1022bc2429b9SCorentin Chary         }
1023863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
10243e230dd2SCorentin Chary     }
10253e230dd2SCorentin Chary 
10263e230dd2SCorentin Chary     return h;
10273e230dd2SCorentin Chary }
10283e230dd2SCorentin Chary 
1029e2b72cb6SDaniel P. Berrange /*
1030e2b72cb6SDaniel P. Berrange  * Figure out how much pending data we should allow in the output
1031e2b72cb6SDaniel P. Berrange  * buffer before we throttle incremental display updates, and/or
1032e2b72cb6SDaniel P. Berrange  * drop audio samples.
1033e2b72cb6SDaniel P. Berrange  *
1034e2b72cb6SDaniel P. Berrange  * We allow for equiv of 1 full display's worth of FB updates,
1035e2b72cb6SDaniel P. Berrange  * and 1 second of audio samples. If audio backlog was larger
1036e2b72cb6SDaniel P. Berrange  * than that the client would already suffering awful audio
1037e2b72cb6SDaniel P. Berrange  * glitches, so dropping samples is no worse really).
1038e2b72cb6SDaniel P. Berrange  */
1039e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs)
1040e2b72cb6SDaniel P. Berrange {
1041e2b72cb6SDaniel P. Berrange     size_t offset =
1042e2b72cb6SDaniel P. Berrange         vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1043e2b72cb6SDaniel P. Berrange 
1044e2b72cb6SDaniel P. Berrange     if (vs->audio_cap) {
1045e2b72cb6SDaniel P. Berrange         int bps;
1046e2b72cb6SDaniel P. Berrange         switch (vs->as.fmt) {
1047e2b72cb6SDaniel P. Berrange         default:
104885bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U8:
104985bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S8:
1050e2b72cb6SDaniel P. Berrange             bps = 1;
1051e2b72cb6SDaniel P. Berrange             break;
105285bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U16:
105385bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S16:
1054e2b72cb6SDaniel P. Berrange             bps = 2;
1055e2b72cb6SDaniel P. Berrange             break;
105685bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U32:
105785bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S32:
1058e2b72cb6SDaniel P. Berrange             bps = 4;
1059e2b72cb6SDaniel P. Berrange             break;
1060e2b72cb6SDaniel P. Berrange         }
1061cf070658SDaniel P. Berrangé         offset += vs->as.freq * bps * vs->as.nchannels;
1062e2b72cb6SDaniel P. Berrange     }
1063e2b72cb6SDaniel P. Berrange 
1064e2b72cb6SDaniel P. Berrange     /* Put a floor of 1MB on offset, so that if we have a large pending
1065e2b72cb6SDaniel P. Berrange      * buffer and the display is resized to a small size & back again
1066e2b72cb6SDaniel P. Berrange      * we don't suddenly apply a tiny send limit
1067e2b72cb6SDaniel P. Berrange      */
1068e2b72cb6SDaniel P. Berrange     offset = MAX(offset, 1024 * 1024);
1069e2b72cb6SDaniel P. Berrange 
10706aa22a29SDaniel P. Berrange     if (vs->throttle_output_offset != offset) {
10716aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_threshold(
10726aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
10736aa22a29SDaniel P. Berrange             vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
10746aa22a29SDaniel P. Berrange     }
10756aa22a29SDaniel P. Berrange 
1076e2b72cb6SDaniel P. Berrange     vs->throttle_output_offset = offset;
1077e2b72cb6SDaniel P. Berrange }
1078e2b72cb6SDaniel P. Berrange 
10790bad8342SDaniel P. Berrange static bool vnc_should_update(VncState *vs)
10800bad8342SDaniel P. Berrange {
10810bad8342SDaniel P. Berrange     switch (vs->update) {
10820bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_NONE:
10830bad8342SDaniel P. Berrange         break;
10840bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_INCREMENTAL:
1085e2b72cb6SDaniel P. Berrange         /* Only allow incremental updates if the pending send queue
1086ada8d2e4SDaniel P. Berrange          * is less than the permitted threshold, and the job worker
1087ada8d2e4SDaniel P. Berrange          * is completely idle.
10880bad8342SDaniel P. Berrange          */
1089ada8d2e4SDaniel P. Berrange         if (vs->output.offset < vs->throttle_output_offset &&
1090ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
10910bad8342SDaniel P. Berrange             return true;
10920bad8342SDaniel P. Berrange         }
10936aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_incremental(
10946aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->output.offset);
10950bad8342SDaniel P. Berrange         break;
10960bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_FORCE:
1097ada8d2e4SDaniel P. Berrange         /* Only allow forced updates if the pending send queue
1098ada8d2e4SDaniel P. Berrange          * does not contain a previous forced update, and the
1099ada8d2e4SDaniel P. Berrange          * job worker is completely idle.
1100ada8d2e4SDaniel P. Berrange          *
1101ada8d2e4SDaniel P. Berrange          * Note this means we'll queue a forced update, even if
1102ada8d2e4SDaniel P. Berrange          * the output buffer size is otherwise over the throttle
1103ada8d2e4SDaniel P. Berrange          * output limit.
1104ada8d2e4SDaniel P. Berrange          */
1105ada8d2e4SDaniel P. Berrange         if (vs->force_update_offset == 0 &&
1106ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
11070bad8342SDaniel P. Berrange             return true;
11080bad8342SDaniel P. Berrange         }
11096aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_forced(
11106aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->force_update_offset);
1111ada8d2e4SDaniel P. Berrange         break;
1112ada8d2e4SDaniel P. Berrange     }
11130bad8342SDaniel P. Berrange     return false;
11140bad8342SDaniel P. Berrange }
11150bad8342SDaniel P. Berrange 
11166af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty)
11173e230dd2SCorentin Chary {
11183e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
1119bd023f95SCorentin Chary     VncJob *job;
11203e230dd2SCorentin Chary     int y;
11212f487a3dSPeter Lieven     int height, width;
1122bd023f95SCorentin Chary     int n = 0;
1123bd023f95SCorentin Chary 
1124b939eb89SDaniel P. Berrange     if (vs->disconnecting) {
1125b939eb89SDaniel P. Berrange         vnc_disconnect_finish(vs);
1126b939eb89SDaniel P. Berrange         return 0;
1127b939eb89SDaniel P. Berrange     }
1128b939eb89SDaniel P. Berrange 
1129b939eb89SDaniel P. Berrange     vs->has_dirty += has_dirty;
11300bad8342SDaniel P. Berrange     if (!vnc_should_update(vs)) {
11313e230dd2SCorentin Chary         return 0;
1132b939eb89SDaniel P. Berrange     }
11333e230dd2SCorentin Chary 
1134fef1bbadSDaniel P. Berrange     if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
11353e230dd2SCorentin Chary         return 0;
1136b939eb89SDaniel P. Berrange     }
11373e230dd2SCorentin Chary 
11383e230dd2SCorentin Chary     /*
11393e230dd2SCorentin Chary      * Send screen updates to the vnc client using the server
11403e230dd2SCorentin Chary      * surface and server dirty map.  guest surface updates
11413e230dd2SCorentin Chary      * happening in parallel don't disturb us, the next pass will
11423e230dd2SCorentin Chary      * send them to the client.
11433e230dd2SCorentin Chary      */
1144bd023f95SCorentin Chary     job = vnc_job_new(vs);
11453e230dd2SCorentin Chary 
1146bea60dd7SPeter Lieven     height = pixman_image_get_height(vd->server);
1147bea60dd7SPeter Lieven     width = pixman_image_get_width(vd->server);
11483e230dd2SCorentin Chary 
114912b316d4SPeter Lieven     y = 0;
115012b316d4SPeter Lieven     for (;;) {
115112b316d4SPeter Lieven         int x, h;
115212b316d4SPeter Lieven         unsigned long x2;
115312b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
115412b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(vs),
115512b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(vs));
115612b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(vs)) {
115712b316d4SPeter Lieven             /* no more dirty bits */
115812b316d4SPeter Lieven             break;
11593e230dd2SCorentin Chary         }
116012b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(vs);
116112b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(vs);
116212b316d4SPeter Lieven         x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
116312b316d4SPeter Lieven                                 VNC_DIRTY_BPL(vs), x);
116412b316d4SPeter Lieven         bitmap_clear(vs->dirty[y], x, x2 - x);
116512b316d4SPeter Lieven         h = find_and_clear_dirty_height(vs, y, x, x2, height);
11662f487a3dSPeter Lieven         x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
11672f487a3dSPeter Lieven         if (x2 > x) {
116812b316d4SPeter Lieven             n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
116912b316d4SPeter Lieven                                   (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
11703e230dd2SCorentin Chary         }
11710e7d6f60SPeter Lieven         if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
11720e7d6f60SPeter Lieven             y += h;
11730e7d6f60SPeter Lieven             if (y == height) {
11740e7d6f60SPeter Lieven                 break;
11750e7d6f60SPeter Lieven             }
11760e7d6f60SPeter Lieven         }
11772f487a3dSPeter Lieven     }
1178bd023f95SCorentin Chary 
1179ada8d2e4SDaniel P. Berrange     vs->job_update = vs->update;
1180728a7ac9SDaniel P. Berrange     vs->update = VNC_STATE_UPDATE_NONE;
1181ada8d2e4SDaniel P. Berrange     vnc_job_push(job);
118263658280SGerd Hoffmann     vs->has_dirty = 0;
1183bd023f95SCorentin Chary     return n;
11843e230dd2SCorentin Chary }
11853e230dd2SCorentin Chary 
11863e230dd2SCorentin Chary /* audio */
11873e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
11883e230dd2SCorentin Chary {
11893e230dd2SCorentin Chary     VncState *vs = opaque;
11903e230dd2SCorentin Chary 
1191f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
11923e230dd2SCorentin Chary     switch (cmd) {
11933e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1194bd023f95SCorentin Chary         vnc_lock_output(vs);
11953e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11963e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11973e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1198bd023f95SCorentin Chary         vnc_unlock_output(vs);
11993e230dd2SCorentin Chary         vnc_flush(vs);
12003e230dd2SCorentin Chary         break;
12013e230dd2SCorentin Chary 
12023e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1203bd023f95SCorentin Chary         vnc_lock_output(vs);
12043e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12053e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12063e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1207bd023f95SCorentin Chary         vnc_unlock_output(vs);
12083e230dd2SCorentin Chary         vnc_flush(vs);
12093e230dd2SCorentin Chary         break;
12103e230dd2SCorentin Chary     }
12113e230dd2SCorentin Chary }
12123e230dd2SCorentin Chary 
12133e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
12143e230dd2SCorentin Chary {
12153e230dd2SCorentin Chary }
12163e230dd2SCorentin Chary 
121757a878edSPhilippe Mathieu-Daudé static void audio_capture(void *opaque, const void *buf, int size)
12183e230dd2SCorentin Chary {
12193e230dd2SCorentin Chary     VncState *vs = opaque;
12203e230dd2SCorentin Chary 
1221f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1222bd023f95SCorentin Chary     vnc_lock_output(vs);
1223e2b72cb6SDaniel P. Berrange     if (vs->output.offset < vs->throttle_output_offset) {
12243e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12253e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12263e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
12273e230dd2SCorentin Chary         vnc_write_u32(vs, size);
12283e230dd2SCorentin Chary         vnc_write(vs, buf, size);
12296aa22a29SDaniel P. Berrange     } else {
12306aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1231e2b72cb6SDaniel P. Berrange     }
1232bd023f95SCorentin Chary     vnc_unlock_output(vs);
12333e230dd2SCorentin Chary     vnc_flush(vs);
12343e230dd2SCorentin Chary }
12353e230dd2SCorentin Chary 
12363e230dd2SCorentin Chary static void audio_add(VncState *vs)
12373e230dd2SCorentin Chary {
12383e230dd2SCorentin Chary     struct audio_capture_ops ops;
12393e230dd2SCorentin Chary 
12403e230dd2SCorentin Chary     if (vs->audio_cap) {
1241027a79c3SCole Robinson         error_report("audio already running");
12423e230dd2SCorentin Chary         return;
12433e230dd2SCorentin Chary     }
12443e230dd2SCorentin Chary 
12453e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
12463e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
12473e230dd2SCorentin Chary     ops.capture = audio_capture;
12483e230dd2SCorentin Chary 
1249f0b9f36dSKővágó, Zoltán     vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
12503e230dd2SCorentin Chary     if (!vs->audio_cap) {
1251027a79c3SCole Robinson         error_report("Failed to add audio capture");
12523e230dd2SCorentin Chary     }
12533e230dd2SCorentin Chary }
12543e230dd2SCorentin Chary 
12553e230dd2SCorentin Chary static void audio_del(VncState *vs)
12563e230dd2SCorentin Chary {
12573e230dd2SCorentin Chary     if (vs->audio_cap) {
12583e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
12593e230dd2SCorentin Chary         vs->audio_cap = NULL;
12603e230dd2SCorentin Chary     }
12613e230dd2SCorentin Chary }
12623e230dd2SCorentin Chary 
12633e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
12643e230dd2SCorentin Chary {
126504d2529dSDaniel P. Berrange     if (vs->disconnecting) {
12663e230dd2SCorentin Chary         return;
126704d2529dSDaniel P. Berrange     }
1268ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_start(vs, vs->ioc);
12698cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
127004d2529dSDaniel P. Berrange     if (vs->ioc_tag) {
127104d2529dSDaniel P. Berrange         g_source_remove(vs->ioc_tag);
1272a75d6f07SBrandon Carpenter         vs->ioc_tag = 0;
127304d2529dSDaniel P. Berrange     }
127404d2529dSDaniel P. Berrange     qio_channel_close(vs->ioc, NULL);
127504d2529dSDaniel P. Berrange     vs->disconnecting = TRUE;
12763e230dd2SCorentin Chary }
12773e230dd2SCorentin Chary 
12787536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
12793e230dd2SCorentin Chary {
12807d964c9dSCorentin Chary     int i;
12817d964c9dSCorentin Chary 
1282ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_finish(vs, vs->ioc);
1283ad6374c4SDaniel P. Berrange 
1284bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1285bd023f95SCorentin Chary 
1286bd023f95SCorentin Chary     vnc_lock_output(vs);
1287fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
12883e230dd2SCorentin Chary 
12893e230dd2SCorentin Chary     buffer_free(&vs->input);
12903e230dd2SCorentin Chary     buffer_free(&vs->output);
12913e230dd2SCorentin Chary 
1292fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
12933e230dd2SCorentin Chary 
12943e230dd2SCorentin Chary     vnc_zlib_clear(vs);
12953e230dd2SCorentin Chary     vnc_tight_clear(vs);
1296148954faSCorentin Chary     vnc_zrle_clear(vs);
12973e230dd2SCorentin Chary 
12983e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
12993e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
13003e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13013e230dd2SCorentin Chary     audio_del(vs);
1302c2f2ba49SGerd Hoffmann     qkbd_state_lift_all_keys(vs->vd->kbd);
13033e230dd2SCorentin Chary 
130490cd03a3SDaniel P. Berrange     if (vs->mouse_mode_notifier.notify != NULL) {
13056fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
130690cd03a3SDaniel P. Berrange     }
130790cd03a3SDaniel P. Berrange     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1308c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1309c7628bffSGerd Hoffmann         /* last client gone */
1310c7628bffSGerd Hoffmann         vnc_update_server_surface(vs->vd);
1311c7628bffSGerd Hoffmann     }
13123e230dd2SCorentin Chary 
1313bd023f95SCorentin Chary     vnc_unlock_output(vs);
1314bd023f95SCorentin Chary 
1315bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
13166fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1317175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
13186fd8e79aSTim Hardeck     }
1319175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1320175b2a6eSCorentin Chary 
13217d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
13227267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
13237d964c9dSCorentin Chary     }
13247267c094SAnthony Liguori     g_free(vs->lossy_rect);
132504d2529dSDaniel P. Berrange 
132604d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->ioc));
132704d2529dSDaniel P. Berrange     vs->ioc = NULL;
132804d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->sioc));
132904d2529dSDaniel P. Berrange     vs->sioc = NULL;
1330f31f9c10SGerd Hoffmann     vs->magic = 0;
13316bf21f3dSLi Qiang     g_free(vs->zrle);
13326bf21f3dSLi Qiang     g_free(vs->tight);
13337267c094SAnthony Liguori     g_free(vs);
13343e230dd2SCorentin Chary }
13353e230dd2SCorentin Chary 
133634ab29c2SVladimir Sementsov-Ogievskiy size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
13373e230dd2SCorentin Chary {
133804d2529dSDaniel P. Berrange     if (ret <= 0) {
133904d2529dSDaniel P. Berrange         if (ret == 0) {
1340ad6374c4SDaniel P. Berrange             trace_vnc_client_eof(vs, vs->ioc);
1341537848eeSMichael Tokarev             vnc_disconnect_start(vs);
134204d2529dSDaniel P. Berrange         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1343ad6374c4SDaniel P. Berrange             trace_vnc_client_io_error(vs, vs->ioc,
134434ab29c2SVladimir Sementsov-Ogievskiy                                       err ? error_get_pretty(err) : "Unknown");
1345537848eeSMichael Tokarev             vnc_disconnect_start(vs);
13463e230dd2SCorentin Chary         }
13473e230dd2SCorentin Chary 
134834ab29c2SVladimir Sementsov-Ogievskiy         error_free(err);
13493e230dd2SCorentin Chary         return 0;
13503e230dd2SCorentin Chary     }
13513e230dd2SCorentin Chary     return ret;
13523e230dd2SCorentin Chary }
13533e230dd2SCorentin Chary 
13543e230dd2SCorentin Chary 
13553e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
13563e230dd2SCorentin Chary {
13573e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
13583e230dd2SCorentin Chary     vnc_disconnect_start(vs);
13593e230dd2SCorentin Chary }
13603e230dd2SCorentin Chary 
13613e305e4aSDaniel P. Berrange 
13623e230dd2SCorentin Chary /*
13633e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
13643e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
13653e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
13663e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
13673e230dd2SCorentin Chary  *
13683e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
13693e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
13703e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
13713e230dd2SCorentin Chary  * is active
13723e230dd2SCorentin Chary  *
13733e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13743e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
137530b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
13763e230dd2SCorentin Chary  */
137730b80fd5SDaniel P. Berrange size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
13783e230dd2SCorentin Chary {
137904d2529dSDaniel P. Berrange     Error *err = NULL;
1380fdd1ab6aSDaniel P. Berrange     ssize_t ret;
138134ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
13823e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
138334ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
13843e230dd2SCorentin Chary }
13853e230dd2SCorentin Chary 
13863e230dd2SCorentin Chary 
13873e230dd2SCorentin Chary /*
13883e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
13893e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
13903e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
13913e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
13923e230dd2SCorentin Chary  *
13933e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13943e230dd2SCorentin Chary  * the buffered output data if the socket would block.  Returns
139530b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
13963e230dd2SCorentin Chary  */
139730b80fd5SDaniel P. Berrange static size_t vnc_client_write_plain(VncState *vs)
13983e230dd2SCorentin Chary {
13996aa22a29SDaniel P. Berrange     size_t offset;
140030b80fd5SDaniel P. Berrange     size_t ret;
14013e230dd2SCorentin Chary 
14023e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14033e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
14043e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
14053e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
14063e230dd2SCorentin Chary 
14073e230dd2SCorentin Chary     if (vs->sasl.conn &&
14083e230dd2SCorentin Chary         vs->sasl.runSSF &&
14093e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
14103e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
14113e230dd2SCorentin Chary         if (ret)
14123e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
14133e230dd2SCorentin Chary     } else
14143e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14153e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
14163e230dd2SCorentin Chary     if (!ret)
14173e230dd2SCorentin Chary         return 0;
14183e230dd2SCorentin Chary 
1419ada8d2e4SDaniel P. Berrange     if (ret >= vs->force_update_offset) {
14206aa22a29SDaniel P. Berrange         if (vs->force_update_offset != 0) {
14216aa22a29SDaniel P. Berrange             trace_vnc_client_unthrottle_forced(vs, vs->ioc);
14226aa22a29SDaniel P. Berrange         }
1423ada8d2e4SDaniel P. Berrange         vs->force_update_offset = 0;
1424ada8d2e4SDaniel P. Berrange     } else {
1425ada8d2e4SDaniel P. Berrange         vs->force_update_offset -= ret;
1426ada8d2e4SDaniel P. Berrange     }
14276aa22a29SDaniel P. Berrange     offset = vs->output.offset;
142832ed2680STim Hardeck     buffer_advance(&vs->output, ret);
14296aa22a29SDaniel P. Berrange     if (offset >= vs->throttle_output_offset &&
14306aa22a29SDaniel P. Berrange         vs->output.offset < vs->throttle_output_offset) {
14316aa22a29SDaniel P. Berrange         trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
14326aa22a29SDaniel P. Berrange     }
14333e230dd2SCorentin Chary 
14343e230dd2SCorentin Chary     if (vs->output.offset == 0) {
143504d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
143604d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
143704d2529dSDaniel P. Berrange         }
143804d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
14392ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
14402ddafce7SDing Hui             vnc_client_io, vs, NULL);
14413e230dd2SCorentin Chary     }
14423e230dd2SCorentin Chary 
14433e230dd2SCorentin Chary     return ret;
14443e230dd2SCorentin Chary }
14453e230dd2SCorentin Chary 
14463e230dd2SCorentin Chary 
14473e230dd2SCorentin Chary /*
14483e230dd2SCorentin Chary  * First function called whenever there is data to be written to
14493e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
14503e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
14513e230dd2SCorentin Chary  */
145204d2529dSDaniel P. Berrange static void vnc_client_write_locked(VncState *vs)
14533e230dd2SCorentin Chary {
14543e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14553e230dd2SCorentin Chary     if (vs->sasl.conn &&
14563e230dd2SCorentin Chary         vs->sasl.runSSF &&
14573e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
14583e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
14593e230dd2SCorentin Chary     } else
14603e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14617536ee4bSTim Hardeck     {
14623e230dd2SCorentin Chary         vnc_client_write_plain(vs);
14633e230dd2SCorentin Chary     }
14647536ee4bSTim Hardeck }
14653e230dd2SCorentin Chary 
146604d2529dSDaniel P. Berrange static void vnc_client_write(VncState *vs)
1467bd023f95SCorentin Chary {
1468f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1469bd023f95SCorentin Chary     vnc_lock_output(vs);
1470d5f04223SDaniel P. Berrange     if (vs->output.offset) {
147104d2529dSDaniel P. Berrange         vnc_client_write_locked(vs);
147204d2529dSDaniel P. Berrange     } else if (vs->ioc != NULL) {
147304d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
147404d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
147504d2529dSDaniel P. Berrange         }
147604d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
14772ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
14782ddafce7SDing Hui             vnc_client_io, vs, NULL);
1479bd023f95SCorentin Chary     }
1480bd023f95SCorentin Chary     vnc_unlock_output(vs);
1481bd023f95SCorentin Chary }
1482bd023f95SCorentin Chary 
14833e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
14843e230dd2SCorentin Chary {
14853e230dd2SCorentin Chary     vs->read_handler = func;
14863e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
14873e230dd2SCorentin Chary }
14883e230dd2SCorentin Chary 
14893e230dd2SCorentin Chary 
14903e230dd2SCorentin Chary /*
14913e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
14923e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
14933e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
14943e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
14953e230dd2SCorentin Chary  *
14963e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
14973e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
14983e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
14993e230dd2SCorentin Chary  * is active
15003e230dd2SCorentin Chary  *
15013e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
15023e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
150330b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15043e230dd2SCorentin Chary  */
150530b80fd5SDaniel P. Berrange size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
15063e230dd2SCorentin Chary {
1507fdd1ab6aSDaniel P. Berrange     ssize_t ret;
150804d2529dSDaniel P. Berrange     Error *err = NULL;
150934ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
15103e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
151134ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
15123e230dd2SCorentin Chary }
15133e230dd2SCorentin Chary 
15143e230dd2SCorentin Chary 
15153e230dd2SCorentin Chary /*
15163e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
15173e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
15183e230dd2SCorentin Chary  * data as possible without blocking.
15193e230dd2SCorentin Chary  *
152030b80fd5SDaniel P. Berrange  * Returns the number of bytes read, which may be less than
152130b80fd5SDaniel P. Berrange  * the requested 'datalen' if the socket would block. Returns
152230b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15233e230dd2SCorentin Chary  */
152430b80fd5SDaniel P. Berrange static size_t vnc_client_read_plain(VncState *vs)
15253e230dd2SCorentin Chary {
152630b80fd5SDaniel P. Berrange     size_t ret;
15273e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
15283e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
15293e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
15303e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
15313e230dd2SCorentin Chary     if (!ret)
15323e230dd2SCorentin Chary         return 0;
15333e230dd2SCorentin Chary     vs->input.offset += ret;
15343e230dd2SCorentin Chary     return ret;
15353e230dd2SCorentin Chary }
15363e230dd2SCorentin Chary 
1537175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1538175b2a6eSCorentin Chary {
1539175b2a6eSCorentin Chary     VncState *vs = opaque;
1540175b2a6eSCorentin Chary 
1541f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1542175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1543175b2a6eSCorentin Chary }
15443e230dd2SCorentin Chary 
15453e230dd2SCorentin Chary /*
15463e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
15473e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
15483e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
1549ea697449SDaniel P. Berrange  * Returns 0 on success, -1 if client disconnected
15503e230dd2SCorentin Chary  */
1551ea697449SDaniel P. Berrange static int vnc_client_read(VncState *vs)
15523e230dd2SCorentin Chary {
155330b80fd5SDaniel P. Berrange     size_t ret;
15543e230dd2SCorentin Chary 
15553e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
15563e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
15573e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
15583e230dd2SCorentin Chary     else
15593e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
15603e230dd2SCorentin Chary         ret = vnc_client_read_plain(vs);
15613e230dd2SCorentin Chary     if (!ret) {
156204d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15633e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1564ea697449SDaniel P. Berrange             return -1;
156504d2529dSDaniel P. Berrange         }
1566ea697449SDaniel P. Berrange         return 0;
15673e230dd2SCorentin Chary     }
15683e230dd2SCorentin Chary 
15693e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
15703e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
15713e230dd2SCorentin Chary         int ret;
15723e230dd2SCorentin Chary 
15733e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
157404d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15753e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1576ea697449SDaniel P. Berrange             return -1;
15773e230dd2SCorentin Chary         }
15783e230dd2SCorentin Chary 
15793e230dd2SCorentin Chary         if (!ret) {
158032ed2680STim Hardeck             buffer_advance(&vs->input, len);
15813e230dd2SCorentin Chary         } else {
15823e230dd2SCorentin Chary             vs->read_handler_expect = ret;
15833e230dd2SCorentin Chary         }
15843e230dd2SCorentin Chary     }
1585ea697449SDaniel P. Berrange     return 0;
15863e230dd2SCorentin Chary }
15873e230dd2SCorentin Chary 
158804d2529dSDaniel P. Berrange gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
158904d2529dSDaniel P. Berrange                        GIOCondition condition, void *opaque)
159004d2529dSDaniel P. Berrange {
159104d2529dSDaniel P. Berrange     VncState *vs = opaque;
1592f31f9c10SGerd Hoffmann 
1593f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
15942ddafce7SDing Hui 
15952ddafce7SDing Hui     if (condition & (G_IO_HUP | G_IO_ERR)) {
15962ddafce7SDing Hui         vnc_disconnect_start(vs);
15972ddafce7SDing Hui         return TRUE;
15982ddafce7SDing Hui     }
15992ddafce7SDing Hui 
160004d2529dSDaniel P. Berrange     if (condition & G_IO_IN) {
1601ea697449SDaniel P. Berrange         if (vnc_client_read(vs) < 0) {
16021bc3117aSGerd Hoffmann             /* vs is free()ed here */
16031bc3117aSGerd Hoffmann             return TRUE;
1604ea697449SDaniel P. Berrange         }
160504d2529dSDaniel P. Berrange     }
160604d2529dSDaniel P. Berrange     if (condition & G_IO_OUT) {
160704d2529dSDaniel P. Berrange         vnc_client_write(vs);
160804d2529dSDaniel P. Berrange     }
16091bc3117aSGerd Hoffmann 
1610d49b87f0SKlim Kireev     if (vs->disconnecting) {
1611d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1612d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1613d49b87f0SKlim Kireev         }
1614d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1615d49b87f0SKlim Kireev     }
161604d2529dSDaniel P. Berrange     return TRUE;
161704d2529dSDaniel P. Berrange }
161804d2529dSDaniel P. Berrange 
161904d2529dSDaniel P. Berrange 
1620f887cf16SDaniel P. Berrange /*
1621f887cf16SDaniel P. Berrange  * Scale factor to apply to vs->throttle_output_offset when checking for
1622f887cf16SDaniel P. Berrange  * hard limit. Worst case normal usage could be x2, if we have a complete
1623f887cf16SDaniel P. Berrange  * incremental update and complete forced update in the output buffer.
1624f887cf16SDaniel P. Berrange  * So x3 should be good enough, but we pick x5 to be conservative and thus
1625f887cf16SDaniel P. Berrange  * (hopefully) never trigger incorrectly.
1626f887cf16SDaniel P. Berrange  */
1627f887cf16SDaniel P. Berrange #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1628f887cf16SDaniel P. Berrange 
16293e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
16303e230dd2SCorentin Chary {
1631f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1632f887cf16SDaniel P. Berrange     if (vs->disconnecting) {
1633f887cf16SDaniel P. Berrange         return;
1634f887cf16SDaniel P. Berrange     }
1635f887cf16SDaniel P. Berrange     /* Protection against malicious client/guest to prevent our output
1636f887cf16SDaniel P. Berrange      * buffer growing without bound if client stops reading data. This
1637f887cf16SDaniel P. Berrange      * should rarely trigger, because we have earlier throttling code
1638f887cf16SDaniel P. Berrange      * which stops issuing framebuffer updates and drops audio data
1639f887cf16SDaniel P. Berrange      * if the throttle_output_offset value is exceeded. So we only reach
1640f887cf16SDaniel P. Berrange      * this higher level if a huge number of pseudo-encodings get
1641f887cf16SDaniel P. Berrange      * triggered while data can't be sent on the socket.
1642f887cf16SDaniel P. Berrange      *
1643f887cf16SDaniel P. Berrange      * NB throttle_output_offset can be zero during early protocol
1644f887cf16SDaniel P. Berrange      * handshake, or from the job thread's VncState clone
1645f887cf16SDaniel P. Berrange      */
1646f887cf16SDaniel P. Berrange     if (vs->throttle_output_offset != 0 &&
1647dffa1de0SDaniel P. Berrangé         (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1648dffa1de0SDaniel P. Berrangé         vs->throttle_output_offset) {
16496aa22a29SDaniel P. Berrange         trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
16506aa22a29SDaniel P. Berrange                                       vs->throttle_output_offset);
1651f887cf16SDaniel P. Berrange         vnc_disconnect_start(vs);
1652f887cf16SDaniel P. Berrange         return;
1653f887cf16SDaniel P. Berrange     }
16543e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
16553e230dd2SCorentin Chary 
165604d2529dSDaniel P. Berrange     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
165704d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
165804d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
165904d2529dSDaniel P. Berrange         }
166004d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
16612ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
16622ddafce7SDing Hui             vnc_client_io, vs, NULL);
16633e230dd2SCorentin Chary     }
16643e230dd2SCorentin Chary 
16653e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
16663e230dd2SCorentin Chary }
16673e230dd2SCorentin Chary 
16683e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
16693e230dd2SCorentin Chary {
16703e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
16713e230dd2SCorentin Chary }
16723e230dd2SCorentin Chary 
16733e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
16743e230dd2SCorentin Chary {
16753e230dd2SCorentin Chary     uint8_t buf[4];
16763e230dd2SCorentin Chary 
16773e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
16783e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
16793e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
16803e230dd2SCorentin Chary     buf[3] = value & 0xFF;
16813e230dd2SCorentin Chary 
16823e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
16833e230dd2SCorentin Chary }
16843e230dd2SCorentin Chary 
16853e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
16863e230dd2SCorentin Chary {
16873e230dd2SCorentin Chary     uint8_t buf[2];
16883e230dd2SCorentin Chary 
16893e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
16903e230dd2SCorentin Chary     buf[1] = value & 0xFF;
16913e230dd2SCorentin Chary 
16923e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
16933e230dd2SCorentin Chary }
16943e230dd2SCorentin Chary 
16953e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
16963e230dd2SCorentin Chary {
16973e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
16983e230dd2SCorentin Chary }
16993e230dd2SCorentin Chary 
17003e230dd2SCorentin Chary void vnc_flush(VncState *vs)
17013e230dd2SCorentin Chary {
1702bd023f95SCorentin Chary     vnc_lock_output(vs);
1703d5f04223SDaniel P. Berrange     if (vs->ioc != NULL && vs->output.offset) {
1704bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1705bd023f95SCorentin Chary     }
1706d49b87f0SKlim Kireev     if (vs->disconnecting) {
1707d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1708d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1709d49b87f0SKlim Kireev         }
1710d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1711d49b87f0SKlim Kireev     }
1712bd023f95SCorentin Chary     vnc_unlock_output(vs);
17133e230dd2SCorentin Chary }
17143e230dd2SCorentin Chary 
171571a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
17163e230dd2SCorentin Chary {
17173e230dd2SCorentin Chary     return data[offset];
17183e230dd2SCorentin Chary }
17193e230dd2SCorentin Chary 
172071a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
17213e230dd2SCorentin Chary {
17223e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
17233e230dd2SCorentin Chary }
17243e230dd2SCorentin Chary 
172571a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
17263e230dd2SCorentin Chary {
17273e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
17283e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
17293e230dd2SCorentin Chary }
17303e230dd2SCorentin Chary 
17313e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
17323e230dd2SCorentin Chary {
17333e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
17343e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
17353e230dd2SCorentin Chary }
17363e230dd2SCorentin Chary 
17373e230dd2SCorentin Chary static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
17383e230dd2SCorentin Chary {
17393e230dd2SCorentin Chary }
17403e230dd2SCorentin Chary 
17419e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
17423e230dd2SCorentin Chary {
17433e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
174414768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
17453e230dd2SCorentin Chary 
17463e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1747bd023f95SCorentin Chary         vnc_lock_output(vs);
17483e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
17493e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
17503e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
17513e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1752bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1753bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
17543e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1755bd023f95SCorentin Chary         vnc_unlock_output(vs);
17563e230dd2SCorentin Chary         vnc_flush(vs);
17573e230dd2SCorentin Chary     }
17583e230dd2SCorentin Chary     vs->absolute = absolute;
17593e230dd2SCorentin Chary }
17603e230dd2SCorentin Chary 
17613e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
17623e230dd2SCorentin Chary {
17637fb1cf16SEric Blake     static uint32_t bmap[INPUT_BUTTON__MAX] = {
176414768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
176514768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
176614768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
1767f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1768f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
176914768ebaSGerd Hoffmann     };
177014768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1771bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1772bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
17733e230dd2SCorentin Chary 
177414768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
177514768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
177614768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
177714768ebaSGerd Hoffmann     }
17783e230dd2SCorentin Chary 
17793e230dd2SCorentin Chary     if (vs->absolute) {
17809cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
17819cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
17823e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
178314768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
178414768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
17853e230dd2SCorentin Chary     } else {
178614768ebaSGerd Hoffmann         if (vs->last_x != -1) {
178714768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
178814768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
178914768ebaSGerd Hoffmann         }
17903e230dd2SCorentin Chary         vs->last_x = x;
17913e230dd2SCorentin Chary         vs->last_y = y;
17923e230dd2SCorentin Chary     }
179314768ebaSGerd Hoffmann     qemu_input_event_sync();
17943e230dd2SCorentin Chary }
17953e230dd2SCorentin Chary 
1796c2f2ba49SGerd Hoffmann static void press_key(VncState *vs, QKeyCode qcode)
17973e230dd2SCorentin Chary {
1798c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, true);
1799c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, false);
18003e230dd2SCorentin Chary }
18013e230dd2SCorentin Chary 
1802ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1803ab99e5c1SLei Li {
1804ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1805ab99e5c1SLei Li         return;
1806ab99e5c1SLei Li     }
1807ab99e5c1SLei Li 
1808ab99e5c1SLei Li     vnc_lock_output(vs);
1809ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1810ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1811ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1812ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1813a54f0d2bSPierre Ossman     vnc_write_u8(vs, vs->vd->ledstate);
1814ab99e5c1SLei Li     vnc_unlock_output(vs);
1815ab99e5c1SLei Li     vnc_flush(vs);
1816ab99e5c1SLei Li }
1817ab99e5c1SLei Li 
18183e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
18193e230dd2SCorentin Chary {
1820a54f0d2bSPierre Ossman     VncDisplay *vd = opaque;
1821a54f0d2bSPierre Ossman     VncState *client;
18223e230dd2SCorentin Chary 
182340066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
182440066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
182540066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
182640066175SGerd Hoffmann 
1827a54f0d2bSPierre Ossman     if (ledstate == vd->ledstate) {
1828a54f0d2bSPierre Ossman         return;
182996f3d174SLei Li     }
1830ab99e5c1SLei Li 
1831a54f0d2bSPierre Ossman     vd->ledstate = ledstate;
1832a54f0d2bSPierre Ossman 
1833a54f0d2bSPierre Ossman     QTAILQ_FOREACH(client, &vd->clients, next) {
1834a54f0d2bSPierre Ossman         vnc_led_state_change(client);
1835ab99e5c1SLei Li     }
18363e230dd2SCorentin Chary }
18373e230dd2SCorentin Chary 
18383e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
18393e230dd2SCorentin Chary {
1840c2f2ba49SGerd Hoffmann     QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1841c2f2ba49SGerd Hoffmann 
18423e230dd2SCorentin Chary     /* QEMU console switch */
1843c2f2ba49SGerd Hoffmann     switch (qcode) {
1844c2f2ba49SGerd Hoffmann     case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1845c2f2ba49SGerd Hoffmann         if (vs->vd->dcl.con == NULL && down &&
1846c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1847c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
18483e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
1849c2f2ba49SGerd Hoffmann             qkbd_state_lift_all_keys(vs->vd->kbd);
1850c2f2ba49SGerd Hoffmann             console_select(qcode - Q_KEY_CODE_1);
18513e230dd2SCorentin Chary             return;
18523e230dd2SCorentin Chary         }
1853c2f2ba49SGerd Hoffmann     default:
18543e230dd2SCorentin Chary         break;
18553e230dd2SCorentin Chary     }
18563e230dd2SCorentin Chary 
1857e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1858e7b2aaccSLei Li        state extension.
1859e7b2aaccSLei Li     */
18609892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1861e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18623e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
18633e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
18643e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18653e230dd2SCorentin Chary            toggles numlock away from the VNC window.
18663e230dd2SCorentin Chary         */
18673e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1868c2f2ba49SGerd Hoffmann             if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
186940066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
1870c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
18713e230dd2SCorentin Chary             }
18723e230dd2SCorentin Chary         } else {
1873c2f2ba49SGerd Hoffmann             if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
187440066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
1875c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
18763e230dd2SCorentin Chary             }
18773e230dd2SCorentin Chary         }
18783e230dd2SCorentin Chary     }
18793e230dd2SCorentin Chary 
18809892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1881e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18823e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
18833e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
18843e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18853e230dd2SCorentin Chary            toggles capslock away from the VNC window.
18863e230dd2SCorentin Chary         */
18873e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1888c2f2ba49SGerd Hoffmann         bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1889c2f2ba49SGerd Hoffmann         bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
18903e230dd2SCorentin Chary         if (capslock) {
18913e230dd2SCorentin Chary             if (uppercase == shift) {
189240066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
1893c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
18943e230dd2SCorentin Chary             }
18953e230dd2SCorentin Chary         } else {
18963e230dd2SCorentin Chary             if (uppercase != shift) {
189740066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
1898c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
18993e230dd2SCorentin Chary             }
19003e230dd2SCorentin Chary         }
19013e230dd2SCorentin Chary     }
19023e230dd2SCorentin Chary 
1903c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, down);
1904c2f2ba49SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
1905c2f2ba49SGerd Hoffmann         bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1906c2f2ba49SGerd Hoffmann         bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
19073e230dd2SCorentin Chary         /* QEMU console emulation */
19083e230dd2SCorentin Chary         if (down) {
19093e230dd2SCorentin Chary             switch (keycode) {
19103e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
19113e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
19123e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
19133e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
19143e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
19153e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
19163e230dd2SCorentin Chary                 break;
19173e230dd2SCorentin Chary             case 0xc8:
19183e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_UP);
19193e230dd2SCorentin Chary                 break;
19203e230dd2SCorentin Chary             case 0xd0:
19213e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DOWN);
19223e230dd2SCorentin Chary                 break;
19233e230dd2SCorentin Chary             case 0xcb:
19243e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_LEFT);
19253e230dd2SCorentin Chary                 break;
19263e230dd2SCorentin Chary             case 0xcd:
19273e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_RIGHT);
19283e230dd2SCorentin Chary                 break;
19293e230dd2SCorentin Chary             case 0xd3:
19303e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DELETE);
19313e230dd2SCorentin Chary                 break;
19323e230dd2SCorentin Chary             case 0xc7:
19333e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_HOME);
19343e230dd2SCorentin Chary                 break;
19353e230dd2SCorentin Chary             case 0xcf:
19363e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_END);
19373e230dd2SCorentin Chary                 break;
19383e230dd2SCorentin Chary             case 0xc9:
19393e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEUP);
19403e230dd2SCorentin Chary                 break;
19413e230dd2SCorentin Chary             case 0xd1:
19423e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
19433e230dd2SCorentin Chary                 break;
19443e230dd2SCorentin Chary 
19453e230dd2SCorentin Chary             case 0x47:
19463e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
19473e230dd2SCorentin Chary                 break;
19483e230dd2SCorentin Chary             case 0x48:
19493e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
19503e230dd2SCorentin Chary                 break;
19513e230dd2SCorentin Chary             case 0x49:
19523e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
19533e230dd2SCorentin Chary                 break;
19543e230dd2SCorentin Chary             case 0x4b:
19553e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
19563e230dd2SCorentin Chary                 break;
19573e230dd2SCorentin Chary             case 0x4c:
19583e230dd2SCorentin Chary                 kbd_put_keysym('5');
19593e230dd2SCorentin Chary                 break;
19603e230dd2SCorentin Chary             case 0x4d:
19613e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
19623e230dd2SCorentin Chary                 break;
19633e230dd2SCorentin Chary             case 0x4f:
19643e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
19653e230dd2SCorentin Chary                 break;
19663e230dd2SCorentin Chary             case 0x50:
19673e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
19683e230dd2SCorentin Chary                 break;
19693e230dd2SCorentin Chary             case 0x51:
19703e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
19713e230dd2SCorentin Chary                 break;
19723e230dd2SCorentin Chary             case 0x52:
19733e230dd2SCorentin Chary                 kbd_put_keysym('0');
19743e230dd2SCorentin Chary                 break;
19753e230dd2SCorentin Chary             case 0x53:
19763e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
19773e230dd2SCorentin Chary                 break;
19783e230dd2SCorentin Chary 
19793e230dd2SCorentin Chary             case 0xb5:
19803e230dd2SCorentin Chary                 kbd_put_keysym('/');
19813e230dd2SCorentin Chary                 break;
19823e230dd2SCorentin Chary             case 0x37:
19833e230dd2SCorentin Chary                 kbd_put_keysym('*');
19843e230dd2SCorentin Chary                 break;
19853e230dd2SCorentin Chary             case 0x4a:
19863e230dd2SCorentin Chary                 kbd_put_keysym('-');
19873e230dd2SCorentin Chary                 break;
19883e230dd2SCorentin Chary             case 0x4e:
19893e230dd2SCorentin Chary                 kbd_put_keysym('+');
19903e230dd2SCorentin Chary                 break;
19913e230dd2SCorentin Chary             case 0x9c:
19923e230dd2SCorentin Chary                 kbd_put_keysym('\n');
19933e230dd2SCorentin Chary                 break;
19943e230dd2SCorentin Chary 
19953e230dd2SCorentin Chary             default:
1996e26437c2SGerd Hoffmann                 if (control) {
1997e26437c2SGerd Hoffmann                     kbd_put_keysym(sym & 0x1f);
1998e26437c2SGerd Hoffmann                 } else {
19993e230dd2SCorentin Chary                     kbd_put_keysym(sym);
2000e26437c2SGerd Hoffmann                 }
20013e230dd2SCorentin Chary                 break;
20023e230dd2SCorentin Chary             }
20033e230dd2SCorentin Chary         }
20043e230dd2SCorentin Chary     }
20053e230dd2SCorentin Chary }
20063e230dd2SCorentin Chary 
200740066175SGerd Hoffmann static const char *code2name(int keycode)
200840066175SGerd Hoffmann {
2009977c736fSMarkus Armbruster     return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
201040066175SGerd Hoffmann }
201140066175SGerd Hoffmann 
20123e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
20133e230dd2SCorentin Chary {
20143e230dd2SCorentin Chary     int keycode;
20153e230dd2SCorentin Chary     int lsym = sym;
20163e230dd2SCorentin Chary 
201781c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
20183e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
20193e230dd2SCorentin Chary     }
20203e230dd2SCorentin Chary 
2021abb4f2c9SGerd Hoffmann     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
202219c1b9fdSGerd Hoffmann                               vs->vd->kbd, down) & SCANCODE_KEYMASK;
202340066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
20243e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
20253e230dd2SCorentin Chary }
20263e230dd2SCorentin Chary 
20273e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
20283e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
20293e230dd2SCorentin Chary {
20303e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
203140066175SGerd Hoffmann     if (keyboard_layout) {
20323e230dd2SCorentin Chary         key_event(vs, down, sym);
203340066175SGerd Hoffmann     } else {
203440066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
20353e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
20363e230dd2SCorentin Chary     }
203740066175SGerd Hoffmann }
20383e230dd2SCorentin Chary 
20393e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
2040bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
20413e230dd2SCorentin Chary {
2042bea60dd7SPeter Lieven     if (incremental) {
2043fef1bbadSDaniel P. Berrange         if (vs->update != VNC_STATE_UPDATE_FORCE) {
2044fef1bbadSDaniel P. Berrange             vs->update = VNC_STATE_UPDATE_INCREMENTAL;
20453e230dd2SCorentin Chary         }
2046fef1bbadSDaniel P. Berrange     } else {
2047fef1bbadSDaniel P. Berrange         vs->update = VNC_STATE_UPDATE_FORCE;
2048f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
20493e230dd2SCorentin Chary     }
2050fef1bbadSDaniel P. Berrange }
20513e230dd2SCorentin Chary 
20523e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
20533e230dd2SCorentin Chary {
2054bd023f95SCorentin Chary     vnc_lock_output(vs);
20553e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20563e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20573e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2058d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2059bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2060bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20613e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
2062bd023f95SCorentin Chary     vnc_unlock_output(vs);
20633e230dd2SCorentin Chary     vnc_flush(vs);
20643e230dd2SCorentin Chary }
20653e230dd2SCorentin Chary 
20663e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
20673e230dd2SCorentin Chary {
2068bd023f95SCorentin Chary     vnc_lock_output(vs);
20693e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20703e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20713e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2072d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2073bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2074bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20753e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2076bd023f95SCorentin Chary     vnc_unlock_output(vs);
20773e230dd2SCorentin Chary     vnc_flush(vs);
20783e230dd2SCorentin Chary }
20793e230dd2SCorentin Chary 
20807b5fa0b5SDaniel P. Berrangé static void send_xvp_message(VncState *vs, int code)
20817b5fa0b5SDaniel P. Berrangé {
20827b5fa0b5SDaniel P. Berrangé     vnc_lock_output(vs);
20837b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
20847b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 0); /* pad */
20857b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 1); /* version */
20867b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, code);
20877b5fa0b5SDaniel P. Berrangé     vnc_unlock_output(vs);
20887b5fa0b5SDaniel P. Berrangé     vnc_flush(vs);
20897b5fa0b5SDaniel P. Berrangé }
20907b5fa0b5SDaniel P. Berrangé 
20913e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
20923e230dd2SCorentin Chary {
20933e230dd2SCorentin Chary     int i;
20943e230dd2SCorentin Chary     unsigned int enc = 0;
20953e230dd2SCorentin Chary 
20963e230dd2SCorentin Chary     vs->features = 0;
20973e230dd2SCorentin Chary     vs->vnc_encoding = 0;
20986bf21f3dSLi Qiang     vs->tight->compression = 9;
20996bf21f3dSLi Qiang     vs->tight->quality = -1; /* Lossless by default */
21003e230dd2SCorentin Chary     vs->absolute = -1;
21013e230dd2SCorentin Chary 
21023e230dd2SCorentin Chary     /*
21033e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2104e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
21053e230dd2SCorentin Chary      * will be set at the end of the loop.
21063e230dd2SCorentin Chary      */
21073e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
21083e230dd2SCorentin Chary         enc = encodings[i];
21093e230dd2SCorentin Chary         switch (enc) {
21103e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
21113e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21123e230dd2SCorentin Chary             break;
21133e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
21143e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
21153e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21163e230dd2SCorentin Chary             break;
21173e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
21183e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
21193e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21203e230dd2SCorentin Chary             break;
2121fe3e7f2dSJoel Martin #ifdef CONFIG_VNC_PNG
2122efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2123efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2124efe556adSCorentin Chary             vs->vnc_encoding = enc;
2125efe556adSCorentin Chary             break;
2126fe3e7f2dSJoel Martin #endif
21273e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
2128557ba0e5SCameron Esfahani             /*
2129557ba0e5SCameron Esfahani              * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2130557ba0e5SCameron Esfahani              * So prioritize ZRLE, even if the client hints that it prefers
2131557ba0e5SCameron Esfahani              * ZLIB.
2132557ba0e5SCameron Esfahani              */
2133557ba0e5SCameron Esfahani             if ((vs->features & VNC_FEATURE_ZRLE_MASK) == 0) {
21343e230dd2SCorentin Chary                 vs->features |= VNC_FEATURE_ZLIB_MASK;
21353e230dd2SCorentin Chary                 vs->vnc_encoding = enc;
2136557ba0e5SCameron Esfahani             }
21373e230dd2SCorentin Chary             break;
2138148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2139148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2140148954faSCorentin Chary             vs->vnc_encoding = enc;
2141148954faSCorentin Chary             break;
2142148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2143148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2144148954faSCorentin Chary             vs->vnc_encoding = enc;
2145148954faSCorentin Chary             break;
21463e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
21473e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
21483e230dd2SCorentin Chary             break;
2149763deea7SGerd Hoffmann         case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2150763deea7SGerd Hoffmann             vs->features |= VNC_FEATURE_RESIZE_EXT_MASK;
2151763deea7SGerd Hoffmann             break;
21523e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
21533e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
21543e230dd2SCorentin Chary             break;
21553e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
21563e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2157074a86d0SGerd Hoffmann             break;
2158074a86d0SGerd Hoffmann         case VNC_ENCODING_ALPHA_CURSOR:
2159074a86d0SGerd Hoffmann             vs->features |= VNC_FEATURE_ALPHA_CURSOR_MASK;
21603e230dd2SCorentin Chary             break;
21613e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
21623e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
21633e230dd2SCorentin Chary             break;
21643e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
21653e230dd2SCorentin Chary             send_ext_audio_ack(vs);
21663e230dd2SCorentin Chary             break;
21673e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
21683e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
21693e230dd2SCorentin Chary             break;
2170ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2171ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2172ab99e5c1SLei Li             break;
21737b5fa0b5SDaniel P. Berrangé         case VNC_ENCODING_XVP:
21747b5fa0b5SDaniel P. Berrangé             if (vs->vd->power_control) {
21757b5fa0b5SDaniel P. Berrangé                 vs->features |= VNC_FEATURE_XVP;
21767b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_INIT);
21777b5fa0b5SDaniel P. Berrangé             }
21787b5fa0b5SDaniel P. Berrangé             break;
21793e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
21806bf21f3dSLi Qiang             vs->tight->compression = (enc & 0x0F);
21813e230dd2SCorentin Chary             break;
21823e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2183b31f519eSCorentin Chary             if (vs->vd->lossy) {
21846bf21f3dSLi Qiang                 vs->tight->quality = (enc & 0x0F);
2185b31f519eSCorentin Chary             }
21863e230dd2SCorentin Chary             break;
21873e230dd2SCorentin Chary         default:
21883e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
21893e230dd2SCorentin Chary             break;
21903e230dd2SCorentin Chary         }
21913e230dd2SCorentin Chary     }
2192*d239726cSGerd Hoffmann     vnc_desktop_resize(vs);
21939e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2194*d239726cSGerd Hoffmann     vnc_led_state_change(vs);
2195*d239726cSGerd Hoffmann     vnc_cursor_define(vs);
2196074a86d0SGerd Hoffmann }
21973e230dd2SCorentin Chary 
21983e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
21993e230dd2SCorentin Chary {
22009f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
22019f64916dSGerd Hoffmann 
22029f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
22033e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
22043e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
22053e230dd2SCorentin Chary     } else {
22063e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
22073e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
22083e230dd2SCorentin Chary     }
22093e230dd2SCorentin Chary }
22103e230dd2SCorentin Chary 
22110c426e45SAlexander Graf static void send_color_map(VncState *vs)
22120c426e45SAlexander Graf {
22130c426e45SAlexander Graf     int i;
22140c426e45SAlexander Graf 
2215947191b4SPeng Liang     vnc_lock_output(vs);
22160c426e45SAlexander Graf     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
22170c426e45SAlexander Graf     vnc_write_u8(vs,  0);    /* padding     */
22180c426e45SAlexander Graf     vnc_write_u16(vs, 0);    /* first color */
22190c426e45SAlexander Graf     vnc_write_u16(vs, 256);  /* # of colors */
22200c426e45SAlexander Graf 
22210c426e45SAlexander Graf     for (i = 0; i < 256; i++) {
22220c426e45SAlexander Graf         PixelFormat *pf = &vs->client_pf;
22230c426e45SAlexander Graf 
22240c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
22250c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
22260c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
22270c426e45SAlexander Graf     }
2228947191b4SPeng Liang     vnc_unlock_output(vs);
22290c426e45SAlexander Graf }
22300c426e45SAlexander Graf 
2231ec9fb41aSGerd Hoffmann static void set_pixel_format(VncState *vs, int bits_per_pixel,
22323e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
22333e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
22343e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
22353e230dd2SCorentin Chary {
22363e230dd2SCorentin Chary     if (!true_color_flag) {
22370c426e45SAlexander Graf         /* Expose a reasonable default 256 color map */
22380c426e45SAlexander Graf         bits_per_pixel = 8;
22390c426e45SAlexander Graf         red_max = 7;
22400c426e45SAlexander Graf         green_max = 7;
22410c426e45SAlexander Graf         blue_max = 3;
22420c426e45SAlexander Graf         red_shift = 0;
22430c426e45SAlexander Graf         green_shift = 3;
22440c426e45SAlexander Graf         blue_shift = 6;
22453e230dd2SCorentin Chary     }
22463e230dd2SCorentin Chary 
2247e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2248e6908bfeSPetr Matousek     case 8:
2249e6908bfeSPetr Matousek     case 16:
2250e6908bfeSPetr Matousek     case 32:
2251e6908bfeSPetr Matousek         break;
2252e6908bfeSPetr Matousek     default:
2253e6908bfeSPetr Matousek         vnc_client_error(vs);
2254e6908bfeSPetr Matousek         return;
2255e6908bfeSPetr Matousek     }
2256e6908bfeSPetr Matousek 
22574c65fed8SPrasad J Pandit     vs->client_pf.rmax = red_max ? red_max : 0xFF;
22587c9209e7SCédric Le Goater     vs->client_pf.rbits = ctpopl(red_max);
22599f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
22609f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
22614c65fed8SPrasad J Pandit     vs->client_pf.gmax = green_max ? green_max : 0xFF;
22627c9209e7SCédric Le Goater     vs->client_pf.gbits = ctpopl(green_max);
22639f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
22649f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
22654c65fed8SPrasad J Pandit     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
22667c9209e7SCédric Le Goater     vs->client_pf.bbits = ctpopl(blue_max);
22679f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
22689f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
22699f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
22709f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
22719f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
22729f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
22733e230dd2SCorentin Chary 
22740c426e45SAlexander Graf     if (!true_color_flag) {
22750c426e45SAlexander Graf         send_color_map(vs);
22760c426e45SAlexander Graf     }
22770c426e45SAlexander Graf 
22783e230dd2SCorentin Chary     set_pixel_conversion(vs);
22793e230dd2SCorentin Chary 
22801d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
22811d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
22823e230dd2SCorentin Chary }
22833e230dd2SCorentin Chary 
22843e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
22853e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
22863e230dd2SCorentin Chary 
22879f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
22889f64916dSGerd Hoffmann 
22899f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
22909f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
22913e230dd2SCorentin Chary 
22923e230dd2SCorentin Chary #ifdef HOST_WORDS_BIGENDIAN
22933e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
22943e230dd2SCorentin Chary #else
22953e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
22963e230dd2SCorentin Chary #endif
22973e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
22989f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
22999f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
23009f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
23019f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
23029f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
23039f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
23049f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
23053e230dd2SCorentin Chary 
23063e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
23073e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
23083e230dd2SCorentin Chary }
23093e230dd2SCorentin Chary 
23103e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
23113e230dd2SCorentin Chary {
23123e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
23133e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2314bd023f95SCorentin Chary         vnc_lock_output(vs);
23153e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
23163e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
23173e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2318d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
2319bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
2320bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
2321d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
23223e230dd2SCorentin Chary         pixel_format_message(vs);
2323bd023f95SCorentin Chary         vnc_unlock_output(vs);
23243e230dd2SCorentin Chary         vnc_flush(vs);
23253e230dd2SCorentin Chary     } else {
23263e230dd2SCorentin Chary         set_pixel_conversion(vs);
23273e230dd2SCorentin Chary     }
23283e230dd2SCorentin Chary }
23293e230dd2SCorentin Chary 
23303e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
23313e230dd2SCorentin Chary {
23323e230dd2SCorentin Chary     int i;
23333e230dd2SCorentin Chary     uint16_t limit;
2334cf070658SDaniel P. Berrangé     uint32_t freq;
23353e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
23363e230dd2SCorentin Chary 
23373e230dd2SCorentin Chary     if (data[0] > 3) {
23380f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
23393e230dd2SCorentin Chary     }
23403e230dd2SCorentin Chary 
23413e230dd2SCorentin Chary     switch (data[0]) {
23423e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
23433e230dd2SCorentin Chary         if (len == 1)
23443e230dd2SCorentin Chary             return 20;
23453e230dd2SCorentin Chary 
2346ec9fb41aSGerd Hoffmann         set_pixel_format(vs, read_u8(data, 4),
23473e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
23483e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
23493e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
23503e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
23513e230dd2SCorentin Chary         break;
23523e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
23533e230dd2SCorentin Chary         if (len == 1)
23543e230dd2SCorentin Chary             return 4;
23553e230dd2SCorentin Chary 
23563e230dd2SCorentin Chary         if (len == 4) {
23573e230dd2SCorentin Chary             limit = read_u16(data, 2);
23583e230dd2SCorentin Chary             if (limit > 0)
23593e230dd2SCorentin Chary                 return 4 + (limit * 4);
23603e230dd2SCorentin Chary         } else
23613e230dd2SCorentin Chary             limit = read_u16(data, 2);
23623e230dd2SCorentin Chary 
23633e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
23643e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
23653e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
23663e230dd2SCorentin Chary         }
23673e230dd2SCorentin Chary 
23683e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
23693e230dd2SCorentin Chary         break;
23703e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
23713e230dd2SCorentin Chary         if (len == 1)
23723e230dd2SCorentin Chary             return 10;
23733e230dd2SCorentin Chary 
23743e230dd2SCorentin Chary         framebuffer_update_request(vs,
23753e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
23763e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
23773e230dd2SCorentin Chary         break;
23783e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
23793e230dd2SCorentin Chary         if (len == 1)
23803e230dd2SCorentin Chary             return 8;
23813e230dd2SCorentin Chary 
23823e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
23833e230dd2SCorentin Chary         break;
23843e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
23853e230dd2SCorentin Chary         if (len == 1)
23863e230dd2SCorentin Chary             return 6;
23873e230dd2SCorentin Chary 
23883e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
23893e230dd2SCorentin Chary         break;
23903e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2391f9a70e79SPeter Lieven         if (len == 1) {
23923e230dd2SCorentin Chary             return 8;
2393f9a70e79SPeter Lieven         }
23943e230dd2SCorentin Chary         if (len == 8) {
23953e230dd2SCorentin Chary             uint32_t dlen = read_u32(data, 4);
2396f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2397f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2398f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2399f9a70e79SPeter Lieven                 vnc_client_error(vs);
2400f9a70e79SPeter Lieven                 break;
2401f9a70e79SPeter Lieven             }
2402f9a70e79SPeter Lieven             if (dlen > 0) {
24033e230dd2SCorentin Chary                 return 8 + dlen;
24043e230dd2SCorentin Chary             }
2405f9a70e79SPeter Lieven         }
24063e230dd2SCorentin Chary 
24073e230dd2SCorentin Chary         client_cut_text(vs, read_u32(data, 4), data + 8);
24083e230dd2SCorentin Chary         break;
24097b5fa0b5SDaniel P. Berrangé     case VNC_MSG_CLIENT_XVP:
24107b5fa0b5SDaniel P. Berrangé         if (!(vs->features & VNC_FEATURE_XVP)) {
24117b5fa0b5SDaniel P. Berrangé             error_report("vnc: xvp client message while disabled");
24127b5fa0b5SDaniel P. Berrangé             vnc_client_error(vs);
24137b5fa0b5SDaniel P. Berrangé             break;
24147b5fa0b5SDaniel P. Berrangé         }
24157b5fa0b5SDaniel P. Berrangé         if (len == 1) {
24167b5fa0b5SDaniel P. Berrangé             return 4;
24177b5fa0b5SDaniel P. Berrangé         }
24187b5fa0b5SDaniel P. Berrangé         if (len == 4) {
24197b5fa0b5SDaniel P. Berrangé             uint8_t version = read_u8(data, 2);
24207b5fa0b5SDaniel P. Berrangé             uint8_t action = read_u8(data, 3);
24217b5fa0b5SDaniel P. Berrangé 
24227b5fa0b5SDaniel P. Berrangé             if (version != 1) {
24237b5fa0b5SDaniel P. Berrangé                 error_report("vnc: xvp client message version %d != 1",
24247b5fa0b5SDaniel P. Berrangé                              version);
24257b5fa0b5SDaniel P. Berrangé                 vnc_client_error(vs);
24267b5fa0b5SDaniel P. Berrangé                 break;
24277b5fa0b5SDaniel P. Berrangé             }
24287b5fa0b5SDaniel P. Berrangé 
24297b5fa0b5SDaniel P. Berrangé             switch (action) {
24307b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_SHUTDOWN:
24317b5fa0b5SDaniel P. Berrangé                 qemu_system_powerdown_request();
24327b5fa0b5SDaniel P. Berrangé                 break;
24337b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_REBOOT:
24347b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24357b5fa0b5SDaniel P. Berrangé                 break;
24367b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_RESET:
24377b5fa0b5SDaniel P. Berrangé                 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
24387b5fa0b5SDaniel P. Berrangé                 break;
24397b5fa0b5SDaniel P. Berrangé             default:
24407b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24417b5fa0b5SDaniel P. Berrangé                 break;
24427b5fa0b5SDaniel P. Berrangé             }
24437b5fa0b5SDaniel P. Berrangé         }
24447b5fa0b5SDaniel P. Berrangé         break;
24453e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
24463e230dd2SCorentin Chary         if (len == 1)
24473e230dd2SCorentin Chary             return 2;
24483e230dd2SCorentin Chary 
24493e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
24503e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
24513e230dd2SCorentin Chary             if (len == 2)
24523e230dd2SCorentin Chary                 return 12;
24533e230dd2SCorentin Chary 
24543e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
24553e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
24563e230dd2SCorentin Chary             break;
24573e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
24583e230dd2SCorentin Chary             if (len == 2)
24593e230dd2SCorentin Chary                 return 4;
24603e230dd2SCorentin Chary 
24613e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
24623e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
24633e230dd2SCorentin Chary                 audio_add(vs);
24643e230dd2SCorentin Chary                 break;
24653e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
24663e230dd2SCorentin Chary                 audio_del(vs);
24673e230dd2SCorentin Chary                 break;
24683e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
24693e230dd2SCorentin Chary                 if (len == 4)
24703e230dd2SCorentin Chary                     return 10;
24713e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
247285bc5852SKővágó, Zoltán                 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
247385bc5852SKővágó, Zoltán                 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
247485bc5852SKővágó, Zoltán                 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
247585bc5852SKővágó, Zoltán                 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
247685bc5852SKővágó, Zoltán                 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
247785bc5852SKővágó, Zoltán                 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
24783e230dd2SCorentin Chary                 default:
2479153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
24803e230dd2SCorentin Chary                     vnc_client_error(vs);
24813e230dd2SCorentin Chary                     break;
24823e230dd2SCorentin Chary                 }
24833e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
24843e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2485090fdc83SMarc-André Lureau                     VNC_DEBUG("Invalid audio channel count %d\n",
24863e230dd2SCorentin Chary                               read_u8(data, 5));
24873e230dd2SCorentin Chary                     vnc_client_error(vs);
24883e230dd2SCorentin Chary                     break;
24893e230dd2SCorentin Chary                 }
2490cf070658SDaniel P. Berrangé                 freq = read_u32(data, 6);
2491cf070658SDaniel P. Berrangé                 /* No official limit for protocol, but 48khz is a sensible
2492cf070658SDaniel P. Berrangé                  * upper bound for trustworthy clients, and this limit
2493cf070658SDaniel P. Berrangé                  * protects calculations involving 'vs->as.freq' later.
2494cf070658SDaniel P. Berrangé                  */
2495cf070658SDaniel P. Berrangé                 if (freq > 48000) {
2496cf070658SDaniel P. Berrangé                     VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2497cf070658SDaniel P. Berrangé                     vnc_client_error(vs);
2498cf070658SDaniel P. Berrangé                     break;
2499cf070658SDaniel P. Berrangé                 }
2500cf070658SDaniel P. Berrangé                 vs->as.freq = freq;
25013e230dd2SCorentin Chary                 break;
25023e230dd2SCorentin Chary             default:
2503153130cdSDaniel P. Berrange                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
25043e230dd2SCorentin Chary                 vnc_client_error(vs);
25053e230dd2SCorentin Chary                 break;
25063e230dd2SCorentin Chary             }
25073e230dd2SCorentin Chary             break;
25083e230dd2SCorentin Chary 
25093e230dd2SCorentin Chary         default:
2510153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
25113e230dd2SCorentin Chary             vnc_client_error(vs);
25123e230dd2SCorentin Chary             break;
25133e230dd2SCorentin Chary         }
25143e230dd2SCorentin Chary         break;
2515763deea7SGerd Hoffmann     case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2516763deea7SGerd Hoffmann     {
2517763deea7SGerd Hoffmann         size_t size;
2518763deea7SGerd Hoffmann         uint8_t screens;
2519763deea7SGerd Hoffmann 
2520763deea7SGerd Hoffmann         if (len < 8) {
2521763deea7SGerd Hoffmann             return 8;
2522763deea7SGerd Hoffmann         }
2523763deea7SGerd Hoffmann 
2524763deea7SGerd Hoffmann         screens = read_u8(data, 6);
2525763deea7SGerd Hoffmann         size    = 8 + screens * 16;
2526763deea7SGerd Hoffmann         if (len < size) {
2527763deea7SGerd Hoffmann             return size;
2528763deea7SGerd Hoffmann         }
2529763deea7SGerd Hoffmann 
2530763deea7SGerd Hoffmann         if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2531763deea7SGerd Hoffmann             QemuUIInfo info;
2532763deea7SGerd Hoffmann             memset(&info, 0, sizeof(info));
2533763deea7SGerd Hoffmann             info.width = read_u16(data, 2);
2534763deea7SGerd Hoffmann             info.height = read_u16(data, 4);
2535763deea7SGerd Hoffmann             dpy_set_ui_info(vs->vd->dcl.con, &info);
2536763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2537763deea7SGerd Hoffmann         } else {
2538763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2539763deea7SGerd Hoffmann         }
2540763deea7SGerd Hoffmann 
2541763deea7SGerd Hoffmann         break;
2542763deea7SGerd Hoffmann     }
25433e230dd2SCorentin Chary     default:
2544153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
25453e230dd2SCorentin Chary         vnc_client_error(vs);
25463e230dd2SCorentin Chary         break;
25473e230dd2SCorentin Chary     }
25483e230dd2SCorentin Chary 
2549e2b72cb6SDaniel P. Berrange     vnc_update_throttle_offset(vs);
25503e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
25513e230dd2SCorentin Chary     return 0;
25523e230dd2SCorentin Chary }
25533e230dd2SCorentin Chary 
25543e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
25553e230dd2SCorentin Chary {
25563e230dd2SCorentin Chary     char buf[1024];
25578cf36489SGerd Hoffmann     VncShareMode mode;
25583e230dd2SCorentin Chary     int size;
25593e230dd2SCorentin Chary 
25608cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
25618cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
25628cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
25638cf36489SGerd Hoffmann         /*
25648cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
25658cf36489SGerd Hoffmann          *
25668cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
25678cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
25688cf36489SGerd Hoffmann          * reasons.
25698cf36489SGerd Hoffmann          */
25708cf36489SGerd Hoffmann         break;
25718cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
25728cf36489SGerd Hoffmann         /*
25738cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
25748cf36489SGerd Hoffmann          *
25758cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
25768cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
25778cf36489SGerd Hoffmann          * as no exclusive connection exists.
25788cf36489SGerd Hoffmann          *
25798cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
25808cf36489SGerd Hoffmann          */
25818cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
25828cf36489SGerd Hoffmann             VncState *client;
25838cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
25848cf36489SGerd Hoffmann                 if (vs == client) {
25858cf36489SGerd Hoffmann                     continue;
25868cf36489SGerd Hoffmann                 }
25878cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
25888cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
25898cf36489SGerd Hoffmann                     continue;
25908cf36489SGerd Hoffmann                 }
25918cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
25928cf36489SGerd Hoffmann             }
25938cf36489SGerd Hoffmann         }
25948cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
25958cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
25968cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
25978cf36489SGerd Hoffmann                 return 0;
25988cf36489SGerd Hoffmann             }
25998cf36489SGerd Hoffmann         }
26008cf36489SGerd Hoffmann         break;
26018cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
26028cf36489SGerd Hoffmann         /*
26038cf36489SGerd Hoffmann          * Policy: Shared connects only.
26048cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
26058cf36489SGerd Hoffmann          *
26068cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
26078cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
26088cf36489SGerd Hoffmann          * client disconnect everybody else.
26098cf36489SGerd Hoffmann          */
26108cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
26118cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
26128cf36489SGerd Hoffmann             return 0;
26138cf36489SGerd Hoffmann         }
26148cf36489SGerd Hoffmann         break;
26158cf36489SGerd Hoffmann     }
26168cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
26178cf36489SGerd Hoffmann 
2618e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2619e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2620e5f34cddSGerd Hoffmann         return 0;
2621e5f34cddSGerd Hoffmann     }
2622e5f34cddSGerd Hoffmann 
26234c956bd8SDaniel P. Berrange     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
26244c956bd8SDaniel P. Berrange            pixman_image_get_width(vs->vd->server) >= 0);
26254c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
26264c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
2627bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2628bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
26293e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
26303e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
26313e230dd2SCorentin Chary 
26323e230dd2SCorentin Chary     pixel_format_message(vs);
26333e230dd2SCorentin Chary 
263497efe4f9SThomas Huth     if (qemu_name) {
26353e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
263697efe4f9SThomas Huth         if (size > sizeof(buf)) {
263797efe4f9SThomas Huth             size = sizeof(buf);
263897efe4f9SThomas Huth         }
263997efe4f9SThomas Huth     } else {
26403e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
264197efe4f9SThomas Huth     }
26423e230dd2SCorentin Chary 
26433e230dd2SCorentin Chary     vnc_write_u32(vs, size);
26443e230dd2SCorentin Chary     vnc_write(vs, buf, size);
26453e230dd2SCorentin Chary     vnc_flush(vs);
26463e230dd2SCorentin Chary 
26473e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2648fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
26493e230dd2SCorentin Chary 
26503e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
26513e230dd2SCorentin Chary 
26523e230dd2SCorentin Chary     return 0;
26533e230dd2SCorentin Chary }
26543e230dd2SCorentin Chary 
26553e230dd2SCorentin Chary void start_client_init(VncState *vs)
26563e230dd2SCorentin Chary {
26573e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
26583e230dd2SCorentin Chary }
26593e230dd2SCorentin Chary 
26604347e638SRichard Henderson static void authentication_failed(VncState *vs)
26614347e638SRichard Henderson {
26624347e638SRichard Henderson     vnc_write_u32(vs, 1); /* Reject auth */
26634347e638SRichard Henderson     if (vs->minor >= 8) {
26644347e638SRichard Henderson         static const char err[] = "Authentication failed";
26654347e638SRichard Henderson         vnc_write_u32(vs, sizeof(err));
26664347e638SRichard Henderson         vnc_write(vs, err, sizeof(err));
26674347e638SRichard Henderson     }
26684347e638SRichard Henderson     vnc_flush(vs);
26694347e638SRichard Henderson     vnc_client_error(vs);
26704347e638SRichard Henderson }
26714347e638SRichard Henderson 
26723e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
26733e230dd2SCorentin Chary {
26743e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2675800567a6SDaniel P. Berrange     size_t i, pwlen;
26763e230dd2SCorentin Chary     unsigned char key[8];
26773c9405a0SGerd Hoffmann     time_t now = time(NULL);
267860928458SGonglei     QCryptoCipher *cipher = NULL;
2679800567a6SDaniel P. Berrange     Error *err = NULL;
26803e230dd2SCorentin Chary 
26811cd20f8bSAnthony Liguori     if (!vs->vd->password) {
26827364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
26836bffdf0fSGerd Hoffmann         goto reject;
26843e230dd2SCorentin Chary     }
26853c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
26867364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
26873c9405a0SGerd Hoffmann         goto reject;
26883c9405a0SGerd Hoffmann     }
26893e230dd2SCorentin Chary 
26903e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
26913e230dd2SCorentin Chary 
26923e230dd2SCorentin Chary     /* Calculate the expected challenge response */
26933e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
26943e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
26953e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2696800567a6SDaniel P. Berrange 
2697800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
2698800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_DES_RFB,
2699800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2700800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2701800567a6SDaniel P. Berrange         &err);
2702800567a6SDaniel P. Berrange     if (!cipher) {
27037364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2704800567a6SDaniel P. Berrange                             error_get_pretty(err));
2705800567a6SDaniel P. Berrange         error_free(err);
2706800567a6SDaniel P. Berrange         goto reject;
2707800567a6SDaniel P. Berrange     }
2708800567a6SDaniel P. Berrange 
2709a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2710800567a6SDaniel P. Berrange                                vs->challenge,
2711800567a6SDaniel P. Berrange                                response,
2712800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2713800567a6SDaniel P. Berrange                                &err) < 0) {
27147364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2715800567a6SDaniel P. Berrange                             error_get_pretty(err));
2716800567a6SDaniel P. Berrange         error_free(err);
2717800567a6SDaniel P. Berrange         goto reject;
2718800567a6SDaniel P. Berrange     }
27193e230dd2SCorentin Chary 
27203e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
27213e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
27227364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
27236bffdf0fSGerd Hoffmann         goto reject;
27246bffdf0fSGerd Hoffmann     } else {
27257364dbdaSDaniel P. Berrange         trace_vnc_auth_pass(vs, vs->auth);
27266bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
27276bffdf0fSGerd Hoffmann         vnc_flush(vs);
27286bffdf0fSGerd Hoffmann 
27296bffdf0fSGerd Hoffmann         start_client_init(vs);
27306bffdf0fSGerd Hoffmann     }
273160928458SGonglei 
273260928458SGonglei     qcrypto_cipher_free(cipher);
27336bffdf0fSGerd Hoffmann     return 0;
27346bffdf0fSGerd Hoffmann 
27356bffdf0fSGerd Hoffmann reject:
27364347e638SRichard Henderson     authentication_failed(vs);
273760928458SGonglei     qcrypto_cipher_free(cipher);
27383e230dd2SCorentin Chary     return 0;
27393e230dd2SCorentin Chary }
27403e230dd2SCorentin Chary 
27413e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
27423e230dd2SCorentin Chary {
2743f7b2502cSRichard Henderson     Error *err = NULL;
2744f7b2502cSRichard Henderson 
2745f7b2502cSRichard Henderson     if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2746f7b2502cSRichard Henderson         trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2747f7b2502cSRichard Henderson                             error_get_pretty(err));
2748f7b2502cSRichard Henderson         error_free(err);
2749f7b2502cSRichard Henderson         authentication_failed(vs);
2750f7b2502cSRichard Henderson         return;
2751f7b2502cSRichard Henderson     }
2752f7b2502cSRichard Henderson 
27533e230dd2SCorentin Chary     /* Send client a 'random' challenge */
27543e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
27553e230dd2SCorentin Chary     vnc_flush(vs);
27563e230dd2SCorentin Chary 
27573e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
27583e230dd2SCorentin Chary }
27593e230dd2SCorentin Chary 
27603e230dd2SCorentin Chary 
27613e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
27623e230dd2SCorentin Chary {
27633e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
27643e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
27657e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
27667364dbdaSDaniel P. Berrange        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
27674347e638SRichard Henderson        authentication_failed(vs);
27683e230dd2SCorentin Chary     } else { /* Accept requested auth */
27697364dbdaSDaniel P. Berrange        trace_vnc_auth_start(vs, vs->auth);
27707e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
27713e230dd2SCorentin Chary        case VNC_AUTH_NONE:
27723e230dd2SCorentin Chary            if (vs->minor >= 8) {
27733e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
27743e230dd2SCorentin Chary                vnc_flush(vs);
27753e230dd2SCorentin Chary            }
27767364dbdaSDaniel P. Berrange            trace_vnc_auth_pass(vs, vs->auth);
27773e230dd2SCorentin Chary            start_client_init(vs);
27783e230dd2SCorentin Chary            break;
27793e230dd2SCorentin Chary 
27803e230dd2SCorentin Chary        case VNC_AUTH_VNC:
27813e230dd2SCorentin Chary            start_auth_vnc(vs);
27823e230dd2SCorentin Chary            break;
27833e230dd2SCorentin Chary 
27843e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
27853e230dd2SCorentin Chary            start_auth_vencrypt(vs);
27863e230dd2SCorentin Chary            break;
27873e230dd2SCorentin Chary 
27883e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
27893e230dd2SCorentin Chary        case VNC_AUTH_SASL:
27903e230dd2SCorentin Chary            start_auth_sasl(vs);
27913e230dd2SCorentin Chary            break;
27923e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
27933e230dd2SCorentin Chary 
27943e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
27957364dbdaSDaniel P. Berrange            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
27964347e638SRichard Henderson            authentication_failed(vs);
27973e230dd2SCorentin Chary        }
27983e230dd2SCorentin Chary     }
27993e230dd2SCorentin Chary     return 0;
28003e230dd2SCorentin Chary }
28013e230dd2SCorentin Chary 
28023e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
28033e230dd2SCorentin Chary {
28043e230dd2SCorentin Chary     char local[13];
28053e230dd2SCorentin Chary 
28063e230dd2SCorentin Chary     memcpy(local, version, 12);
28073e230dd2SCorentin Chary     local[12] = 0;
28083e230dd2SCorentin Chary 
28093e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
28103e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
28113e230dd2SCorentin Chary         vnc_client_error(vs);
28123e230dd2SCorentin Chary         return 0;
28133e230dd2SCorentin Chary     }
28143e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
28153e230dd2SCorentin Chary     if (vs->major != 3 ||
28163e230dd2SCorentin Chary         (vs->minor != 3 &&
28173e230dd2SCorentin Chary          vs->minor != 4 &&
28183e230dd2SCorentin Chary          vs->minor != 5 &&
28193e230dd2SCorentin Chary          vs->minor != 7 &&
28203e230dd2SCorentin Chary          vs->minor != 8)) {
28213e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
28223e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
28233e230dd2SCorentin Chary         vnc_flush(vs);
28243e230dd2SCorentin Chary         vnc_client_error(vs);
28253e230dd2SCorentin Chary         return 0;
28263e230dd2SCorentin Chary     }
28273e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
28283e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
28293e230dd2SCorentin Chary      */
28303e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
28313e230dd2SCorentin Chary         vs->minor = 3;
28323e230dd2SCorentin Chary 
28333e230dd2SCorentin Chary     if (vs->minor == 3) {
28347364dbdaSDaniel P. Berrange         trace_vnc_auth_start(vs, vs->auth);
28357e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
28367e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
28373e230dd2SCorentin Chary             vnc_flush(vs);
28387364dbdaSDaniel P. Berrange             trace_vnc_auth_pass(vs, vs->auth);
28393e230dd2SCorentin Chary             start_client_init(vs);
28407e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
28413e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
28427e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
28433e230dd2SCorentin Chary             vnc_flush(vs);
28443e230dd2SCorentin Chary             start_auth_vnc(vs);
28453e230dd2SCorentin Chary        } else {
28467364dbdaSDaniel P. Berrange             trace_vnc_auth_fail(vs, vs->auth,
28477364dbdaSDaniel P. Berrange                                 "Unsupported auth method for v3.3", "");
28483e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
28493e230dd2SCorentin Chary             vnc_flush(vs);
28503e230dd2SCorentin Chary             vnc_client_error(vs);
28513e230dd2SCorentin Chary        }
28523e230dd2SCorentin Chary     } else {
28533e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
28547e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
28553e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
28563e230dd2SCorentin Chary         vnc_flush(vs);
28573e230dd2SCorentin Chary     }
28583e230dd2SCorentin Chary 
28593e230dd2SCorentin Chary     return 0;
28603e230dd2SCorentin Chary }
28613e230dd2SCorentin Chary 
2862999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2863999342a0SCorentin Chary {
2864999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2865999342a0SCorentin Chary 
2866999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2867999342a0SCorentin Chary }
2868999342a0SCorentin Chary 
28697d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
28707d964c9dSCorentin Chary {
28717d964c9dSCorentin Chary     int i, j;
28727d964c9dSCorentin Chary 
28737d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
28747d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
28757d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
28767d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
28777d964c9dSCorentin Chary 
2878207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2879207f328aSCorentin Chary         for (i = x; i <= w; i++) {
28807d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
28817d964c9dSCorentin Chary         }
28827d964c9dSCorentin Chary     }
28837d964c9dSCorentin Chary }
28847d964c9dSCorentin Chary 
28857d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
28867d964c9dSCorentin Chary {
28877d964c9dSCorentin Chary     VncState *vs;
28887d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
28897d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
28907d964c9dSCorentin Chary     int has_dirty = 0;
28917d964c9dSCorentin Chary 
28925a3804dbSMarc-André Lureau     y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
28935a3804dbSMarc-André Lureau     x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
28947d964c9dSCorentin Chary 
28957d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2896bc2429b9SCorentin Chary         int j;
28977d964c9dSCorentin Chary 
28987d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
28997d964c9dSCorentin Chary         if (vs->output.offset) {
29007d964c9dSCorentin Chary             continue;
29017d964c9dSCorentin Chary         }
29027d964c9dSCorentin Chary 
29037d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
29047d964c9dSCorentin Chary             continue;
29057d964c9dSCorentin Chary         }
2906207f328aSCorentin Chary 
29077d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
29087d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2909b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2910b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2911b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
29127d964c9dSCorentin Chary         }
29137d964c9dSCorentin Chary         has_dirty++;
29147d964c9dSCorentin Chary     }
2915207f328aSCorentin Chary 
29167d964c9dSCorentin Chary     return has_dirty;
29177d964c9dSCorentin Chary }
29187d964c9dSCorentin Chary 
29197d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2920999342a0SCorentin Chary {
2921eebe0b79SGerd Hoffmann     int width = MIN(pixman_image_get_width(vd->guest.fb),
2922eebe0b79SGerd Hoffmann                     pixman_image_get_width(vd->server));
2923eebe0b79SGerd Hoffmann     int height = MIN(pixman_image_get_height(vd->guest.fb),
2924eebe0b79SGerd Hoffmann                      pixman_image_get_height(vd->server));
2925999342a0SCorentin Chary     int x, y;
2926999342a0SCorentin Chary     struct timeval res;
29277d964c9dSCorentin Chary     int has_dirty = 0;
2928999342a0SCorentin Chary 
29299f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
29309f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2931999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2932999342a0SCorentin Chary 
2933999342a0SCorentin Chary             rect->updated = false;
2934999342a0SCorentin Chary         }
2935999342a0SCorentin Chary     }
2936999342a0SCorentin Chary 
2937ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2938999342a0SCorentin Chary 
2939999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
29407d964c9dSCorentin Chary         return has_dirty;
2941999342a0SCorentin Chary     }
2942999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
2943999342a0SCorentin Chary 
29449f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
29459f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2946999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2947999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
2948999342a0SCorentin Chary             struct timeval min, max;
2949999342a0SCorentin Chary 
2950999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
2951999342a0SCorentin Chary                 continue ;
2952999342a0SCorentin Chary             }
2953999342a0SCorentin Chary 
2954999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2955ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
2956999342a0SCorentin Chary 
2957999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2958999342a0SCorentin Chary                 rect->freq = 0;
29597d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2960999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
2961999342a0SCorentin Chary                 continue ;
2962999342a0SCorentin Chary             }
2963999342a0SCorentin Chary 
2964999342a0SCorentin Chary             min = rect->times[rect->idx];
2965999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2966ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
2967999342a0SCorentin Chary 
2968999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2969999342a0SCorentin Chary             rect->freq /= count;
2970999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
2971999342a0SCorentin Chary         }
2972999342a0SCorentin Chary     }
29737d964c9dSCorentin Chary     return has_dirty;
2974999342a0SCorentin Chary }
2975999342a0SCorentin Chary 
2976999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2977999342a0SCorentin Chary {
2978999342a0SCorentin Chary     int i, j;
2979999342a0SCorentin Chary     double total = 0;
2980999342a0SCorentin Chary     int num = 0;
2981999342a0SCorentin Chary 
29825a3804dbSMarc-André Lureau     x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
29835a3804dbSMarc-André Lureau     y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2984999342a0SCorentin Chary 
2985999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2986999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2987999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
2988999342a0SCorentin Chary             num++;
2989999342a0SCorentin Chary         }
2990999342a0SCorentin Chary     }
2991999342a0SCorentin Chary 
2992999342a0SCorentin Chary     if (num) {
2993999342a0SCorentin Chary         return total / num;
2994999342a0SCorentin Chary     } else {
2995999342a0SCorentin Chary         return 0;
2996999342a0SCorentin Chary     }
2997999342a0SCorentin Chary }
2998999342a0SCorentin Chary 
2999999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
3000999342a0SCorentin Chary {
3001999342a0SCorentin Chary     VncRectStat *rect;
3002999342a0SCorentin Chary 
3003999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
3004999342a0SCorentin Chary     if (rect->updated) {
3005999342a0SCorentin Chary         return ;
3006999342a0SCorentin Chary     }
3007999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
3008999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3009999342a0SCorentin Chary     rect->updated = true;
3010999342a0SCorentin Chary }
3011999342a0SCorentin Chary 
30123e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
30133e230dd2SCorentin Chary {
3014bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
3015bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
3016bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
3017bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
3018eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
301912b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
30203e230dd2SCorentin Chary     VncState *vs;
30213e230dd2SCorentin Chary     int has_dirty = 0;
30229f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
30233e230dd2SCorentin Chary 
302480e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
3025999342a0SCorentin Chary 
302680e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
3027999342a0SCorentin Chary         gettimeofday(&tv, NULL);
30287d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
302980e0c8c3SCorentin Chary     }
3030999342a0SCorentin Chary 
30313e230dd2SCorentin Chary     /*
30323e230dd2SCorentin Chary      * Walk through the guest dirty map.
30333e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
30343e230dd2SCorentin Chary      * Update server dirty map.
30353e230dd2SCorentin Chary      */
3036bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3037eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
3038eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
3039bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3040bea60dd7SPeter Lieven                     server_stride);
30419f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
30429f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
30439f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
304412b316d4SPeter Lieven     } else {
3045eb8934b0SGerd Hoffmann         int guest_bpp =
3046eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
304712b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
304812b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
3049949ed4c2SPhilippe Mathieu-Daudé         guest_ll = pixman_image_get_width(vd->guest.fb)
3050949ed4c2SPhilippe Mathieu-Daudé                    * DIV_ROUND_UP(guest_bpp, 8);
30519f64916dSGerd Hoffmann     }
3052eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
305312b316d4SPeter Lieven 
305412b316d4SPeter Lieven     for (;;) {
30553e230dd2SCorentin Chary         int x;
305612b316d4SPeter Lieven         uint8_t *guest_ptr, *server_ptr;
305712b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
305812b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(&vd->guest),
305912b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(&vd->guest));
306012b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
306112b316d4SPeter Lieven             /* no more dirty bits */
306212b316d4SPeter Lieven             break;
306312b316d4SPeter Lieven         }
306412b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
306512b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
306612b316d4SPeter Lieven 
306712b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
30683e230dd2SCorentin Chary 
30699f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3070bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
30719f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
30729f64916dSGerd Hoffmann         } else {
307312b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
30749f64916dSGerd Hoffmann         }
307512b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
30763e230dd2SCorentin Chary 
307712b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
307812b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3079bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
308012b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
30813e230dd2SCorentin Chary                 continue;
3082b4c85ddcSPeter Lieven             }
3083eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
3084eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
3085bea60dd7SPeter Lieven             }
3086eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
3087bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
30883e230dd2SCorentin Chary                 continue;
3089b4c85ddcSPeter Lieven             }
3090bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
309112b316d4SPeter Lieven             if (!vd->non_adaptive) {
309212b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
309312b316d4SPeter Lieven                                  y, &tv);
309412b316d4SPeter Lieven             }
30953e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
309612b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
30973e230dd2SCorentin Chary             }
30983e230dd2SCorentin Chary             has_dirty++;
30993e230dd2SCorentin Chary         }
310012b316d4SPeter Lieven 
310112b316d4SPeter Lieven         y++;
31023e230dd2SCorentin Chary     }
31039f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
31043e230dd2SCorentin Chary     return has_dirty;
31053e230dd2SCorentin Chary }
31063e230dd2SCorentin Chary 
31070f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
31083e230dd2SCorentin Chary {
31090f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
31103e230dd2SCorentin Chary     VncState *vs, *vn;
31113e230dd2SCorentin Chary     int has_dirty, rects = 0;
31123e230dd2SCorentin Chary 
31139d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
31149d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
31159d6b2070SChenLiang         return;
31169d6b2070SChenLiang     }
31179d6b2070SChenLiang 
31181d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
31193e230dd2SCorentin Chary 
3120bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
31210f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3122bd023f95SCorentin Chary         return;
3123bd023f95SCorentin Chary     }
3124bd023f95SCorentin Chary 
31253e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
3126bd023f95SCorentin Chary     vnc_unlock_display(vd);
31273e230dd2SCorentin Chary 
31283e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
31296af998dbSDaniel P. Berrange         rects += vnc_update_client(vs, has_dirty);
31303e230dd2SCorentin Chary         /* vs might be free()ed here */
31313e230dd2SCorentin Chary     }
3132bd023f95SCorentin Chary 
31333e230dd2SCorentin Chary     if (has_dirty && rects) {
31340f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
31350f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
31360f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
31370f7b2864SGerd Hoffmann         }
31383e230dd2SCorentin Chary     } else {
31390f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
31400f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
31410f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
31423e230dd2SCorentin Chary         }
31433e230dd2SCorentin Chary     }
31443e230dd2SCorentin Chary }
31453e230dd2SCorentin Chary 
314604d2529dSDaniel P. Berrange static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
31472c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
31483e230dd2SCorentin Chary {
3149fedf0d35SMarkus Armbruster     VncState *vs = g_new0(VncState, 1);
315090cd03a3SDaniel P. Berrange     bool first_client = QTAILQ_EMPTY(&vd->clients);
31517d964c9dSCorentin Chary     int i;
31527d964c9dSCorentin Chary 
3153ad6374c4SDaniel P. Berrange     trace_vnc_client_connect(vs, sioc);
31546bf21f3dSLi Qiang     vs->zrle = g_new0(VncZrle, 1);
31556bf21f3dSLi Qiang     vs->tight = g_new0(VncTight, 1);
3156f31f9c10SGerd Hoffmann     vs->magic = VNC_MAGIC;
315704d2529dSDaniel P. Berrange     vs->sioc = sioc;
315804d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->sioc));
315904d2529dSDaniel P. Berrange     vs->ioc = QIO_CHANNEL(sioc);
316004d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->ioc));
3161d616ccc5SGerd Hoffmann     vs->vd = vd;
31627e7e2ebcSDaniel P. Berrange 
316304d2529dSDaniel P. Berrange     buffer_init(&vs->input,          "vnc-input/%p", sioc);
316404d2529dSDaniel P. Berrange     buffer_init(&vs->output,         "vnc-output/%p", sioc);
316504d2529dSDaniel P. Berrange     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3166543b9580SGerd Hoffmann 
31676bf21f3dSLi Qiang     buffer_init(&vs->tight->tight,    "vnc-tight/%p", sioc);
31686bf21f3dSLi Qiang     buffer_init(&vs->tight->zlib,     "vnc-tight-zlib/%p", sioc);
31696bf21f3dSLi Qiang     buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3170543b9580SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
31716bf21f3dSLi Qiang     buffer_init(&vs->tight->jpeg,     "vnc-tight-jpeg/%p", sioc);
3172543b9580SGerd Hoffmann #endif
3173543b9580SGerd Hoffmann #ifdef CONFIG_VNC_PNG
31746bf21f3dSLi Qiang     buffer_init(&vs->tight->png,      "vnc-tight-png/%p", sioc);
3175543b9580SGerd Hoffmann #endif
317604d2529dSDaniel P. Berrange     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
31776bf21f3dSLi Qiang     buffer_init(&vs->zrle->zrle,      "vnc-zrle/%p", sioc);
31786bf21f3dSLi Qiang     buffer_init(&vs->zrle->fb,        "vnc-zrle-fb/%p", sioc);
31796bf21f3dSLi Qiang     buffer_init(&vs->zrle->zlib,      "vnc-zrle-zlib/%p", sioc);
3180543b9580SGerd Hoffmann 
31817e7e2ebcSDaniel P. Berrange     if (skipauth) {
31827e7e2ebcSDaniel P. Berrange         vs->auth = VNC_AUTH_NONE;
31837e7e2ebcSDaniel P. Berrange         vs->subauth = VNC_AUTH_INVALID;
31847e7e2ebcSDaniel P. Berrange     } else {
3185f9148c8aSDaniel P. Berrange         if (websocket) {
3186f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
3187f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
3188f9148c8aSDaniel P. Berrange         } else {
31897e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
31907e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
31917e7e2ebcSDaniel P. Berrange         }
3192f9148c8aSDaniel P. Berrange     }
319304d2529dSDaniel P. Berrange     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
319404d2529dSDaniel P. Berrange               sioc, websocket, vs->auth, vs->subauth);
31957e7e2ebcSDaniel P. Berrange 
31967267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
31977d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3198fedf0d35SMarkus Armbruster         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
31997d964c9dSCorentin Chary     }
32003e230dd2SCorentin Chary 
320104d2529dSDaniel P. Berrange     VNC_DEBUG("New client on socket %p\n", vs->sioc);
32020f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
320304d2529dSDaniel P. Berrange     qio_channel_set_blocking(vs->ioc, false, NULL);
3204a75d6f07SBrandon Carpenter     if (vs->ioc_tag) {
3205a75d6f07SBrandon Carpenter         g_source_remove(vs->ioc_tag);
3206a75d6f07SBrandon Carpenter     }
32077536ee4bSTim Hardeck     if (websocket) {
32087536ee4bSTim Hardeck         vs->websocket = 1;
320938e5756aSDaniel P. Berrange         if (vd->tlscreds) {
321004d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
32112ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32122ddafce7SDing Hui                 vncws_tls_handshake_io, vs, NULL);
32133e305e4aSDaniel P. Berrange         } else {
321404d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
32152ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32162ddafce7SDing Hui                 vncws_handshake_io, vs, NULL);
32170057a0d5STim Hardeck         }
321804d2529dSDaniel P. Berrange     } else {
321904d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
32202ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32212ddafce7SDing Hui             vnc_client_io, vs, NULL);
32227536ee4bSTim Hardeck     }
32233e230dd2SCorentin Chary 
32243e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3225fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
32268cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
32273e230dd2SCorentin Chary 
32283e230dd2SCorentin Chary     vs->last_x = -1;
32293e230dd2SCorentin Chary     vs->last_y = -1;
32303e230dd2SCorentin Chary 
32313e230dd2SCorentin Chary     vs->as.freq = 44100;
32323e230dd2SCorentin Chary     vs->as.nchannels = 2;
323385bc5852SKővágó, Zoltán     vs->as.fmt = AUDIO_FORMAT_S16;
32343e230dd2SCorentin Chary     vs->as.endianness = 0;
32353e230dd2SCorentin Chary 
3236bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3237175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3238bd023f95SCorentin Chary 
3239e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3240c7628bffSGerd Hoffmann     if (first_client) {
3241c7628bffSGerd Hoffmann         vnc_update_server_surface(vd);
3242c7628bffSGerd Hoffmann     }
32433e230dd2SCorentin Chary 
32441d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
32453e230dd2SCorentin Chary 
324690cd03a3SDaniel P. Berrange     if (!vs->websocket) {
3247dbee9897SDaniel P. Berrange         vnc_start_protocol(vs);
324890cd03a3SDaniel P. Berrange     }
324990cd03a3SDaniel P. Berrange 
325090cd03a3SDaniel P. Berrange     if (vd->num_connecting > vd->connections_limit) {
325190cd03a3SDaniel P. Berrange         QTAILQ_FOREACH(vs, &vd->clients, next) {
325290cd03a3SDaniel P. Berrange             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
325390cd03a3SDaniel P. Berrange                 vnc_disconnect_start(vs);
325490cd03a3SDaniel P. Berrange                 return;
325590cd03a3SDaniel P. Berrange             }
325690cd03a3SDaniel P. Berrange         }
325790cd03a3SDaniel P. Berrange     }
325890cd03a3SDaniel P. Berrange }
325990cd03a3SDaniel P. Berrange 
3260dbee9897SDaniel P. Berrange void vnc_start_protocol(VncState *vs)
326190cd03a3SDaniel P. Berrange {
32623e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
32633e230dd2SCorentin Chary     vnc_flush(vs);
32643e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
32653e230dd2SCorentin Chary 
32663e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
32673e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
32683e230dd2SCorentin Chary }
32693e230dd2SCorentin Chary 
327013e1d0e7SDaniel P. Berrange static void vnc_listen_io(QIONetListener *listener,
327113e1d0e7SDaniel P. Berrange                           QIOChannelSocket *cioc,
327204d2529dSDaniel P. Berrange                           void *opaque)
32733e230dd2SCorentin Chary {
3274bf01c179SDaniel P. Berrange     VncDisplay *vd = opaque;
327513e1d0e7SDaniel P. Berrange     bool isWebsock = listener == vd->wslistener;
32764ee74fa7SDaniel P. Berrange 
327713e1d0e7SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(cioc),
32784ee74fa7SDaniel P. Berrange                          isWebsock ? "vnc-ws-server" : "vnc-server");
327913e1d0e7SDaniel P. Berrange     qio_channel_set_delay(QIO_CHANNEL(cioc), false);
328013e1d0e7SDaniel P. Berrange     vnc_connect(vd, cioc, false, isWebsock);
32817536ee4bSTim Hardeck }
32827536ee4bSTim Hardeck 
32837c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
32847c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
32850f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
32867c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3287c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
328834da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
32897c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
32907c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
32917c20b4a3SGerd Hoffmann };
32927c20b4a3SGerd Hoffmann 
3293ab4f931eSFei Li void vnc_display_init(const char *id, Error **errp)
32943e230dd2SCorentin Chary {
3295bf01c179SDaniel P. Berrange     VncDisplay *vd;
32964db14629SGerd Hoffmann 
32974db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
32984db14629SGerd Hoffmann         return;
32994db14629SGerd Hoffmann     }
3300bf01c179SDaniel P. Berrange     vd = g_malloc0(sizeof(*vd));
33013e230dd2SCorentin Chary 
3302bf01c179SDaniel P. Berrange     vd->id = strdup(id);
3303bf01c179SDaniel P. Berrange     QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
33043e230dd2SCorentin Chary 
3305bf01c179SDaniel P. Berrange     QTAILQ_INIT(&vd->clients);
3306bf01c179SDaniel P. Berrange     vd->expires = TIME_MAX;
33073e230dd2SCorentin Chary 
330840066175SGerd Hoffmann     if (keyboard_layout) {
330940066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
3310ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym,
3311ab4f931eSFei Li                                               keyboard_layout, errp);
331240066175SGerd Hoffmann     } else {
3313ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
331440066175SGerd Hoffmann     }
33153e230dd2SCorentin Chary 
3316bf01c179SDaniel P. Berrange     if (!vd->kbd_layout) {
3317ab4f931eSFei Li         return;
3318bf01c179SDaniel P. Berrange     }
33193e230dd2SCorentin Chary 
3320bf01c179SDaniel P. Berrange     vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3321bf01c179SDaniel P. Berrange     vd->connections_limit = 32;
332212e29b16SDaniel P. Berrange 
3323bf01c179SDaniel P. Berrange     qemu_mutex_init(&vd->mutex);
3324bd023f95SCorentin Chary     vnc_start_worker_thread();
3325bd023f95SCorentin Chary 
3326bf01c179SDaniel P. Berrange     vd->dcl.ops = &dcl_ops;
3327bf01c179SDaniel P. Berrange     register_displaychangelistener(&vd->dcl);
3328c2f2ba49SGerd Hoffmann     vd->kbd = qkbd_state_init(vd->dcl.con);
33293e230dd2SCorentin Chary }
33303e230dd2SCorentin Chary 
33313e230dd2SCorentin Chary 
3332bf01c179SDaniel P. Berrange static void vnc_display_close(VncDisplay *vd)
33333e230dd2SCorentin Chary {
3334bf01c179SDaniel P. Berrange     if (!vd) {
33353e230dd2SCorentin Chary         return;
333604d2529dSDaniel P. Berrange     }
3337bf01c179SDaniel P. Berrange     vd->is_unix = false;
33384ee74fa7SDaniel P. Berrange 
333913e1d0e7SDaniel P. Berrange     if (vd->listener) {
334013e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->listener);
334113e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->listener));
334204d2529dSDaniel P. Berrange     }
334313e1d0e7SDaniel P. Berrange     vd->listener = NULL;
334413e1d0e7SDaniel P. Berrange 
334513e1d0e7SDaniel P. Berrange     if (vd->wslistener) {
334613e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->wslistener);
334713e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->wslistener));
33487536ee4bSTim Hardeck     }
334913e1d0e7SDaniel P. Berrange     vd->wslistener = NULL;
33504ee74fa7SDaniel P. Berrange 
3351bf01c179SDaniel P. Berrange     vd->auth = VNC_AUTH_INVALID;
3352bf01c179SDaniel P. Berrange     vd->subauth = VNC_AUTH_INVALID;
3353bf01c179SDaniel P. Berrange     if (vd->tlscreds) {
3354521534dfSZihao Chang         object_unref(OBJECT(vd->tlscreds));
3355bf01c179SDaniel P. Berrange         vd->tlscreds = NULL;
3356bf01c179SDaniel P. Berrange     }
3357b76806d4SDaniel P. Berrange     if (vd->tlsauthz) {
3358b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->tlsauthz));
3359b76806d4SDaniel P. Berrange         vd->tlsauthz = NULL;
3360b76806d4SDaniel P. Berrange     }
3361b76806d4SDaniel P. Berrange     g_free(vd->tlsauthzid);
3362b76806d4SDaniel P. Berrange     vd->tlsauthzid = NULL;
3363a54f0d2bSPierre Ossman     if (vd->lock_key_sync) {
3364a54f0d2bSPierre Ossman         qemu_remove_led_event_handler(vd->led);
33652dc120beSGerd Hoffmann         vd->led = NULL;
3366a54f0d2bSPierre Ossman     }
3367b76806d4SDaniel P. Berrange #ifdef CONFIG_VNC_SASL
3368b76806d4SDaniel P. Berrange     if (vd->sasl.authz) {
3369b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->sasl.authz));
3370b76806d4SDaniel P. Berrange         vd->sasl.authz = NULL;
3371b76806d4SDaniel P. Berrange     }
3372b76806d4SDaniel P. Berrange     g_free(vd->sasl.authzid);
3373b76806d4SDaniel P. Berrange     vd->sasl.authzid = NULL;
3374b76806d4SDaniel P. Berrange #endif
33753e230dd2SCorentin Chary }
33763e230dd2SCorentin Chary 
337714f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
33781cd20f8bSAnthony Liguori {
3379bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
33801cd20f8bSAnthony Liguori 
3381bf01c179SDaniel P. Berrange     if (!vd) {
3382a6aa9d3eSLuiz Capitulino         return -EINVAL;
33831cd20f8bSAnthony Liguori     }
3384bf01c179SDaniel P. Berrange     if (vd->auth == VNC_AUTH_NONE) {
3385cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
33867ea7d36eSMarkus Armbruster                                 "password auth using '-vnc ${dpy},password'.\n");
3387cf864569SGerd Hoffmann         return -EINVAL;
33881cd20f8bSAnthony Liguori     }
33891cd20f8bSAnthony Liguori 
3390bf01c179SDaniel P. Berrange     g_free(vd->password);
3391bf01c179SDaniel P. Berrange     vd->password = g_strdup(password);
3392a6aa9d3eSLuiz Capitulino 
3393a6aa9d3eSLuiz Capitulino     return 0;
33943e230dd2SCorentin Chary }
33953e230dd2SCorentin Chary 
339614f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
33973c9405a0SGerd Hoffmann {
3398bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
33993c9405a0SGerd Hoffmann 
3400bf01c179SDaniel P. Berrange     if (!vd) {
34011643f2b2SGerd Hoffmann         return -EINVAL;
34021643f2b2SGerd Hoffmann     }
34031643f2b2SGerd Hoffmann 
3404bf01c179SDaniel P. Berrange     vd->expires = expires;
34053c9405a0SGerd Hoffmann     return 0;
34063c9405a0SGerd Hoffmann }
34073c9405a0SGerd Hoffmann 
3408bf01c179SDaniel P. Berrange static void vnc_display_print_local_addr(VncDisplay *vd)
34093e230dd2SCorentin Chary {
3410bd269ebcSMarkus Armbruster     SocketAddress *addr;
34113e230dd2SCorentin Chary 
341213e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
34134ee74fa7SDaniel P. Berrange         return;
34144ee74fa7SDaniel P. Berrange     }
34154ee74fa7SDaniel P. Berrange 
3416b94b3c02SMarkus Armbruster     addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
341704d2529dSDaniel P. Berrange     if (!addr) {
341833df7bf3SPaolo Bonzini         return;
341904d2529dSDaniel P. Berrange     }
342004d2529dSDaniel P. Berrange 
3421bd269ebcSMarkus Armbruster     if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3422bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
342333df7bf3SPaolo Bonzini         return;
342404d2529dSDaniel P. Berrange     }
342533df7bf3SPaolo Bonzini     error_printf_unless_qmp("VNC server running on %s:%s\n",
3426bd269ebcSMarkus Armbruster                             addr->u.inet.host,
3427bd269ebcSMarkus Armbruster                             addr->u.inet.port);
3428bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
34293e230dd2SCorentin Chary }
34303e230dd2SCorentin Chary 
34314db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
34324db14629SGerd Hoffmann     .name = "vnc",
34334db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
34344db14629SGerd Hoffmann     .implied_opt_name = "vnc",
34354db14629SGerd Hoffmann     .desc = {
34364db14629SGerd Hoffmann         {
34374db14629SGerd Hoffmann             .name = "vnc",
34384db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
34394db14629SGerd Hoffmann         },{
34404db14629SGerd Hoffmann             .name = "websocket",
34414db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
34424db14629SGerd Hoffmann         },{
34433e305e4aSDaniel P. Berrange             .name = "tls-creds",
34443e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
34453e305e4aSDaniel P. Berrange         },{
34464db14629SGerd Hoffmann             .name = "share",
34474db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
34484db14629SGerd Hoffmann         },{
34491d0d59feSGerd Hoffmann             .name = "display",
34501d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
34511d0d59feSGerd Hoffmann         },{
34521d0d59feSGerd Hoffmann             .name = "head",
34531d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
34541d0d59feSGerd Hoffmann         },{
3455e5f34cddSGerd Hoffmann             .name = "connections",
3456e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3457e5f34cddSGerd Hoffmann         },{
345888428b7aSGonglei             .name = "to",
345988428b7aSGonglei             .type = QEMU_OPT_NUMBER,
346088428b7aSGonglei         },{
346188428b7aSGonglei             .name = "ipv4",
346288428b7aSGonglei             .type = QEMU_OPT_BOOL,
346388428b7aSGonglei         },{
346488428b7aSGonglei             .name = "ipv6",
346588428b7aSGonglei             .type = QEMU_OPT_BOOL,
346688428b7aSGonglei         },{
34674db14629SGerd Hoffmann             .name = "password",
34684db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
34694db14629SGerd Hoffmann         },{
34704db14629SGerd Hoffmann             .name = "reverse",
34714db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
34724db14629SGerd Hoffmann         },{
34734db14629SGerd Hoffmann             .name = "lock-key-sync",
34744db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
34754db14629SGerd Hoffmann         },{
3476c5ce8333SGerd Hoffmann             .name = "key-delay-ms",
3477c5ce8333SGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3478c5ce8333SGerd Hoffmann         },{
34794db14629SGerd Hoffmann             .name = "sasl",
34804db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
34814db14629SGerd Hoffmann         },{
34824db14629SGerd Hoffmann             .name = "acl",
34834db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
34844db14629SGerd Hoffmann         },{
348555cf09a0SDaniel P. Berrange             .name = "tls-authz",
348655cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
348755cf09a0SDaniel P. Berrange         },{
348855cf09a0SDaniel P. Berrange             .name = "sasl-authz",
348955cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
349055cf09a0SDaniel P. Berrange         },{
34914db14629SGerd Hoffmann             .name = "lossy",
34924db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
34934db14629SGerd Hoffmann         },{
34944db14629SGerd Hoffmann             .name = "non-adaptive",
34954db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
3496f0b9f36dSKővágó, Zoltán         },{
3497f0b9f36dSKővágó, Zoltán             .name = "audiodev",
3498f0b9f36dSKővágó, Zoltán             .type = QEMU_OPT_STRING,
34997b5fa0b5SDaniel P. Berrangé         },{
35007b5fa0b5SDaniel P. Berrangé             .name = "power-control",
35017b5fa0b5SDaniel P. Berrangé             .type = QEMU_OPT_BOOL,
35024db14629SGerd Hoffmann         },
35034db14629SGerd Hoffmann         { /* end of list */ }
35044db14629SGerd Hoffmann     },
35054db14629SGerd Hoffmann };
35064db14629SGerd Hoffmann 
35070dd72e15SDaniel P. Berrange 
35083e305e4aSDaniel P. Berrange static int
3509eda24e18SDaniel P. Berrange vnc_display_setup_auth(int *auth,
3510eda24e18SDaniel P. Berrange                        int *subauth,
3511eda24e18SDaniel P. Berrange                        QCryptoTLSCreds *tlscreds,
35120dd72e15SDaniel P. Berrange                        bool password,
35130dd72e15SDaniel P. Berrange                        bool sasl,
35143e305e4aSDaniel P. Berrange                        bool websocket,
35153e305e4aSDaniel P. Berrange                        Error **errp)
35160dd72e15SDaniel P. Berrange {
35170dd72e15SDaniel P. Berrange     /*
35180dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
35190dd72e15SDaniel P. Berrange      *
35200dd72e15SDaniel P. Berrange      *   1. none
35210dd72e15SDaniel P. Berrange      *   2. vnc
35220dd72e15SDaniel P. Berrange      *   3. sasl
35230dd72e15SDaniel P. Berrange      *
35240dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
35250dd72e15SDaniel P. Berrange      *
35260dd72e15SDaniel P. Berrange      *   1. clear
35270dd72e15SDaniel P. Berrange      *   2. tls
35280dd72e15SDaniel P. Berrange      *
35290dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
35300dd72e15SDaniel P. Berrange      *
35310dd72e15SDaniel P. Berrange      *   1. anon
35320dd72e15SDaniel P. Berrange      *   2. x509
35330dd72e15SDaniel P. Berrange      *
35340dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
35350dd72e15SDaniel P. Berrange      *
35360dd72e15SDaniel P. Berrange      *   1. clear + none
35370dd72e15SDaniel P. Berrange      *   2. clear + vnc
35380dd72e15SDaniel P. Berrange      *   3. clear + sasl
35390dd72e15SDaniel P. Berrange      *   4. tls + anon + none
35400dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
35410dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
35420dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
35430dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
35440dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
35450dd72e15SDaniel P. Berrange      *
35460dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
35470dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
35480dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
35490dd72e15SDaniel P. Berrange      * sub-auth types.
3550f9148c8aSDaniel P. Berrange      *
3551f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3552f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3553f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3554f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3555f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3556f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3557f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3558f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3559f9148c8aSDaniel P. Berrange      *
3560f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3561f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3562f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
35630dd72e15SDaniel P. Berrange      */
3564eda24e18SDaniel P. Berrange     if (websocket || !tlscreds) {
35650dd72e15SDaniel P. Berrange         if (password) {
35660dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
3567eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_VNC;
35680dd72e15SDaniel P. Berrange         } else if (sasl) {
35690dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3570eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_SASL;
35710dd72e15SDaniel P. Berrange         } else {
35720dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
3573eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_NONE;
35740dd72e15SDaniel P. Berrange         }
3575eda24e18SDaniel P. Berrange         *subauth = VNC_AUTH_INVALID;
3576f9148c8aSDaniel P. Berrange     } else {
3577eda24e18SDaniel P. Berrange         bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3578eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3579eda24e18SDaniel P. Berrange         bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3580eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3581eda24e18SDaniel P. Berrange 
3582eda24e18SDaniel P. Berrange         if (!is_x509 && !is_anon) {
3583eda24e18SDaniel P. Berrange             error_setg(errp,
3584eda24e18SDaniel P. Berrange                        "Unsupported TLS cred type %s",
3585eda24e18SDaniel P. Berrange                        object_get_typename(OBJECT(tlscreds)));
3586eda24e18SDaniel P. Berrange             return -1;
3587eda24e18SDaniel P. Berrange         }
3588eda24e18SDaniel P. Berrange         *auth = VNC_AUTH_VENCRYPT;
3589eda24e18SDaniel P. Berrange         if (password) {
3590eda24e18SDaniel P. Berrange             if (is_x509) {
3591eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3592eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3593eda24e18SDaniel P. Berrange             } else {
3594eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3595eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3596eda24e18SDaniel P. Berrange             }
3597eda24e18SDaniel P. Berrange 
3598eda24e18SDaniel P. Berrange         } else if (sasl) {
3599eda24e18SDaniel P. Berrange             if (is_x509) {
3600eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3601eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3602eda24e18SDaniel P. Berrange             } else {
3603eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3604eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3605eda24e18SDaniel P. Berrange             }
3606eda24e18SDaniel P. Berrange         } else {
3607eda24e18SDaniel P. Berrange             if (is_x509) {
3608eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3609eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3610eda24e18SDaniel P. Berrange             } else {
3611eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3612eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3613eda24e18SDaniel P. Berrange             }
3614f9148c8aSDaniel P. Berrange         }
36150dd72e15SDaniel P. Berrange     }
36163e305e4aSDaniel P. Berrange     return 0;
36170dd72e15SDaniel P. Berrange }
36180dd72e15SDaniel P. Berrange 
36193e305e4aSDaniel P. Berrange 
3620275e0d61SDaniel P. Berrange static int vnc_display_get_address(const char *addrstr,
3621275e0d61SDaniel P. Berrange                                    bool websocket,
3622e5766eb4SGerd Hoffmann                                    bool reverse,
3623275e0d61SDaniel P. Berrange                                    int displaynum,
3624275e0d61SDaniel P. Berrange                                    int to,
3625275e0d61SDaniel P. Berrange                                    bool has_ipv4,
3626275e0d61SDaniel P. Berrange                                    bool has_ipv6,
3627275e0d61SDaniel P. Berrange                                    bool ipv4,
3628275e0d61SDaniel P. Berrange                                    bool ipv6,
3629bd269ebcSMarkus Armbruster                                    SocketAddress **retaddr,
3630275e0d61SDaniel P. Berrange                                    Error **errp)
3631275e0d61SDaniel P. Berrange {
3632275e0d61SDaniel P. Berrange     int ret = -1;
3633bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3634275e0d61SDaniel P. Berrange 
3635bd269ebcSMarkus Armbruster     addr = g_new0(SocketAddress, 1);
3636275e0d61SDaniel P. Berrange 
3637275e0d61SDaniel P. Berrange     if (strncmp(addrstr, "unix:", 5) == 0) {
3638bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3639bd269ebcSMarkus Armbruster         addr->u.q_unix.path = g_strdup(addrstr + 5);
3640275e0d61SDaniel P. Berrange 
3641275e0d61SDaniel P. Berrange         if (websocket) {
3642275e0d61SDaniel P. Berrange             error_setg(errp, "UNIX sockets not supported with websock");
3643275e0d61SDaniel P. Berrange             goto cleanup;
3644275e0d61SDaniel P. Berrange         }
3645275e0d61SDaniel P. Berrange 
3646275e0d61SDaniel P. Berrange         if (to) {
3647275e0d61SDaniel P. Berrange             error_setg(errp, "Port range not support with UNIX socket");
3648275e0d61SDaniel P. Berrange             goto cleanup;
3649275e0d61SDaniel P. Berrange         }
3650275e0d61SDaniel P. Berrange         ret = 0;
3651275e0d61SDaniel P. Berrange     } else {
3652275e0d61SDaniel P. Berrange         const char *port;
3653275e0d61SDaniel P. Berrange         size_t hostlen;
3654275e0d61SDaniel P. Berrange         unsigned long long baseport = 0;
3655275e0d61SDaniel P. Berrange         InetSocketAddress *inet;
3656275e0d61SDaniel P. Berrange 
3657275e0d61SDaniel P. Berrange         port = strrchr(addrstr, ':');
3658275e0d61SDaniel P. Berrange         if (!port) {
3659275e0d61SDaniel P. Berrange             if (websocket) {
3660275e0d61SDaniel P. Berrange                 hostlen = 0;
3661275e0d61SDaniel P. Berrange                 port = addrstr;
3662275e0d61SDaniel P. Berrange             } else {
3663275e0d61SDaniel P. Berrange                 error_setg(errp, "no vnc port specified");
3664275e0d61SDaniel P. Berrange                 goto cleanup;
3665275e0d61SDaniel P. Berrange             }
3666275e0d61SDaniel P. Berrange         } else {
3667275e0d61SDaniel P. Berrange             hostlen = port - addrstr;
3668275e0d61SDaniel P. Berrange             port++;
3669275e0d61SDaniel P. Berrange             if (*port == '\0') {
3670275e0d61SDaniel P. Berrange                 error_setg(errp, "vnc port cannot be empty");
3671275e0d61SDaniel P. Berrange                 goto cleanup;
3672275e0d61SDaniel P. Berrange             }
3673275e0d61SDaniel P. Berrange         }
3674275e0d61SDaniel P. Berrange 
3675bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_INET;
3676bd269ebcSMarkus Armbruster         inet = &addr->u.inet;
3677275e0d61SDaniel P. Berrange         if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3678275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr + 1, hostlen - 2);
3679275e0d61SDaniel P. Berrange         } else {
3680275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr, hostlen);
3681275e0d61SDaniel P. Berrange         }
3682275e0d61SDaniel P. Berrange         /* plain VNC port is just an offset, for websocket
3683275e0d61SDaniel P. Berrange          * port is absolute */
3684275e0d61SDaniel P. Berrange         if (websocket) {
3685275e0d61SDaniel P. Berrange             if (g_str_equal(addrstr, "") ||
3686275e0d61SDaniel P. Berrange                 g_str_equal(addrstr, "on")) {
3687396f935aSDaniel P. Berrange                 if (displaynum == -1) {
3688396f935aSDaniel P. Berrange                     error_setg(errp, "explicit websocket port is required");
3689396f935aSDaniel P. Berrange                     goto cleanup;
3690396f935aSDaniel P. Berrange                 }
3691275e0d61SDaniel P. Berrange                 inet->port = g_strdup_printf(
3692275e0d61SDaniel P. Berrange                     "%d", displaynum + 5700);
3693275e0d61SDaniel P. Berrange                 if (to) {
3694275e0d61SDaniel P. Berrange                     inet->has_to = true;
3695275e0d61SDaniel P. Berrange                     inet->to = to + 5700;
3696275e0d61SDaniel P. Berrange                 }
3697275e0d61SDaniel P. Berrange             } else {
3698275e0d61SDaniel P. Berrange                 inet->port = g_strdup(port);
3699275e0d61SDaniel P. Berrange             }
3700275e0d61SDaniel P. Berrange         } else {
3701e5766eb4SGerd Hoffmann             int offset = reverse ? 0 : 5900;
3702275e0d61SDaniel P. Berrange             if (parse_uint_full(port, &baseport, 10) < 0) {
3703275e0d61SDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", port);
3704275e0d61SDaniel P. Berrange                 goto cleanup;
3705275e0d61SDaniel P. Berrange             }
3706275e0d61SDaniel P. Berrange             if (baseport > 65535 ||
3707e5766eb4SGerd Hoffmann                 baseport + offset > 65535) {
3708275e0d61SDaniel P. Berrange                 error_setg(errp, "port %s out of range", port);
3709275e0d61SDaniel P. Berrange                 goto cleanup;
3710275e0d61SDaniel P. Berrange             }
3711275e0d61SDaniel P. Berrange             inet->port = g_strdup_printf(
3712e5766eb4SGerd Hoffmann                 "%d", (int)baseport + offset);
3713275e0d61SDaniel P. Berrange 
3714275e0d61SDaniel P. Berrange             if (to) {
3715275e0d61SDaniel P. Berrange                 inet->has_to = true;
3716e5766eb4SGerd Hoffmann                 inet->to = to + offset;
3717275e0d61SDaniel P. Berrange             }
3718275e0d61SDaniel P. Berrange         }
3719275e0d61SDaniel P. Berrange 
3720275e0d61SDaniel P. Berrange         inet->ipv4 = ipv4;
3721275e0d61SDaniel P. Berrange         inet->has_ipv4 = has_ipv4;
3722275e0d61SDaniel P. Berrange         inet->ipv6 = ipv6;
3723275e0d61SDaniel P. Berrange         inet->has_ipv6 = has_ipv6;
3724275e0d61SDaniel P. Berrange 
3725275e0d61SDaniel P. Berrange         ret = baseport;
3726275e0d61SDaniel P. Berrange     }
3727275e0d61SDaniel P. Berrange 
3728275e0d61SDaniel P. Berrange     *retaddr = addr;
3729275e0d61SDaniel P. Berrange 
3730275e0d61SDaniel P. Berrange  cleanup:
3731275e0d61SDaniel P. Berrange     if (ret < 0) {
3732bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
3733275e0d61SDaniel P. Berrange     }
3734275e0d61SDaniel P. Berrange     return ret;
3735275e0d61SDaniel P. Berrange }
3736275e0d61SDaniel P. Berrange 
37379f26f325SPhilippe Mathieu-Daudé static void vnc_free_addresses(SocketAddress ***retsaddr,
37389f26f325SPhilippe Mathieu-Daudé                                size_t *retnsaddr)
37399f26f325SPhilippe Mathieu-Daudé {
37409f26f325SPhilippe Mathieu-Daudé     size_t i;
37419f26f325SPhilippe Mathieu-Daudé 
37429f26f325SPhilippe Mathieu-Daudé     for (i = 0; i < *retnsaddr; i++) {
37439f26f325SPhilippe Mathieu-Daudé         qapi_free_SocketAddress((*retsaddr)[i]);
37449f26f325SPhilippe Mathieu-Daudé     }
37459f26f325SPhilippe Mathieu-Daudé     g_free(*retsaddr);
37469f26f325SPhilippe Mathieu-Daudé 
37479f26f325SPhilippe Mathieu-Daudé     *retsaddr = NULL;
37489f26f325SPhilippe Mathieu-Daudé     *retnsaddr = 0;
37499f26f325SPhilippe Mathieu-Daudé }
37509f26f325SPhilippe Mathieu-Daudé 
3751275e0d61SDaniel P. Berrange static int vnc_display_get_addresses(QemuOpts *opts,
3752e5766eb4SGerd Hoffmann                                      bool reverse,
3753bd269ebcSMarkus Armbruster                                      SocketAddress ***retsaddr,
3754396f935aSDaniel P. Berrange                                      size_t *retnsaddr,
3755bd269ebcSMarkus Armbruster                                      SocketAddress ***retwsaddr,
3756396f935aSDaniel P. Berrange                                      size_t *retnwsaddr,
3757275e0d61SDaniel P. Berrange                                      Error **errp)
3758275e0d61SDaniel P. Berrange {
3759bd269ebcSMarkus Armbruster     SocketAddress *saddr = NULL;
3760bd269ebcSMarkus Armbruster     SocketAddress *wsaddr = NULL;
3761396f935aSDaniel P. Berrange     QemuOptsIter addriter;
3762396f935aSDaniel P. Berrange     const char *addr;
3763275e0d61SDaniel P. Berrange     int to = qemu_opt_get_number(opts, "to", 0);
3764275e0d61SDaniel P. Berrange     bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3765275e0d61SDaniel P. Berrange     bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3766275e0d61SDaniel P. Berrange     bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3767275e0d61SDaniel P. Berrange     bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3768396f935aSDaniel P. Berrange     int displaynum = -1;
3769396f935aSDaniel P. Berrange     int ret = -1;
3770275e0d61SDaniel P. Berrange 
3771275e0d61SDaniel P. Berrange     *retsaddr = NULL;
3772396f935aSDaniel P. Berrange     *retnsaddr = 0;
3773275e0d61SDaniel P. Berrange     *retwsaddr = NULL;
3774396f935aSDaniel P. Berrange     *retnwsaddr = 0;
3775275e0d61SDaniel P. Berrange 
3776396f935aSDaniel P. Berrange     addr = qemu_opt_get(opts, "vnc");
3777396f935aSDaniel P. Berrange     if (addr == NULL || g_str_equal(addr, "none")) {
3778396f935aSDaniel P. Berrange         ret = 0;
3779396f935aSDaniel P. Berrange         goto cleanup;
3780396f935aSDaniel P. Berrange     }
3781396f935aSDaniel P. Berrange     if (qemu_opt_get(opts, "websocket") &&
3782275e0d61SDaniel P. Berrange         !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3783275e0d61SDaniel P. Berrange         error_setg(errp,
3784275e0d61SDaniel P. Berrange                    "SHA1 hash support is required for websockets");
3785396f935aSDaniel P. Berrange         goto cleanup;
3786275e0d61SDaniel P. Berrange     }
3787275e0d61SDaniel P. Berrange 
3788396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "vnc");
3789396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3790396f935aSDaniel P. Berrange         int rv;
3791e5766eb4SGerd Hoffmann         rv = vnc_display_get_address(addr, false, reverse, 0, to,
3792275e0d61SDaniel P. Berrange                                      has_ipv4, has_ipv6,
3793275e0d61SDaniel P. Berrange                                      ipv4, ipv6,
3794275e0d61SDaniel P. Berrange                                      &saddr, errp);
3795396f935aSDaniel P. Berrange         if (rv < 0) {
3796396f935aSDaniel P. Berrange             goto cleanup;
3797275e0d61SDaniel P. Berrange         }
3798396f935aSDaniel P. Berrange         /* Historical compat - first listen address can be used
3799396f935aSDaniel P. Berrange          * to set the default websocket port
3800396f935aSDaniel P. Berrange          */
3801396f935aSDaniel P. Berrange         if (displaynum == -1) {
3802396f935aSDaniel P. Berrange             displaynum = rv;
3803396f935aSDaniel P. Berrange         }
3804bd269ebcSMarkus Armbruster         *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3805396f935aSDaniel P. Berrange         (*retsaddr)[(*retnsaddr)++] = saddr;
3806396f935aSDaniel P. Berrange     }
3807396f935aSDaniel P. Berrange 
3808396f935aSDaniel P. Berrange     /* If we had multiple primary displays, we don't do defaults
3809396f935aSDaniel P. Berrange      * for websocket, and require explicit config instead. */
3810396f935aSDaniel P. Berrange     if (*retnsaddr > 1) {
3811396f935aSDaniel P. Berrange         displaynum = -1;
3812396f935aSDaniel P. Berrange     }
3813396f935aSDaniel P. Berrange 
3814396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "websocket");
3815396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3816e5766eb4SGerd Hoffmann         if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3817275e0d61SDaniel P. Berrange                                     has_ipv4, has_ipv6,
3818275e0d61SDaniel P. Berrange                                     ipv4, ipv6,
3819275e0d61SDaniel P. Berrange                                     &wsaddr, errp) < 0) {
3820396f935aSDaniel P. Berrange             goto cleanup;
3821275e0d61SDaniel P. Berrange         }
3822396f935aSDaniel P. Berrange 
3823396f935aSDaniel P. Berrange         /* Historical compat - if only a single listen address was
3824396f935aSDaniel P. Berrange          * provided, then this is used to set the default listen
3825396f935aSDaniel P. Berrange          * address for websocket too
3826396f935aSDaniel P. Berrange          */
3827396f935aSDaniel P. Berrange         if (*retnsaddr == 1 &&
3828bd269ebcSMarkus Armbruster             (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3829bd269ebcSMarkus Armbruster             wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3830bd269ebcSMarkus Armbruster             g_str_equal(wsaddr->u.inet.host, "") &&
3831bd269ebcSMarkus Armbruster             !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3832bd269ebcSMarkus Armbruster             g_free(wsaddr->u.inet.host);
3833bd269ebcSMarkus Armbruster             wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3834275e0d61SDaniel P. Berrange         }
3835275e0d61SDaniel P. Berrange 
3836bd269ebcSMarkus Armbruster         *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3837396f935aSDaniel P. Berrange         (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3838396f935aSDaniel P. Berrange     }
3839396f935aSDaniel P. Berrange 
3840396f935aSDaniel P. Berrange     ret = 0;
3841396f935aSDaniel P. Berrange  cleanup:
3842396f935aSDaniel P. Berrange     if (ret < 0) {
38439f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retsaddr, retnsaddr);
38449f26f325SPhilippe Mathieu-Daudé         vnc_free_addresses(retwsaddr, retnwsaddr);
3845396f935aSDaniel P. Berrange     }
3846396f935aSDaniel P. Berrange     return ret;
3847275e0d61SDaniel P. Berrange }
3848275e0d61SDaniel P. Berrange 
38498bd22f47SDaniel P. Berrange static int vnc_display_connect(VncDisplay *vd,
3850bd269ebcSMarkus Armbruster                                SocketAddress **saddr,
3851396f935aSDaniel P. Berrange                                size_t nsaddr,
3852bd269ebcSMarkus Armbruster                                SocketAddress **wsaddr,
3853396f935aSDaniel P. Berrange                                size_t nwsaddr,
38548bd22f47SDaniel P. Berrange                                Error **errp)
38558bd22f47SDaniel P. Berrange {
38568bd22f47SDaniel P. Berrange     /* connect to viewer */
38578bd22f47SDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
3858396f935aSDaniel P. Berrange     if (nwsaddr != 0) {
38598bd22f47SDaniel P. Berrange         error_setg(errp, "Cannot use websockets in reverse mode");
38608bd22f47SDaniel P. Berrange         return -1;
38618bd22f47SDaniel P. Berrange     }
3862396f935aSDaniel P. Berrange     if (nsaddr != 1) {
3863396f935aSDaniel P. Berrange         error_setg(errp, "Expected a single address in reverse mode");
3864396f935aSDaniel P. Berrange         return -1;
3865396f935aSDaniel P. Berrange     }
3866bd269ebcSMarkus Armbruster     /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3867bd269ebcSMarkus Armbruster     vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
38688bd22f47SDaniel P. Berrange     sioc = qio_channel_socket_new();
38698bd22f47SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3870396f935aSDaniel P. Berrange     if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
38715f8679feSAlex Chen         object_unref(OBJECT(sioc));
38728bd22f47SDaniel P. Berrange         return -1;
38738bd22f47SDaniel P. Berrange     }
38748bd22f47SDaniel P. Berrange     vnc_connect(vd, sioc, false, false);
38758bd22f47SDaniel P. Berrange     object_unref(OBJECT(sioc));
38768bd22f47SDaniel P. Berrange     return 0;
38778bd22f47SDaniel P. Berrange }
38788bd22f47SDaniel P. Berrange 
38798bd22f47SDaniel P. Berrange 
38808bd22f47SDaniel P. Berrange static int vnc_display_listen(VncDisplay *vd,
3881bd269ebcSMarkus Armbruster                               SocketAddress **saddr,
3882396f935aSDaniel P. Berrange                               size_t nsaddr,
3883bd269ebcSMarkus Armbruster                               SocketAddress **wsaddr,
3884396f935aSDaniel P. Berrange                               size_t nwsaddr,
38858bd22f47SDaniel P. Berrange                               Error **errp)
38868bd22f47SDaniel P. Berrange {
3887396f935aSDaniel P. Berrange     size_t i;
38888bd22f47SDaniel P. Berrange 
388913e1d0e7SDaniel P. Berrange     if (nsaddr) {
389013e1d0e7SDaniel P. Berrange         vd->listener = qio_net_listener_new();
389113e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->listener, "vnc-listen");
3892396f935aSDaniel P. Berrange         for (i = 0; i < nsaddr; i++) {
389313e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->listener,
3894fc8135c6SJuan Quintela                                            saddr[i], 1,
38958bd22f47SDaniel P. Berrange                                            errp) < 0)  {
38968bd22f47SDaniel P. Berrange                 return -1;
38978bd22f47SDaniel P. Berrange             }
3898396f935aSDaniel P. Berrange         }
389913e1d0e7SDaniel P. Berrange 
390013e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->listener,
390113e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
390213e1d0e7SDaniel P. Berrange     }
390313e1d0e7SDaniel P. Berrange 
390413e1d0e7SDaniel P. Berrange     if (nwsaddr) {
390513e1d0e7SDaniel P. Berrange         vd->wslistener = qio_net_listener_new();
390613e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3907396f935aSDaniel P. Berrange         for (i = 0; i < nwsaddr; i++) {
390813e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->wslistener,
3909fc8135c6SJuan Quintela                                            wsaddr[i], 1,
39108bd22f47SDaniel P. Berrange                                            errp) < 0)  {
39118bd22f47SDaniel P. Berrange                 return -1;
39128bd22f47SDaniel P. Berrange             }
3913396f935aSDaniel P. Berrange         }
39148bd22f47SDaniel P. Berrange 
391513e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->wslistener,
391613e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
391713e1d0e7SDaniel P. Berrange     }
391813e1d0e7SDaniel P. Berrange 
39198bd22f47SDaniel P. Berrange     return 0;
39208bd22f47SDaniel P. Berrange }
39218bd22f47SDaniel P. Berrange 
39228bd22f47SDaniel P. Berrange 
39234db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
39243e230dd2SCorentin Chary {
3925bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
39264db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3927bd269ebcSMarkus Armbruster     SocketAddress **saddr = NULL, **wsaddr = NULL;
3928396f935aSDaniel P. Berrange     size_t nsaddr, nwsaddr;
3929e2a11d9dSGonglei     const char *share, *device_id;
39301d0d59feSGerd Hoffmann     QemuConsole *con;
3931a2c72de0SGonglei     bool password = false;
3932a2c72de0SGonglei     bool reverse = false;
39333e305e4aSDaniel P. Berrange     const char *credid;
3934a2c72de0SGonglei     bool sasl = false;
39353e230dd2SCorentin Chary     int acl = 0;
393655cf09a0SDaniel P. Berrange     const char *tlsauthz;
393755cf09a0SDaniel P. Berrange     const char *saslauthz;
39383e230dd2SCorentin Chary     int lock_key_sync = 1;
3939c5ce8333SGerd Hoffmann     int key_delay_ms;
3940f0b9f36dSKővágó, Zoltán     const char *audiodev;
39413e230dd2SCorentin Chary 
3942bf01c179SDaniel P. Berrange     if (!vd) {
39432d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
39442d55f0e8SPaolo Bonzini         return;
39452d55f0e8SPaolo Bonzini     }
3946bf01c179SDaniel P. Berrange     vnc_display_close(vd);
39474db14629SGerd Hoffmann 
39484db14629SGerd Hoffmann     if (!opts) {
39492d55f0e8SPaolo Bonzini         return;
39504db14629SGerd Hoffmann     }
3951275e0d61SDaniel P. Berrange 
3952e5766eb4SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
3953e5766eb4SGerd Hoffmann     if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3954396f935aSDaniel P. Berrange                                   &wsaddr, &nwsaddr, errp) < 0) {
3955275e0d61SDaniel P. Berrange         goto fail;
3956275e0d61SDaniel P. Berrange     }
3957275e0d61SDaniel P. Berrange 
39584db14629SGerd Hoffmann     password = qemu_opt_get_bool(opts, "password", false);
3959800567a6SDaniel P. Berrange     if (password) {
3960800567a6SDaniel P. Berrange         if (fips_get_state()) {
39612d55f0e8SPaolo Bonzini             error_setg(errp,
39620f66998fSPaul Moore                        "VNC password auth disabled due to FIPS mode, "
39630f66998fSPaul Moore                        "consider using the VeNCrypt or SASL authentication "
39642d55f0e8SPaolo Bonzini                        "methods as an alternative");
39651ce52c78SPaolo Bonzini             goto fail;
39660f66998fSPaul Moore         }
3967800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
3968f844836dSGonglei                 QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3969800567a6SDaniel P. Berrange             error_setg(errp,
3970800567a6SDaniel P. Berrange                        "Cipher backend does not support DES RFB algorithm");
3971800567a6SDaniel P. Berrange             goto fail;
3972800567a6SDaniel P. Berrange         }
3973800567a6SDaniel P. Berrange     }
39744db14629SGerd Hoffmann 
39754db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3976d3b0db6dSAlexander Graf     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
39774db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
3978d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
3979d169f04bSDaniel P. Berrange     if (sasl) {
3980d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3981d169f04bSDaniel P. Berrange         goto fail;
3982d169f04bSDaniel P. Berrange     }
3983d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
39843e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
39853e305e4aSDaniel P. Berrange     if (credid) {
39863e305e4aSDaniel P. Berrange         Object *creds;
39873e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
39883e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
39893e305e4aSDaniel P. Berrange         if (!creds) {
39903e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
39913e305e4aSDaniel P. Berrange                        credid);
39923e305e4aSDaniel P. Berrange             goto fail;
39933e305e4aSDaniel P. Berrange         }
3994bf01c179SDaniel P. Berrange         vd->tlscreds = (QCryptoTLSCreds *)
39953e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
39963e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
3997bf01c179SDaniel P. Berrange         if (!vd->tlscreds) {
39983e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
39993e305e4aSDaniel P. Berrange                        credid);
40003e305e4aSDaniel P. Berrange             goto fail;
40013e305e4aSDaniel P. Berrange         }
4002bf01c179SDaniel P. Berrange         object_ref(OBJECT(vd->tlscreds));
40033e305e4aSDaniel P. Berrange 
4004bf01c179SDaniel P. Berrange         if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
40053e305e4aSDaniel P. Berrange             error_setg(errp,
40063e305e4aSDaniel P. Berrange                        "Expecting TLS credentials with a server endpoint");
40073e305e4aSDaniel P. Berrange             goto fail;
40083e305e4aSDaniel P. Berrange         }
4009d169f04bSDaniel P. Berrange     }
401055cf09a0SDaniel P. Berrange     if (qemu_opt_get(opts, "acl")) {
401155cf09a0SDaniel P. Berrange         error_report("The 'acl' option to -vnc is deprecated. "
401255cf09a0SDaniel P. Berrange                      "Please use the 'tls-authz' and 'sasl-authz' "
401355cf09a0SDaniel P. Berrange                      "options instead");
401455cf09a0SDaniel P. Berrange     }
40154db14629SGerd Hoffmann     acl = qemu_opt_get_bool(opts, "acl", false);
401655cf09a0SDaniel P. Berrange     tlsauthz = qemu_opt_get(opts, "tls-authz");
401755cf09a0SDaniel P. Berrange     if (acl && tlsauthz) {
401855cf09a0SDaniel P. Berrange         error_setg(errp, "'acl' option is mutually exclusive with the "
401955cf09a0SDaniel P. Berrange                    "'tls-authz' option");
402055cf09a0SDaniel P. Berrange         goto fail;
402155cf09a0SDaniel P. Berrange     }
402255cf09a0SDaniel P. Berrange     if (tlsauthz && !vd->tlscreds) {
402355cf09a0SDaniel P. Berrange         error_setg(errp, "'tls-authz' provided but TLS is not enabled");
402455cf09a0SDaniel P. Berrange         goto fail;
402555cf09a0SDaniel P. Berrange     }
402655cf09a0SDaniel P. Berrange 
402755cf09a0SDaniel P. Berrange     saslauthz = qemu_opt_get(opts, "sasl-authz");
402855cf09a0SDaniel P. Berrange     if (acl && saslauthz) {
402955cf09a0SDaniel P. Berrange         error_setg(errp, "'acl' option is mutually exclusive with the "
403055cf09a0SDaniel P. Berrange                    "'sasl-authz' option");
403155cf09a0SDaniel P. Berrange         goto fail;
403255cf09a0SDaniel P. Berrange     }
403355cf09a0SDaniel P. Berrange     if (saslauthz && !sasl) {
403455cf09a0SDaniel P. Berrange         error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
403555cf09a0SDaniel P. Berrange         goto fail;
403655cf09a0SDaniel P. Berrange     }
40374db14629SGerd Hoffmann 
40384db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
40394db14629SGerd Hoffmann     if (share) {
40404db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
4041bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_IGNORE;
40424db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
4043bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
40444db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
4045bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
40468cf36489SGerd Hoffmann         } else {
40472d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
40481ce52c78SPaolo Bonzini             goto fail;
40498cf36489SGerd Hoffmann         }
40504db14629SGerd Hoffmann     } else {
4051bf01c179SDaniel P. Berrange         vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
40523e230dd2SCorentin Chary     }
4053bf01c179SDaniel P. Berrange     vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
40543e230dd2SCorentin Chary 
40554db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
4056bf01c179SDaniel P. Berrange     vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
40574db14629SGerd Hoffmann #endif
4058bf01c179SDaniel P. Berrange     vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4059e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
4060e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
4061e22492d3SPeter Lieven      * calculations otherwise */
4062bf01c179SDaniel P. Berrange     if (!vd->lossy) {
4063bf01c179SDaniel P. Berrange         vd->non_adaptive = true;
4064e22492d3SPeter Lieven     }
4065e22492d3SPeter Lieven 
40667b5fa0b5SDaniel P. Berrangé     vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
40677b5fa0b5SDaniel P. Berrangé 
406855cf09a0SDaniel P. Berrange     if (tlsauthz) {
406955cf09a0SDaniel P. Berrange         vd->tlsauthzid = g_strdup(tlsauthz);
407055cf09a0SDaniel P. Berrange     } else if (acl) {
4071bf01c179SDaniel P. Berrange         if (strcmp(vd->id, "default") == 0) {
4072b76806d4SDaniel P. Berrange             vd->tlsauthzid = g_strdup("vnc.x509dname");
4073c8496408SGerd Hoffmann         } else {
4074b76806d4SDaniel P. Berrange             vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
4075c8496408SGerd Hoffmann         }
4076b76806d4SDaniel P. Berrange         vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
4077b76806d4SDaniel P. Berrange                                               QAUTHZ_LIST_POLICY_DENY,
4078b76806d4SDaniel P. Berrange                                               &error_abort));
40793e230dd2SCorentin Chary     }
40803e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
408155cf09a0SDaniel P. Berrange     if (sasl) {
408255cf09a0SDaniel P. Berrange         if (saslauthz) {
408355cf09a0SDaniel P. Berrange             vd->sasl.authzid = g_strdup(saslauthz);
408455cf09a0SDaniel P. Berrange         } else if (acl) {
4085bf01c179SDaniel P. Berrange             if (strcmp(vd->id, "default") == 0) {
4086b76806d4SDaniel P. Berrange                 vd->sasl.authzid = g_strdup("vnc.username");
4087c8496408SGerd Hoffmann             } else {
4088b76806d4SDaniel P. Berrange                 vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
4089c8496408SGerd Hoffmann             }
4090b76806d4SDaniel P. Berrange             vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
4091b76806d4SDaniel P. Berrange                                                     QAUTHZ_LIST_POLICY_DENY,
4092b76806d4SDaniel P. Berrange                                                     &error_abort));
40933e230dd2SCorentin Chary         }
409455cf09a0SDaniel P. Berrange     }
40953e230dd2SCorentin Chary #endif
40963e230dd2SCorentin Chary 
4097eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4098eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4099eda24e18SDaniel P. Berrange                                sasl, false, errp) < 0) {
4100eda24e18SDaniel P. Berrange         goto fail;
4101eda24e18SDaniel P. Berrange     }
41027364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4103eda24e18SDaniel P. Berrange 
4104eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4105eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4106eda24e18SDaniel P. Berrange                                sasl, true, errp) < 0) {
41073e305e4aSDaniel P. Berrange         goto fail;
41083e305e4aSDaniel P. Berrange     }
41097364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
41103e230dd2SCorentin Chary 
41113e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
4112b5dc0d7dSMarc-André Lureau     if (sasl) {
4113b5dc0d7dSMarc-André Lureau         int saslErr = sasl_server_init(NULL, "qemu");
4114b5dc0d7dSMarc-André Lureau 
4115b5dc0d7dSMarc-André Lureau         if (saslErr != SASL_OK) {
41162d55f0e8SPaolo Bonzini             error_setg(errp, "Failed to initialize SASL auth: %s",
41173e230dd2SCorentin Chary                        sasl_errstring(saslErr, NULL, NULL));
41181ce52c78SPaolo Bonzini             goto fail;
41193e230dd2SCorentin Chary         }
4120b5dc0d7dSMarc-André Lureau     }
41213e230dd2SCorentin Chary #endif
4122bf01c179SDaniel P. Berrange     vd->lock_key_sync = lock_key_sync;
4123a54f0d2bSPierre Ossman     if (lock_key_sync) {
4124a54f0d2bSPierre Ossman         vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4125a54f0d2bSPierre Ossman     }
4126a54f0d2bSPierre Ossman     vd->ledstate = 0;
41273e230dd2SCorentin Chary 
4128f0b9f36dSKővágó, Zoltán     audiodev = qemu_opt_get(opts, "audiodev");
4129f0b9f36dSKővágó, Zoltán     if (audiodev) {
4130f0b9f36dSKővágó, Zoltán         vd->audio_state = audio_state_by_name(audiodev);
4131f0b9f36dSKővágó, Zoltán         if (!vd->audio_state) {
4132f0b9f36dSKővágó, Zoltán             error_setg(errp, "Audiodev '%s' not found", audiodev);
4133f0b9f36dSKővágó, Zoltán             goto fail;
4134f0b9f36dSKővágó, Zoltán         }
4135f0b9f36dSKővágó, Zoltán     }
4136f0b9f36dSKővágó, Zoltán 
41371d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
41381d0d59feSGerd Hoffmann     if (device_id) {
41391d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
4140f2c1d54cSGerd Hoffmann         Error *err = NULL;
41411d0d59feSGerd Hoffmann 
4142f2c1d54cSGerd Hoffmann         con = qemu_console_lookup_by_device_name(device_id, head, &err);
4143f2c1d54cSGerd Hoffmann         if (err) {
4144f2c1d54cSGerd Hoffmann             error_propagate(errp, err);
41451d0d59feSGerd Hoffmann             goto fail;
41461d0d59feSGerd Hoffmann         }
41471d0d59feSGerd Hoffmann     } else {
41481d0d59feSGerd Hoffmann         con = NULL;
41491d0d59feSGerd Hoffmann     }
41501d0d59feSGerd Hoffmann 
4151bf01c179SDaniel P. Berrange     if (con != vd->dcl.con) {
4152c2f2ba49SGerd Hoffmann         qkbd_state_free(vd->kbd);
4153bf01c179SDaniel P. Berrange         unregister_displaychangelistener(&vd->dcl);
4154bf01c179SDaniel P. Berrange         vd->dcl.con = con;
4155bf01c179SDaniel P. Berrange         register_displaychangelistener(&vd->dcl);
4156c2f2ba49SGerd Hoffmann         vd->kbd = qkbd_state_init(vd->dcl.con);
41571d0d59feSGerd Hoffmann     }
4158c2f2ba49SGerd Hoffmann     qkbd_state_set_delay(vd->kbd, key_delay_ms);
41591d0d59feSGerd Hoffmann 
4160fa03cb7fSMarc-André Lureau     if (saddr == NULL) {
4161fa03cb7fSMarc-André Lureau         goto cleanup;
4162fa03cb7fSMarc-André Lureau     }
4163fa03cb7fSMarc-André Lureau 
41643e230dd2SCorentin Chary     if (reverse) {
4165396f935aSDaniel P. Berrange         if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4166e0d03b8cSDaniel P. Berrange             goto fail;
41673e230dd2SCorentin Chary         }
41683e230dd2SCorentin Chary     } else {
4169396f935aSDaniel P. Berrange         if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
41703d00ac1aSCole Robinson             goto fail;
41713d00ac1aSCole Robinson         }
41723e230dd2SCorentin Chary     }
4173e0d03b8cSDaniel P. Berrange 
4174275e0d61SDaniel P. Berrange     if (qemu_opt_get(opts, "to")) {
4175bf01c179SDaniel P. Berrange         vnc_display_print_local_addr(vd);
417633df7bf3SPaolo Bonzini     }
417733df7bf3SPaolo Bonzini 
4178396f935aSDaniel P. Berrange  cleanup:
41799f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&saddr, &nsaddr);
41809f26f325SPhilippe Mathieu-Daudé     vnc_free_addresses(&wsaddr, &nwsaddr);
41812d55f0e8SPaolo Bonzini     return;
41821ce52c78SPaolo Bonzini 
41831ce52c78SPaolo Bonzini fail:
41844ee74fa7SDaniel P. Berrange     vnc_display_close(vd);
4185396f935aSDaniel P. Berrange     goto cleanup;
41863e230dd2SCorentin Chary }
418713661089SDaniel P. Berrange 
418814f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
418913661089SDaniel P. Berrange {
4190bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
419104d2529dSDaniel P. Berrange     QIOChannelSocket *sioc;
419213661089SDaniel P. Berrange 
4193bf01c179SDaniel P. Berrange     if (!vd) {
4194d616ccc5SGerd Hoffmann         return;
4195d616ccc5SGerd Hoffmann     }
419604d2529dSDaniel P. Berrange 
419704d2529dSDaniel P. Berrange     sioc = qio_channel_socket_new_fd(csock, NULL);
419804d2529dSDaniel P. Berrange     if (sioc) {
419910bcfe58SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4200bf01c179SDaniel P. Berrange         vnc_connect(vd, sioc, skipauth, false);
420104d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
420204d2529dSDaniel P. Berrange     }
420313661089SDaniel P. Berrange }
42044db14629SGerd Hoffmann 
42059634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
42062779672fSGonglei {
42072779672fSGonglei     int i = 2;
42082779672fSGonglei     char *id;
42092779672fSGonglei 
42102779672fSGonglei     id = g_strdup("default");
42112779672fSGonglei     while (qemu_opts_find(olist, id)) {
42122779672fSGonglei         g_free(id);
42132779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
42142779672fSGonglei     }
42152779672fSGonglei     qemu_opts_set_id(opts, id);
42162779672fSGonglei }
42172779672fSGonglei 
4218653c9747SPaolo Bonzini void vnc_parse(const char *str)
42194db14629SGerd Hoffmann {
42204db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
4221653c9747SPaolo Bonzini     QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
422281607cbfSGonglei     const char *id;
42234db14629SGerd Hoffmann 
422481607cbfSGonglei     if (!opts) {
4225653c9747SPaolo Bonzini         exit(1);
422681607cbfSGonglei     }
422781607cbfSGonglei 
422881607cbfSGonglei     id = qemu_opts_id(opts);
42294db14629SGerd Hoffmann     if (!id) {
42304db14629SGerd Hoffmann         /* auto-assign id if not present */
42312779672fSGonglei         vnc_auto_assign_id(olist, opts);
42329634f4e3SGerd Hoffmann     }
42334db14629SGerd Hoffmann }
42344db14629SGerd Hoffmann 
423528d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
42369634f4e3SGerd Hoffmann {
42379634f4e3SGerd Hoffmann     Error *local_err = NULL;
42389634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
42399634f4e3SGerd Hoffmann 
42409634f4e3SGerd Hoffmann     assert(id);
4241ab4f931eSFei Li     vnc_display_init(id, &local_err);
4242ab4f931eSFei Li     if (local_err) {
4243612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4244612aea20SMarkus Armbruster         return -1;
4245ab4f931eSFei Li     }
42464db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
42474db14629SGerd Hoffmann     if (local_err != NULL) {
4248612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4249612aea20SMarkus Armbruster         return -1;
42504db14629SGerd Hoffmann     }
42514db14629SGerd Hoffmann     return 0;
42524db14629SGerd Hoffmann }
42534db14629SGerd Hoffmann 
42544db14629SGerd Hoffmann static void vnc_register_config(void)
42554db14629SGerd Hoffmann {
42564db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
42574db14629SGerd Hoffmann }
425834294e2fSEduardo Habkost opts_init(vnc_register_config);
4259