xref: /openbmc/qemu/ui/vnc.c (revision 176adafca72ecc35e7f1f011deb52ca1ae091df6)
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"
483c52bf0cSPhilippe Mathieu-Daudé #include "crypto/tlscreds.h"
493e305e4aSDaniel P. Berrange #include "crypto/tlscredsanon.h"
503e305e4aSDaniel P. Berrange #include "crypto/tlscredsx509.h"
51f7b2502cSRichard Henderson #include "crypto/random.h"
526c6840e9SDaniel P. Berrangé #include "crypto/secret_common.h"
533e305e4aSDaniel P. Berrange #include "qom/object_interfaces.h"
54f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
55653c9747SPaolo Bonzini #include "qemu/help_option.h"
5657a6d6d5SDaniel P. Berrange #include "io/dns-resolver.h"
57756a98ddSMarc-André Lureau #include "monitor/monitor.h"
583e230dd2SCorentin Chary 
590f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
603e230dd2SCorentin Chary #define VNC_REFRESH_INTERVAL_INC  50
610f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
62999342a0SCorentin Chary static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
63999342a0SCorentin Chary static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
643e230dd2SCorentin Chary 
653e230dd2SCorentin Chary #include "vnc_keysym.h"
66800567a6SDaniel P. Berrange #include "crypto/cipher.h"
673e230dd2SCorentin Chary 
68d616ccc5SGerd Hoffmann static QTAILQ_HEAD(, VncDisplay) vnc_displays =
69d616ccc5SGerd Hoffmann     QTAILQ_HEAD_INITIALIZER(vnc_displays);
703e230dd2SCorentin Chary 
713e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs);
72e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs);
733e230dd2SCorentin Chary 
748cf36489SGerd Hoffmann static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
758cf36489SGerd Hoffmann {
768cf36489SGerd Hoffmann #ifdef _VNC_DEBUG
778cf36489SGerd Hoffmann     static const char *mn[] = {
788cf36489SGerd Hoffmann         [0]                           = "undefined",
798cf36489SGerd Hoffmann         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
808cf36489SGerd Hoffmann         [VNC_SHARE_MODE_SHARED]       = "shared",
818cf36489SGerd Hoffmann         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
828cf36489SGerd Hoffmann         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
838cf36489SGerd Hoffmann     };
8404d2529dSDaniel P. Berrange     fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
8504d2529dSDaniel P. Berrange             vs->ioc, mn[vs->share_mode], mn[mode]);
868cf36489SGerd Hoffmann #endif
878cf36489SGerd Hoffmann 
88e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
89e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
90e5f34cddSGerd Hoffmann         vs->vd->num_connecting--;
91e5f34cddSGerd Hoffmann         break;
92e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
93e5f34cddSGerd Hoffmann         vs->vd->num_shared--;
94e5f34cddSGerd Hoffmann         break;
95e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
968cf36489SGerd Hoffmann         vs->vd->num_exclusive--;
97e5f34cddSGerd Hoffmann         break;
98e5f34cddSGerd Hoffmann     default:
99e5f34cddSGerd Hoffmann         break;
1008cf36489SGerd Hoffmann     }
101e5f34cddSGerd Hoffmann 
1028cf36489SGerd Hoffmann     vs->share_mode = mode;
103e5f34cddSGerd Hoffmann 
104e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
105e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
106e5f34cddSGerd Hoffmann         vs->vd->num_connecting++;
107e5f34cddSGerd Hoffmann         break;
108e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
109e5f34cddSGerd Hoffmann         vs->vd->num_shared++;
110e5f34cddSGerd Hoffmann         break;
111e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
1128cf36489SGerd Hoffmann         vs->vd->num_exclusive++;
113e5f34cddSGerd Hoffmann         break;
114e5f34cddSGerd Hoffmann     default:
115e5f34cddSGerd Hoffmann         break;
1168cf36489SGerd Hoffmann     }
1178cf36489SGerd Hoffmann }
1188cf36489SGerd Hoffmann 
1193e230dd2SCorentin Chary 
120bd269ebcSMarkus Armbruster static void vnc_init_basic_info(SocketAddress *addr,
12198481bfcSEric Blake                                 VncBasicInfo *info,
12298481bfcSEric Blake                                 Error **errp)
1233e230dd2SCorentin Chary {
12404d2529dSDaniel P. Berrange     switch (addr->type) {
125bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_INET:
126bd269ebcSMarkus Armbruster         info->host = g_strdup(addr->u.inet.host);
127bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.inet.port);
128bd269ebcSMarkus Armbruster         if (addr->u.inet.ipv6) {
12904d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
13004d2529dSDaniel P. Berrange         } else {
13104d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
13204d2529dSDaniel P. Berrange         }
13304d2529dSDaniel P. Berrange         break;
1343e230dd2SCorentin Chary 
135bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_UNIX:
13604d2529dSDaniel P. Berrange         info->host = g_strdup("");
137bd269ebcSMarkus Armbruster         info->service = g_strdup(addr->u.q_unix.path);
13804d2529dSDaniel P. Berrange         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
13904d2529dSDaniel P. Berrange         break;
14004d2529dSDaniel P. Berrange 
141bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_VSOCK:
142bd269ebcSMarkus Armbruster     case SOCKET_ADDRESS_TYPE_FD:
143a6c76285SMarkus Armbruster         error_setg(errp, "Unsupported socket address type %s",
144977c736fSMarkus Armbruster                    SocketAddressType_str(addr->type));
14504d2529dSDaniel P. Berrange         break;
146a6c76285SMarkus Armbruster     default:
147a6c76285SMarkus Armbruster         abort();
14804d2529dSDaniel P. Berrange     }
14904d2529dSDaniel P. Berrange 
15098481bfcSEric Blake     return;
1513e230dd2SCorentin Chary }
1523e230dd2SCorentin Chary 
15304d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
15404d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
15598481bfcSEric Blake                                                  Error **errp)
1563e230dd2SCorentin Chary {
157bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1583e230dd2SCorentin Chary 
159624cdd46SDaniel P. Berrange     if (!ioc) {
160624cdd46SDaniel P. Berrange         error_setg(errp, "No listener socket available");
161624cdd46SDaniel P. Berrange         return;
162624cdd46SDaniel P. Berrange     }
163624cdd46SDaniel P. Berrange 
16404d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, errp);
16504d2529dSDaniel P. Berrange     if (!addr) {
16698481bfcSEric Blake         return;
1673e230dd2SCorentin Chary     }
1683e230dd2SCorentin Chary 
16904d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
170bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1713e230dd2SCorentin Chary }
1723e230dd2SCorentin Chary 
17304d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
17404d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
17598481bfcSEric Blake                                                  Error **errp)
1763e230dd2SCorentin Chary {
177bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
1783e230dd2SCorentin Chary 
17904d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_remote_address(ioc, errp);
18004d2529dSDaniel P. Berrange     if (!addr) {
18198481bfcSEric Blake         return;
1823e230dd2SCorentin Chary     }
1833e230dd2SCorentin Chary 
18404d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
185bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
1863e230dd2SCorentin Chary }
1873e230dd2SCorentin Chary 
1883e230dd2SCorentin Chary static const char *vnc_auth_name(VncDisplay *vd) {
1893e230dd2SCorentin Chary     switch (vd->auth) {
1903e230dd2SCorentin Chary     case VNC_AUTH_INVALID:
1913e230dd2SCorentin Chary         return "invalid";
1923e230dd2SCorentin Chary     case VNC_AUTH_NONE:
1933e230dd2SCorentin Chary         return "none";
1943e230dd2SCorentin Chary     case VNC_AUTH_VNC:
1953e230dd2SCorentin Chary         return "vnc";
1963e230dd2SCorentin Chary     case VNC_AUTH_RA2:
1973e230dd2SCorentin Chary         return "ra2";
1983e230dd2SCorentin Chary     case VNC_AUTH_RA2NE:
1993e230dd2SCorentin Chary         return "ra2ne";
2003e230dd2SCorentin Chary     case VNC_AUTH_TIGHT:
2013e230dd2SCorentin Chary         return "tight";
2023e230dd2SCorentin Chary     case VNC_AUTH_ULTRA:
2033e230dd2SCorentin Chary         return "ultra";
2043e230dd2SCorentin Chary     case VNC_AUTH_TLS:
2053e230dd2SCorentin Chary         return "tls";
2063e230dd2SCorentin Chary     case VNC_AUTH_VENCRYPT:
2073e230dd2SCorentin Chary         switch (vd->subauth) {
2083e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_PLAIN:
2093e230dd2SCorentin Chary             return "vencrypt+plain";
2103e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSNONE:
2113e230dd2SCorentin Chary             return "vencrypt+tls+none";
2123e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSVNC:
2133e230dd2SCorentin Chary             return "vencrypt+tls+vnc";
2143e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSPLAIN:
2153e230dd2SCorentin Chary             return "vencrypt+tls+plain";
2163e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509NONE:
2173e230dd2SCorentin Chary             return "vencrypt+x509+none";
2183e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509VNC:
2193e230dd2SCorentin Chary             return "vencrypt+x509+vnc";
2203e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509PLAIN:
2213e230dd2SCorentin Chary             return "vencrypt+x509+plain";
2223e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSSASL:
2233e230dd2SCorentin Chary             return "vencrypt+tls+sasl";
2243e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509SASL:
2253e230dd2SCorentin Chary             return "vencrypt+x509+sasl";
2263e230dd2SCorentin Chary         default:
2273e230dd2SCorentin Chary             return "vencrypt";
2283e230dd2SCorentin Chary         }
2293e230dd2SCorentin Chary     case VNC_AUTH_SASL:
2303e230dd2SCorentin Chary         return "sasl";
2313e230dd2SCorentin Chary     }
2323e230dd2SCorentin Chary     return "unknown";
2333e230dd2SCorentin Chary }
2343e230dd2SCorentin Chary 
235d616ccc5SGerd Hoffmann static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
2363e230dd2SCorentin Chary {
237fb6ba0d5SWenchao Xia     VncServerInfo *info;
23898481bfcSEric Blake     Error *err = NULL;
2393e230dd2SCorentin Chary 
24013e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
2414ee74fa7SDaniel P. Berrange         return NULL;
2424ee74fa7SDaniel P. Berrange     }
2434ee74fa7SDaniel P. Berrange 
2443e7f136dSDaniel P. Berrange     info = g_malloc0(sizeof(*info));
24513e1d0e7SDaniel P. Berrange     vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
246ddf21908SEric Blake                                          qapi_VncServerInfo_base(info), &err);
247d616ccc5SGerd Hoffmann     info->auth = g_strdup(vnc_auth_name(vd));
24898481bfcSEric Blake     if (err) {
24998481bfcSEric Blake         qapi_free_VncServerInfo(info);
25098481bfcSEric Blake         info = NULL;
25198481bfcSEric Blake         error_free(err);
25298481bfcSEric Blake     }
253fb6ba0d5SWenchao Xia     return info;
2543e230dd2SCorentin Chary }
2553e230dd2SCorentin Chary 
2563e230dd2SCorentin Chary static void vnc_client_cache_auth(VncState *client)
2573e230dd2SCorentin Chary {
2583e230dd2SCorentin Chary     if (!client->info) {
2593e230dd2SCorentin Chary         return;
2603e230dd2SCorentin Chary     }
2613e230dd2SCorentin Chary 
2623e305e4aSDaniel P. Berrange     if (client->tls) {
2633e305e4aSDaniel P. Berrange         client->info->x509_dname =
2643e305e4aSDaniel P. Berrange             qcrypto_tls_session_get_peer_name(client->tls);
2653e230dd2SCorentin Chary     }
2663e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
2673e230dd2SCorentin Chary     if (client->sasl.conn &&
2683e230dd2SCorentin Chary         client->sasl.username) {
269fb6ba0d5SWenchao Xia         client->info->sasl_username = g_strdup(client->sasl.username);
2703e230dd2SCorentin Chary     }
2713e230dd2SCorentin Chary #endif
2723e230dd2SCorentin Chary }
2733e230dd2SCorentin Chary 
2743e230dd2SCorentin Chary static void vnc_client_cache_addr(VncState *client)
2753e230dd2SCorentin Chary {
27698481bfcSEric Blake     Error *err = NULL;
2773e230dd2SCorentin Chary 
278fb6ba0d5SWenchao Xia     client->info = g_malloc0(sizeof(*client->info));
27904d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
280ddf21908SEric Blake                                          qapi_VncClientInfo_base(client->info),
28198481bfcSEric Blake                                          &err);
282e1b3d477SGerd Hoffmann     client->info->websocket = client->websocket;
28398481bfcSEric Blake     if (err) {
28498481bfcSEric Blake         qapi_free_VncClientInfo(client->info);
28598481bfcSEric Blake         client->info = NULL;
28698481bfcSEric Blake         error_free(err);
287fb6ba0d5SWenchao Xia     }
2883e230dd2SCorentin Chary }
2893e230dd2SCorentin Chary 
290fb6ba0d5SWenchao Xia static void vnc_qmp_event(VncState *vs, QAPIEvent event)
2913e230dd2SCorentin Chary {
292fb6ba0d5SWenchao Xia     VncServerInfo *si;
2933e230dd2SCorentin Chary 
2943e230dd2SCorentin Chary     if (!vs->info) {
2953e230dd2SCorentin Chary         return;
2963e230dd2SCorentin Chary     }
2973e230dd2SCorentin Chary 
298d616ccc5SGerd Hoffmann     si = vnc_server_info_get(vs->vd);
299fb6ba0d5SWenchao Xia     if (!si) {
3003e230dd2SCorentin Chary         return;
3013e230dd2SCorentin Chary     }
3023e230dd2SCorentin Chary 
303fb6ba0d5SWenchao Xia     switch (event) {
304fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_CONNECTED:
3053ab72385SPeter Xu         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
306fb6ba0d5SWenchao Xia         break;
307fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_INITIALIZED:
3083ab72385SPeter Xu         qapi_event_send_vnc_initialized(si, vs->info);
309fb6ba0d5SWenchao Xia         break;
310fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_DISCONNECTED:
3113ab72385SPeter Xu         qapi_event_send_vnc_disconnected(si, vs->info);
312fb6ba0d5SWenchao Xia         break;
313fb6ba0d5SWenchao Xia     default:
314fb6ba0d5SWenchao Xia         break;
315fb6ba0d5SWenchao Xia     }
3163e230dd2SCorentin Chary 
317fb6ba0d5SWenchao Xia     qapi_free_VncServerInfo(si);
3183e230dd2SCorentin Chary }
3193e230dd2SCorentin Chary 
3202b54aa87SLuiz Capitulino static VncClientInfo *qmp_query_vnc_client(const VncState *client)
3213e230dd2SCorentin Chary {
3222b54aa87SLuiz Capitulino     VncClientInfo *info;
32304d2529dSDaniel P. Berrange     Error *err = NULL;
3242b54aa87SLuiz Capitulino 
3252b54aa87SLuiz Capitulino     info = g_malloc0(sizeof(*info));
32604d2529dSDaniel P. Berrange 
32704d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
32804d2529dSDaniel P. Berrange                                          qapi_VncClientInfo_base(info),
32904d2529dSDaniel P. Berrange                                          &err);
33004d2529dSDaniel P. Berrange     if (err) {
33104d2529dSDaniel P. Berrange         error_free(err);
33204d2529dSDaniel P. Berrange         qapi_free_VncClientInfo(info);
33304d2529dSDaniel P. Berrange         return NULL;
33404d2529dSDaniel P. Berrange     }
33504d2529dSDaniel P. Berrange 
336ddf21908SEric Blake     info->websocket = client->websocket;
3373e230dd2SCorentin Chary 
3383e305e4aSDaniel P. Berrange     if (client->tls) {
3393e305e4aSDaniel P. Berrange         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
3402b54aa87SLuiz Capitulino     }
3413e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
3422b54aa87SLuiz Capitulino     if (client->sasl.conn && client->sasl.username) {
3432b54aa87SLuiz Capitulino         info->sasl_username = g_strdup(client->sasl.username);
3442b54aa87SLuiz Capitulino     }
3453e230dd2SCorentin Chary #endif
3462b54aa87SLuiz Capitulino 
3472b54aa87SLuiz Capitulino     return info;
3483e230dd2SCorentin Chary }
3493e230dd2SCorentin Chary 
350d616ccc5SGerd Hoffmann static VncDisplay *vnc_display_find(const char *id)
351d616ccc5SGerd Hoffmann {
352d616ccc5SGerd Hoffmann     VncDisplay *vd;
353d616ccc5SGerd Hoffmann 
354d616ccc5SGerd Hoffmann     if (id == NULL) {
355d616ccc5SGerd Hoffmann         return QTAILQ_FIRST(&vnc_displays);
356d616ccc5SGerd Hoffmann     }
357d616ccc5SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
358d616ccc5SGerd Hoffmann         if (strcmp(id, vd->id) == 0) {
359d616ccc5SGerd Hoffmann             return vd;
360d616ccc5SGerd Hoffmann         }
361d616ccc5SGerd Hoffmann     }
362d616ccc5SGerd Hoffmann     return NULL;
363d616ccc5SGerd Hoffmann }
364d616ccc5SGerd Hoffmann 
3652d29a436SGerd Hoffmann static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
3662d29a436SGerd Hoffmann {
36754aa3de7SEric Blake     VncClientInfoList *prev = NULL;
3682d29a436SGerd Hoffmann     VncState *client;
3692d29a436SGerd Hoffmann 
3702d29a436SGerd Hoffmann     QTAILQ_FOREACH(client, &vd->clients, next) {
37154aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, qmp_query_vnc_client(client));
3722d29a436SGerd Hoffmann     }
3732d29a436SGerd Hoffmann     return prev;
3742d29a436SGerd Hoffmann }
3752d29a436SGerd Hoffmann 
3762b54aa87SLuiz Capitulino VncInfo *qmp_query_vnc(Error **errp)
3773e230dd2SCorentin Chary {
3782b54aa87SLuiz Capitulino     VncInfo *info = g_malloc0(sizeof(*info));
379d616ccc5SGerd Hoffmann     VncDisplay *vd = vnc_display_find(NULL);
380bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3813e230dd2SCorentin Chary 
38213e1d0e7SDaniel P. Berrange     if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
3832b54aa87SLuiz Capitulino         info->enabled = false;
3843e230dd2SCorentin Chary     } else {
3852b54aa87SLuiz Capitulino         info->enabled = true;
3862b54aa87SLuiz Capitulino 
3872b54aa87SLuiz Capitulino         /* for compatibility with the original command */
3882b54aa87SLuiz Capitulino         info->has_clients = true;
3892d29a436SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
3903e230dd2SCorentin Chary 
39113e1d0e7SDaniel P. Berrange         addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
39213e1d0e7SDaniel P. Berrange                                                     errp);
39304d2529dSDaniel P. Berrange         if (!addr) {
3942b54aa87SLuiz Capitulino             goto out_error;
3952b54aa87SLuiz Capitulino         }
3963e230dd2SCorentin Chary 
39704d2529dSDaniel P. Berrange         switch (addr->type) {
398bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_INET:
399bd269ebcSMarkus Armbruster             info->host = g_strdup(addr->u.inet.host);
400bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.inet.port);
401bd269ebcSMarkus Armbruster             if (addr->u.inet.ipv6) {
40204d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
40304d2529dSDaniel P. Berrange             } else {
40404d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
40504d2529dSDaniel P. Berrange             }
40604d2529dSDaniel P. Berrange             break;
40704d2529dSDaniel P. Berrange 
408bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_UNIX:
40904d2529dSDaniel P. Berrange             info->host = g_strdup("");
410bd269ebcSMarkus Armbruster             info->service = g_strdup(addr->u.q_unix.path);
41104d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
41204d2529dSDaniel P. Berrange             break;
41304d2529dSDaniel P. Berrange 
414bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_VSOCK:
415bd269ebcSMarkus Armbruster         case SOCKET_ADDRESS_TYPE_FD:
416a6c76285SMarkus Armbruster             error_setg(errp, "Unsupported socket address type %s",
417977c736fSMarkus Armbruster                        SocketAddressType_str(addr->type));
4182b54aa87SLuiz Capitulino             goto out_error;
419a6c76285SMarkus Armbruster         default:
420a6c76285SMarkus Armbruster             abort();
4213e230dd2SCorentin Chary         }
4222b54aa87SLuiz Capitulino 
4232b54aa87SLuiz Capitulino         info->has_family = true;
4242b54aa87SLuiz Capitulino 
425d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4263e230dd2SCorentin Chary     }
4272b54aa87SLuiz Capitulino 
428bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4292b54aa87SLuiz Capitulino     return info;
4302b54aa87SLuiz Capitulino 
4312b54aa87SLuiz Capitulino out_error:
432bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
4332b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4342b54aa87SLuiz Capitulino     return NULL;
4353e230dd2SCorentin Chary }
4363e230dd2SCorentin Chary 
4372a7e6857SDaniel P. Berrange 
4382a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4392a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4402a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4412a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt);
4422a7e6857SDaniel P. Berrange 
4432a7e6857SDaniel P. Berrange static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
4444478aa76SGerd Hoffmann                                                   bool websocket,
4452a7e6857SDaniel P. Berrange                                                   int auth,
4462a7e6857SDaniel P. Berrange                                                   int subauth,
4472a7e6857SDaniel P. Berrange                                                   VncServerInfo2List *prev)
448df887684SGerd Hoffmann {
4492a7e6857SDaniel P. Berrange     VncServerInfo2 *info;
45004d2529dSDaniel P. Berrange     Error *err = NULL;
451bd269ebcSMarkus Armbruster     SocketAddress *addr;
452df887684SGerd Hoffmann 
4539261ef5eSMarkus Armbruster     addr = qio_channel_socket_get_local_address(ioc, NULL);
45404d2529dSDaniel P. Berrange     if (!addr) {
455df887684SGerd Hoffmann         return prev;
456df887684SGerd Hoffmann     }
457df887684SGerd Hoffmann 
4582a7e6857SDaniel P. Berrange     info = g_new0(VncServerInfo2, 1);
4592a7e6857SDaniel P. Berrange     vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
460bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
46104d2529dSDaniel P. Berrange     if (err) {
4622a7e6857SDaniel P. Berrange         qapi_free_VncServerInfo2(info);
46304d2529dSDaniel P. Berrange         error_free(err);
46404d2529dSDaniel P. Berrange         return prev;
46504d2529dSDaniel P. Berrange     }
4664478aa76SGerd Hoffmann     info->websocket = websocket;
467df887684SGerd Hoffmann 
4682a7e6857SDaniel P. Berrange     qmp_query_auth(auth, subauth, &info->auth,
4692a7e6857SDaniel P. Berrange                    &info->vencrypt, &info->has_vencrypt);
4702a7e6857SDaniel P. Berrange 
47154aa3de7SEric Blake     QAPI_LIST_PREPEND(prev, info);
47254aa3de7SEric Blake     return prev;
473df887684SGerd Hoffmann }
474df887684SGerd Hoffmann 
4752a7e6857SDaniel P. Berrange static void qmp_query_auth(int auth, int subauth,
4762a7e6857SDaniel P. Berrange                            VncPrimaryAuth *qmp_auth,
4772a7e6857SDaniel P. Berrange                            VncVencryptSubAuth *qmp_vencrypt,
4782a7e6857SDaniel P. Berrange                            bool *qmp_has_vencrypt)
479df887684SGerd Hoffmann {
4802a7e6857SDaniel P. Berrange     switch (auth) {
481df887684SGerd Hoffmann     case VNC_AUTH_VNC:
4822a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VNC;
483df887684SGerd Hoffmann         break;
484df887684SGerd Hoffmann     case VNC_AUTH_RA2:
4852a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2;
486df887684SGerd Hoffmann         break;
487df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
4882a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
489df887684SGerd Hoffmann         break;
490df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
4912a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
492df887684SGerd Hoffmann         break;
493df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
4942a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
495df887684SGerd Hoffmann         break;
496df887684SGerd Hoffmann     case VNC_AUTH_TLS:
4972a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_TLS;
498df887684SGerd Hoffmann         break;
499df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
5002a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
5012a7e6857SDaniel P. Berrange         *qmp_has_vencrypt = true;
5022a7e6857SDaniel P. Berrange         switch (subauth) {
503df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
5042a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
505df887684SGerd Hoffmann             break;
506df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
5072a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
508df887684SGerd Hoffmann             break;
509df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
5102a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
511df887684SGerd Hoffmann             break;
512df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
5132a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
514df887684SGerd Hoffmann             break;
515df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
5162a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
517df887684SGerd Hoffmann             break;
518df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
5192a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
520df887684SGerd Hoffmann             break;
521df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
5222a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
523df887684SGerd Hoffmann             break;
524df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
5252a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
526df887684SGerd Hoffmann             break;
527df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
5282a7e6857SDaniel P. Berrange             *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
529df887684SGerd Hoffmann             break;
530df887684SGerd Hoffmann         default:
5312a7e6857SDaniel P. Berrange             *qmp_has_vencrypt = false;
532df887684SGerd Hoffmann             break;
533df887684SGerd Hoffmann         }
534df887684SGerd Hoffmann         break;
535df887684SGerd Hoffmann     case VNC_AUTH_SASL:
5362a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_SASL;
537df887684SGerd Hoffmann         break;
538df887684SGerd Hoffmann     case VNC_AUTH_NONE:
539df887684SGerd Hoffmann     default:
5402a7e6857SDaniel P. Berrange         *qmp_auth = VNC_PRIMARY_AUTH_NONE;
541df887684SGerd Hoffmann         break;
542df887684SGerd Hoffmann     }
543df887684SGerd Hoffmann }
544df887684SGerd Hoffmann 
545df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
546df887684SGerd Hoffmann {
54754aa3de7SEric Blake     VncInfo2List *prev = NULL;
548df887684SGerd Hoffmann     VncInfo2 *info;
549df887684SGerd Hoffmann     VncDisplay *vd;
550df887684SGerd Hoffmann     DeviceState *dev;
5514ee74fa7SDaniel P. Berrange     size_t i;
552df887684SGerd Hoffmann 
553df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
554df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
555df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
556df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
5572a7e6857SDaniel P. Berrange         qmp_query_auth(vd->auth, vd->subauth, &info->auth,
5582a7e6857SDaniel P. Berrange                        &info->vencrypt, &info->has_vencrypt);
559df887684SGerd Hoffmann         if (vd->dcl.con) {
560df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
561552d7f49SMarkus Armbruster                                                   "device", &error_abort));
562df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
563df887684SGerd Hoffmann         }
56413e1d0e7SDaniel P. Berrange         for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
56504d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
56613e1d0e7SDaniel P. Berrange                 vd->listener->sioc[i], false, vd->auth, vd->subauth,
56713e1d0e7SDaniel P. Berrange                 info->server);
568df887684SGerd Hoffmann         }
56913e1d0e7SDaniel P. Berrange         for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
57004d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
57113e1d0e7SDaniel P. Berrange                 vd->wslistener->sioc[i], true, vd->ws_auth,
5724ee74fa7SDaniel P. Berrange                 vd->ws_subauth, info->server);
573df887684SGerd Hoffmann         }
574df887684SGerd Hoffmann 
57554aa3de7SEric Blake         QAPI_LIST_PREPEND(prev, info);
576df887684SGerd Hoffmann     }
577df887684SGerd Hoffmann     return prev;
578df887684SGerd Hoffmann }
579df887684SGerd Hoffmann 
5801f08e341SZihao Chang bool vnc_display_reload_certs(const char *id, Error **errp)
5811f08e341SZihao Chang {
5821f08e341SZihao Chang     VncDisplay *vd = vnc_display_find(id);
5831f08e341SZihao Chang     QCryptoTLSCredsClass *creds = NULL;
5841f08e341SZihao Chang 
5851f08e341SZihao Chang     if (!vd) {
5861f08e341SZihao Chang         error_setg(errp, "Can not find vnc display");
5871f08e341SZihao Chang         return false;
5881f08e341SZihao Chang     }
5891f08e341SZihao Chang 
5901f08e341SZihao Chang     if (!vd->tlscreds) {
5914087ecb8SMichael Tokarev         error_setg(errp, "vnc tls is not enabled");
5921f08e341SZihao Chang         return false;
5931f08e341SZihao Chang     }
5941f08e341SZihao Chang 
5951f08e341SZihao Chang     creds = QCRYPTO_TLS_CREDS_GET_CLASS(OBJECT(vd->tlscreds));
5961f08e341SZihao Chang     if (creds->reload == NULL) {
5971f08e341SZihao Chang         error_setg(errp, "%s doesn't support to reload TLS credential",
5981f08e341SZihao Chang                    object_get_typename(OBJECT(vd->tlscreds)));
5991f08e341SZihao Chang         return false;
6001f08e341SZihao Chang     }
6011f08e341SZihao Chang     if (!creds->reload(vd->tlscreds, errp)) {
6021f08e341SZihao Chang         return false;
6031f08e341SZihao Chang     }
6041f08e341SZihao Chang 
6051f08e341SZihao Chang     return true;
6061f08e341SZihao Chang }
6071f08e341SZihao Chang 
6083e230dd2SCorentin Chary /* TODO
6093e230dd2SCorentin Chary    1) Get the queue working for IO.
6103e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
6113e230dd2SCorentin Chary       and not totally invalidated
6123e230dd2SCorentin Chary    3) resolutions > 1024
6133e230dd2SCorentin Chary */
6143e230dd2SCorentin Chary 
6156af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty);
6163e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
6173e230dd2SCorentin Chary 
6183e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
6193e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
6203e230dd2SCorentin Chary                                        int x_position, int y_position,
6213e230dd2SCorentin Chary                                        int w, int h);
6220f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
6233e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
6243e230dd2SCorentin Chary 
625d05959c2SGerd Hoffmann static int vnc_width(VncDisplay *vd)
626d05959c2SGerd Hoffmann {
627d05959c2SGerd Hoffmann     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
628d05959c2SGerd Hoffmann                                        VNC_DIRTY_PIXELS_PER_BIT));
629d05959c2SGerd Hoffmann }
630d05959c2SGerd Hoffmann 
63169cc8db4SDaniel P. Berrangé static int vnc_true_width(VncDisplay *vd)
63269cc8db4SDaniel P. Berrangé {
63369cc8db4SDaniel P. Berrangé     return MIN(VNC_MAX_WIDTH, surface_width(vd->ds));
63469cc8db4SDaniel P. Berrangé }
63569cc8db4SDaniel P. Berrangé 
636d05959c2SGerd Hoffmann static int vnc_height(VncDisplay *vd)
637d05959c2SGerd Hoffmann {
638d05959c2SGerd Hoffmann     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
639d05959c2SGerd Hoffmann }
640d05959c2SGerd Hoffmann 
641bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
642bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
643f7b3d68cSGerd Hoffmann                                VncDisplay *vd,
644f7b3d68cSGerd Hoffmann                                int x, int y, int w, int h)
645f7b3d68cSGerd Hoffmann {
646f7b3d68cSGerd Hoffmann     int width = vnc_width(vd);
647f7b3d68cSGerd Hoffmann     int height = vnc_height(vd);
648f7b3d68cSGerd Hoffmann 
64991937225SPeter Lieven     /* this is needed this to ensure we updated all affected
65091937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
651b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
652b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6533e230dd2SCorentin Chary 
6549f64916dSGerd Hoffmann     x = MIN(x, width);
6559f64916dSGerd Hoffmann     y = MIN(y, height);
6569f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
65791937225SPeter Lieven     h = MIN(y + h, height);
6583e230dd2SCorentin Chary 
659b4c85ddcSPeter Lieven     for (; y < h; y++) {
660bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
66191937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
662b4c85ddcSPeter Lieven     }
6633e230dd2SCorentin Chary }
6643e230dd2SCorentin Chary 
665bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
666bea60dd7SPeter Lieven                            int x, int y, int w, int h)
667bea60dd7SPeter Lieven {
668bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
669bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
670bea60dd7SPeter Lieven 
671f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
672bea60dd7SPeter Lieven }
673bea60dd7SPeter Lieven 
6743e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6753e230dd2SCorentin Chary                             int32_t encoding)
6763e230dd2SCorentin Chary {
6773e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6783e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6793e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6803e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6813e230dd2SCorentin Chary 
6823e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6833e230dd2SCorentin Chary }
6843e230dd2SCorentin Chary 
685763deea7SGerd Hoffmann static void vnc_desktop_resize_ext(VncState *vs, int reject_reason)
686763deea7SGerd Hoffmann {
687adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_ext_desktop_resize(
688adc8fce8SDaniel P. Berrangé         vs, vs->ioc, vs->client_width, vs->client_height, reject_reason);
689adc8fce8SDaniel P. Berrangé 
690763deea7SGerd Hoffmann     vnc_lock_output(vs);
691763deea7SGerd Hoffmann     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
692763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);
693763deea7SGerd Hoffmann     vnc_write_u16(vs, 1); /* number of rects */
694763deea7SGerd Hoffmann     vnc_framebuffer_update(vs,
695763deea7SGerd Hoffmann                            reject_reason ? 1 : 0,
696763deea7SGerd Hoffmann                            reject_reason,
697763deea7SGerd Hoffmann                            vs->client_width, vs->client_height,
698763deea7SGerd Hoffmann                            VNC_ENCODING_DESKTOP_RESIZE_EXT);
699763deea7SGerd Hoffmann     vnc_write_u8(vs, 1);  /* number of screens */
700763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
701763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
702763deea7SGerd Hoffmann     vnc_write_u8(vs, 0);  /* padding */
703763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen id */
704763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen x-pos */
705763deea7SGerd Hoffmann     vnc_write_u16(vs, 0); /* screen y-pos */
706763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_width);
707763deea7SGerd Hoffmann     vnc_write_u16(vs, vs->client_height);
708763deea7SGerd Hoffmann     vnc_write_u32(vs, 0); /* screen flags */
709763deea7SGerd Hoffmann     vnc_unlock_output(vs);
710763deea7SGerd Hoffmann     vnc_flush(vs);
711763deea7SGerd Hoffmann }
71232ed2680STim Hardeck 
7133e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
7143e230dd2SCorentin Chary {
715763deea7SGerd Hoffmann     if (vs->ioc == NULL || (!vnc_has_feature(vs, VNC_FEATURE_RESIZE) &&
716763deea7SGerd Hoffmann                             !vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT))) {
7173e230dd2SCorentin Chary         return;
7183e230dd2SCorentin Chary     }
71969cc8db4SDaniel P. Berrangé     if (vs->client_width == vs->vd->true_width &&
720d239726cSGerd Hoffmann         vs->client_height == pixman_image_get_height(vs->vd->server)) {
721d239726cSGerd Hoffmann         return;
722d239726cSGerd Hoffmann     }
7234c956bd8SDaniel P. Berrange 
72469cc8db4SDaniel P. Berrangé     assert(vs->vd->true_width < 65536 &&
72569cc8db4SDaniel P. Berrangé            vs->vd->true_width >= 0);
7264c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
7274c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
72869cc8db4SDaniel P. Berrangé     vs->client_width = vs->vd->true_width;
729bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
730763deea7SGerd Hoffmann 
731763deea7SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
732763deea7SGerd Hoffmann         vnc_desktop_resize_ext(vs, 0);
733763deea7SGerd Hoffmann         return;
734763deea7SGerd Hoffmann     }
735763deea7SGerd Hoffmann 
736adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_desktop_resize(
737adc8fce8SDaniel P. Berrangé         vs, vs->ioc, vs->client_width, vs->client_height);
738adc8fce8SDaniel P. Berrangé 
739bd023f95SCorentin Chary     vnc_lock_output(vs);
7403e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
7413e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
7423e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
7433e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
7443e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
745bd023f95SCorentin Chary     vnc_unlock_output(vs);
7463e230dd2SCorentin Chary     vnc_flush(vs);
7473e230dd2SCorentin Chary }
7483e230dd2SCorentin Chary 
749bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
750bd023f95SCorentin Chary {
751bd023f95SCorentin Chary     VncState *vs;
752bd023f95SCorentin Chary 
753bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
754bd023f95SCorentin Chary         vnc_lock_output(vs);
755bd023f95SCorentin Chary         vs->abort = true;
756bd023f95SCorentin Chary         vnc_unlock_output(vs);
757bd023f95SCorentin Chary     }
758bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
759bd023f95SCorentin Chary         vnc_jobs_join(vs);
760bd023f95SCorentin Chary     }
761bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
762bd023f95SCorentin Chary         vnc_lock_output(vs);
763bbcdeb62SGerd Hoffmann         if (vs->update == VNC_STATE_UPDATE_NONE &&
764bbcdeb62SGerd Hoffmann             vs->job_update != VNC_STATE_UPDATE_NONE) {
765bbcdeb62SGerd Hoffmann             /* job aborted before completion */
766bbcdeb62SGerd Hoffmann             vs->update = vs->job_update;
767bbcdeb62SGerd Hoffmann             vs->job_update = VNC_STATE_UPDATE_NONE;
768bbcdeb62SGerd Hoffmann         }
769bd023f95SCorentin Chary         vs->abort = false;
770bd023f95SCorentin Chary         vnc_unlock_output(vs);
771bd023f95SCorentin Chary     }
772bd023f95SCorentin Chary }
773bd023f95SCorentin Chary 
7749f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
7759f64916dSGerd Hoffmann {
7769f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
7779f64916dSGerd Hoffmann }
7789f64916dSGerd Hoffmann 
7799f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
7809f64916dSGerd Hoffmann {
7819f64916dSGerd Hoffmann     uint8_t *ptr;
7829f64916dSGerd Hoffmann 
7839f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
7849f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
7859f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
7869f64916dSGerd Hoffmann     return ptr;
7879f64916dSGerd Hoffmann }
7889f64916dSGerd Hoffmann 
789453f842bSGerd Hoffmann static void vnc_update_server_surface(VncDisplay *vd)
790453f842bSGerd Hoffmann {
791b69a553bSDaniel P. Berrange     int width, height;
792b69a553bSDaniel P. Berrange 
793453f842bSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
794453f842bSGerd Hoffmann     vd->server = NULL;
795453f842bSGerd Hoffmann 
796c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vd->clients)) {
797c7628bffSGerd Hoffmann         return;
798c7628bffSGerd Hoffmann     }
799c7628bffSGerd Hoffmann 
800b69a553bSDaniel P. Berrange     width = vnc_width(vd);
801b69a553bSDaniel P. Berrange     height = vnc_height(vd);
80269cc8db4SDaniel P. Berrangé     vd->true_width = vnc_true_width(vd);
803453f842bSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
804b69a553bSDaniel P. Berrange                                           width, height,
805453f842bSGerd Hoffmann                                           NULL, 0);
806b69a553bSDaniel P. Berrange 
807b69a553bSDaniel P. Berrange     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
808b69a553bSDaniel P. Berrange     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
809b69a553bSDaniel P. Berrange                        width, height);
810453f842bSGerd Hoffmann }
811453f842bSGerd Hoffmann 
81261e77a5fSGerd Hoffmann static bool vnc_check_pageflip(DisplaySurface *s1,
81361e77a5fSGerd Hoffmann                                DisplaySurface *s2)
81461e77a5fSGerd Hoffmann {
81561e77a5fSGerd Hoffmann     return (s1 != NULL &&
81661e77a5fSGerd Hoffmann             s2 != NULL &&
81761e77a5fSGerd Hoffmann             surface_width(s1) == surface_width(s2) &&
81861e77a5fSGerd Hoffmann             surface_height(s1) == surface_height(s2) &&
81961e77a5fSGerd Hoffmann             surface_format(s1) == surface_format(s2));
82061e77a5fSGerd Hoffmann 
82161e77a5fSGerd Hoffmann }
82261e77a5fSGerd Hoffmann 
823c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
824c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
8253e230dd2SCorentin Chary {
82621ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
82761e77a5fSGerd Hoffmann     bool pageflip = vnc_check_pageflip(vd->ds, surface);
8283e230dd2SCorentin Chary     VncState *vs;
8293e230dd2SCorentin Chary 
830bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
831453f842bSGerd Hoffmann     vd->ds = surface;
832bd023f95SCorentin Chary 
8333e230dd2SCorentin Chary     /* guest surface */
8349f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
835d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
836ff174c67SMarc-André Lureau     vd->guest.format = surface_format(surface);
8373e230dd2SCorentin Chary 
83869cc8db4SDaniel P. Berrangé 
83961e77a5fSGerd Hoffmann     if (pageflip) {
84069cc8db4SDaniel P. Berrangé         trace_vnc_server_dpy_pageflip(vd,
84169cc8db4SDaniel P. Berrangé                                       surface_width(surface),
84269cc8db4SDaniel P. Berrangé                                       surface_height(surface),
84369cc8db4SDaniel P. Berrangé                                       surface_format(surface));
84461e77a5fSGerd Hoffmann         vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
84561e77a5fSGerd Hoffmann                            surface_width(surface),
84661e77a5fSGerd Hoffmann                            surface_height(surface));
84761e77a5fSGerd Hoffmann         return;
84861e77a5fSGerd Hoffmann     }
84961e77a5fSGerd Hoffmann 
85069cc8db4SDaniel P. Berrangé     trace_vnc_server_dpy_recreate(vd,
85169cc8db4SDaniel P. Berrangé                                   surface_width(surface),
85269cc8db4SDaniel P. Berrangé                                   surface_height(surface),
85369cc8db4SDaniel P. Berrangé                                   surface_format(surface));
85461e77a5fSGerd Hoffmann     /* server surface */
85561e77a5fSGerd Hoffmann     vnc_update_server_surface(vd);
85661e77a5fSGerd Hoffmann 
8573e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
8583e230dd2SCorentin Chary         vnc_colordepth(vs);
8593e230dd2SCorentin Chary         vnc_desktop_resize(vs);
8603e230dd2SCorentin Chary         vnc_cursor_define(vs);
861bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
862f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
863b69a553bSDaniel P. Berrange                            vnc_width(vd),
864b69a553bSDaniel P. Berrange                            vnc_height(vd));
865e2b72cb6SDaniel P. Berrange         vnc_update_throttle_offset(vs);
8663e230dd2SCorentin Chary     }
8673e230dd2SCorentin Chary }
8683e230dd2SCorentin Chary 
8693e230dd2SCorentin Chary /* fastest code */
8709f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
8713e230dd2SCorentin Chary                                   void *pixels, int size)
8723e230dd2SCorentin Chary {
8733e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
8743e230dd2SCorentin Chary }
8753e230dd2SCorentin Chary 
8763e230dd2SCorentin Chary /* slowest but generic code. */
8773e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
8783e230dd2SCorentin Chary {
8793e230dd2SCorentin Chary     uint8_t r, g, b;
8803e230dd2SCorentin Chary 
8819f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
8829f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
8839f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
8849f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
8859f64916dSGerd Hoffmann #else
8869f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
8879f64916dSGerd Hoffmann #endif
8889f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
8899f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
8909f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
8919f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
8923e230dd2SCorentin Chary     case 1:
8933e230dd2SCorentin Chary         buf[0] = v;
8943e230dd2SCorentin Chary         break;
8953e230dd2SCorentin Chary     case 2:
8969f64916dSGerd Hoffmann         if (vs->client_be) {
8973e230dd2SCorentin Chary             buf[0] = v >> 8;
8983e230dd2SCorentin Chary             buf[1] = v;
8993e230dd2SCorentin Chary         } else {
9003e230dd2SCorentin Chary             buf[1] = v >> 8;
9013e230dd2SCorentin Chary             buf[0] = v;
9023e230dd2SCorentin Chary         }
9033e230dd2SCorentin Chary         break;
9043e230dd2SCorentin Chary     default:
9053e230dd2SCorentin Chary     case 4:
9069f64916dSGerd Hoffmann         if (vs->client_be) {
9073e230dd2SCorentin Chary             buf[0] = v >> 24;
9083e230dd2SCorentin Chary             buf[1] = v >> 16;
9093e230dd2SCorentin Chary             buf[2] = v >> 8;
9103e230dd2SCorentin Chary             buf[3] = v;
9113e230dd2SCorentin Chary         } else {
9123e230dd2SCorentin Chary             buf[3] = v >> 24;
9133e230dd2SCorentin Chary             buf[2] = v >> 16;
9143e230dd2SCorentin Chary             buf[1] = v >> 8;
9153e230dd2SCorentin Chary             buf[0] = v;
9163e230dd2SCorentin Chary         }
9173e230dd2SCorentin Chary         break;
9183e230dd2SCorentin Chary     }
9193e230dd2SCorentin Chary }
9203e230dd2SCorentin Chary 
9219f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
9223e230dd2SCorentin Chary                                      void *pixels1, int size)
9233e230dd2SCorentin Chary {
9243e230dd2SCorentin Chary     uint8_t buf[4];
9253e230dd2SCorentin Chary 
9269f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
9273e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
9283e230dd2SCorentin Chary         int n, i;
9293e230dd2SCorentin Chary         n = size >> 2;
9303e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
9313e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
9329f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
9333e230dd2SCorentin Chary         }
9343e230dd2SCorentin Chary     }
9353e230dd2SCorentin Chary }
9363e230dd2SCorentin Chary 
9373e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9383e230dd2SCorentin Chary {
9393e230dd2SCorentin Chary     int i;
9403e230dd2SCorentin Chary     uint8_t *row;
9413e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
9423e230dd2SCorentin Chary 
9439f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
9443e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
9459f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
9469f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
9473e230dd2SCorentin Chary     }
9483e230dd2SCorentin Chary     return 1;
9493e230dd2SCorentin Chary }
9503e230dd2SCorentin Chary 
951bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
9523e230dd2SCorentin Chary {
9533e230dd2SCorentin Chary     int n = 0;
9543e230dd2SCorentin Chary 
9553e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
9563e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
9573e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
9583e230dd2SCorentin Chary             break;
9593e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
9603e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
9613e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
9623e230dd2SCorentin Chary             break;
9633e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
9643e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
9653e230dd2SCorentin Chary             break;
966efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
967efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
968efe556adSCorentin Chary             break;
969148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
970148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
971148954faSCorentin Chary             break;
972148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
973148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
974148954faSCorentin Chary             break;
9753e230dd2SCorentin Chary         default:
976de3f7de7SPeter Lieven             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
977de3f7de7SPeter Lieven             n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
9780780ec7bSGerd Hoffmann             break;
979de3f7de7SPeter Lieven     }
9803e230dd2SCorentin Chary     return n;
9813e230dd2SCorentin Chary }
9823e230dd2SCorentin Chary 
9837c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9847c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9853e230dd2SCorentin Chary {
9863e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9873e230dd2SCorentin Chary }
9883e230dd2SCorentin Chary 
9893e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
9903e230dd2SCorentin Chary {
991385ac97fSMarc-André Lureau     QEMUCursor *c = qemu_console_get_cursor(vs->vd->dcl.con);
9923e230dd2SCorentin Chary     int isize;
9933e230dd2SCorentin Chary 
994385ac97fSMarc-André Lureau     if (!c) {
995b3c2de9cSGerd Hoffmann         return -1;
996b3c2de9cSGerd Hoffmann     }
997b3c2de9cSGerd Hoffmann 
998074a86d0SGerd Hoffmann     if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
999074a86d0SGerd Hoffmann         vnc_lock_output(vs);
1000074a86d0SGerd Hoffmann         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1001074a86d0SGerd Hoffmann         vnc_write_u8(vs,  0);  /*  padding     */
1002074a86d0SGerd Hoffmann         vnc_write_u16(vs, 1);  /*  # of rects  */
1003074a86d0SGerd Hoffmann         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
1004074a86d0SGerd Hoffmann                                VNC_ENCODING_ALPHA_CURSOR);
1005074a86d0SGerd Hoffmann         vnc_write_s32(vs, VNC_ENCODING_RAW);
1006074a86d0SGerd Hoffmann         vnc_write(vs, c->data, c->width * c->height * 4);
1007074a86d0SGerd Hoffmann         vnc_unlock_output(vs);
1008074a86d0SGerd Hoffmann         return 0;
1009074a86d0SGerd Hoffmann     }
10103e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
1011d01f9595SCorentin Chary         vnc_lock_output(vs);
10123e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
10133e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
10143e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
10153e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
10163e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
10179f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
10189f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
10193e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
1020d01f9595SCorentin Chary         vnc_unlock_output(vs);
10213e230dd2SCorentin Chary         return 0;
10223e230dd2SCorentin Chary     }
10233e230dd2SCorentin Chary     return -1;
10243e230dd2SCorentin Chary }
10253e230dd2SCorentin Chary 
10267c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
10277c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
10283e230dd2SCorentin Chary {
1029d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
10303e230dd2SCorentin Chary     VncState *vs;
10313e230dd2SCorentin Chary 
10327267c094SAnthony Liguori     g_free(vd->cursor_mask);
10333e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
10347267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
10353e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
10363e230dd2SCorentin Chary 
10373e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
10383e230dd2SCorentin Chary         vnc_cursor_define(vs);
10393e230dd2SCorentin Chary     }
10403e230dd2SCorentin Chary }
10413e230dd2SCorentin Chary 
10424769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
10436c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
10443e230dd2SCorentin Chary {
10453e230dd2SCorentin Chary     int h;
10463e230dd2SCorentin Chary 
10476c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
1048bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
10493e230dd2SCorentin Chary             break;
1050bc2429b9SCorentin Chary         }
1051863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
10523e230dd2SCorentin Chary     }
10533e230dd2SCorentin Chary 
10543e230dd2SCorentin Chary     return h;
10553e230dd2SCorentin Chary }
10563e230dd2SCorentin Chary 
1057e2b72cb6SDaniel P. Berrange /*
1058e2b72cb6SDaniel P. Berrange  * Figure out how much pending data we should allow in the output
1059e2b72cb6SDaniel P. Berrange  * buffer before we throttle incremental display updates, and/or
1060e2b72cb6SDaniel P. Berrange  * drop audio samples.
1061e2b72cb6SDaniel P. Berrange  *
1062e2b72cb6SDaniel P. Berrange  * We allow for equiv of 1 full display's worth of FB updates,
1063e2b72cb6SDaniel P. Berrange  * and 1 second of audio samples. If audio backlog was larger
1064e2b72cb6SDaniel P. Berrange  * than that the client would already suffering awful audio
1065e2b72cb6SDaniel P. Berrange  * glitches, so dropping samples is no worse really).
1066e2b72cb6SDaniel P. Berrange  */
1067e2b72cb6SDaniel P. Berrange static void vnc_update_throttle_offset(VncState *vs)
1068e2b72cb6SDaniel P. Berrange {
1069e2b72cb6SDaniel P. Berrange     size_t offset =
1070e2b72cb6SDaniel P. Berrange         vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1071e2b72cb6SDaniel P. Berrange 
1072e2b72cb6SDaniel P. Berrange     if (vs->audio_cap) {
1073e2b72cb6SDaniel P. Berrange         int bps;
1074e2b72cb6SDaniel P. Berrange         switch (vs->as.fmt) {
1075e2b72cb6SDaniel P. Berrange         default:
107685bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U8:
107785bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S8:
1078e2b72cb6SDaniel P. Berrange             bps = 1;
1079e2b72cb6SDaniel P. Berrange             break;
108085bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U16:
108185bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S16:
1082e2b72cb6SDaniel P. Berrange             bps = 2;
1083e2b72cb6SDaniel P. Berrange             break;
108485bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_U32:
108585bc5852SKővágó, Zoltán         case  AUDIO_FORMAT_S32:
1086e2b72cb6SDaniel P. Berrange             bps = 4;
1087e2b72cb6SDaniel P. Berrange             break;
1088e2b72cb6SDaniel P. Berrange         }
1089cf070658SDaniel P. Berrangé         offset += vs->as.freq * bps * vs->as.nchannels;
1090e2b72cb6SDaniel P. Berrange     }
1091e2b72cb6SDaniel P. Berrange 
1092e2b72cb6SDaniel P. Berrange     /* Put a floor of 1MB on offset, so that if we have a large pending
1093e2b72cb6SDaniel P. Berrange      * buffer and the display is resized to a small size & back again
1094e2b72cb6SDaniel P. Berrange      * we don't suddenly apply a tiny send limit
1095e2b72cb6SDaniel P. Berrange      */
1096e2b72cb6SDaniel P. Berrange     offset = MAX(offset, 1024 * 1024);
1097e2b72cb6SDaniel P. Berrange 
10986aa22a29SDaniel P. Berrange     if (vs->throttle_output_offset != offset) {
10996aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_threshold(
11006aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
11016aa22a29SDaniel P. Berrange             vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
11026aa22a29SDaniel P. Berrange     }
11036aa22a29SDaniel P. Berrange 
1104e2b72cb6SDaniel P. Berrange     vs->throttle_output_offset = offset;
1105e2b72cb6SDaniel P. Berrange }
1106e2b72cb6SDaniel P. Berrange 
11070bad8342SDaniel P. Berrange static bool vnc_should_update(VncState *vs)
11080bad8342SDaniel P. Berrange {
11090bad8342SDaniel P. Berrange     switch (vs->update) {
11100bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_NONE:
11110bad8342SDaniel P. Berrange         break;
11120bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_INCREMENTAL:
1113e2b72cb6SDaniel P. Berrange         /* Only allow incremental updates if the pending send queue
1114ada8d2e4SDaniel P. Berrange          * is less than the permitted threshold, and the job worker
1115ada8d2e4SDaniel P. Berrange          * is completely idle.
11160bad8342SDaniel P. Berrange          */
1117ada8d2e4SDaniel P. Berrange         if (vs->output.offset < vs->throttle_output_offset &&
1118ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
11190bad8342SDaniel P. Berrange             return true;
11200bad8342SDaniel P. Berrange         }
11216aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_incremental(
11226aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->output.offset);
11230bad8342SDaniel P. Berrange         break;
11240bad8342SDaniel P. Berrange     case VNC_STATE_UPDATE_FORCE:
1125ada8d2e4SDaniel P. Berrange         /* Only allow forced updates if the pending send queue
1126ada8d2e4SDaniel P. Berrange          * does not contain a previous forced update, and the
1127ada8d2e4SDaniel P. Berrange          * job worker is completely idle.
1128ada8d2e4SDaniel P. Berrange          *
1129ada8d2e4SDaniel P. Berrange          * Note this means we'll queue a forced update, even if
1130ada8d2e4SDaniel P. Berrange          * the output buffer size is otherwise over the throttle
1131ada8d2e4SDaniel P. Berrange          * output limit.
1132ada8d2e4SDaniel P. Berrange          */
1133ada8d2e4SDaniel P. Berrange         if (vs->force_update_offset == 0 &&
1134ada8d2e4SDaniel P. Berrange             vs->job_update == VNC_STATE_UPDATE_NONE) {
11350bad8342SDaniel P. Berrange             return true;
11360bad8342SDaniel P. Berrange         }
11376aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_forced(
11386aa22a29SDaniel P. Berrange             vs, vs->ioc, vs->job_update, vs->force_update_offset);
1139ada8d2e4SDaniel P. Berrange         break;
1140ada8d2e4SDaniel P. Berrange     }
11410bad8342SDaniel P. Berrange     return false;
11420bad8342SDaniel P. Berrange }
11430bad8342SDaniel P. Berrange 
11446af998dbSDaniel P. Berrange static int vnc_update_client(VncState *vs, int has_dirty)
11453e230dd2SCorentin Chary {
11463e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
1147bd023f95SCorentin Chary     VncJob *job;
11483e230dd2SCorentin Chary     int y;
11492f487a3dSPeter Lieven     int height, width;
1150bd023f95SCorentin Chary     int n = 0;
1151bd023f95SCorentin Chary 
1152b939eb89SDaniel P. Berrange     if (vs->disconnecting) {
1153b939eb89SDaniel P. Berrange         vnc_disconnect_finish(vs);
1154b939eb89SDaniel P. Berrange         return 0;
1155b939eb89SDaniel P. Berrange     }
1156b939eb89SDaniel P. Berrange 
1157b939eb89SDaniel P. Berrange     vs->has_dirty += has_dirty;
11580bad8342SDaniel P. Berrange     if (!vnc_should_update(vs)) {
11593e230dd2SCorentin Chary         return 0;
1160b939eb89SDaniel P. Berrange     }
11613e230dd2SCorentin Chary 
1162fef1bbadSDaniel P. Berrange     if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
11633e230dd2SCorentin Chary         return 0;
1164b939eb89SDaniel P. Berrange     }
11653e230dd2SCorentin Chary 
11663e230dd2SCorentin Chary     /*
11673e230dd2SCorentin Chary      * Send screen updates to the vnc client using the server
11683e230dd2SCorentin Chary      * surface and server dirty map.  guest surface updates
11693e230dd2SCorentin Chary      * happening in parallel don't disturb us, the next pass will
11703e230dd2SCorentin Chary      * send them to the client.
11713e230dd2SCorentin Chary      */
1172bd023f95SCorentin Chary     job = vnc_job_new(vs);
11733e230dd2SCorentin Chary 
1174bea60dd7SPeter Lieven     height = pixman_image_get_height(vd->server);
1175bea60dd7SPeter Lieven     width = pixman_image_get_width(vd->server);
11763e230dd2SCorentin Chary 
117712b316d4SPeter Lieven     y = 0;
117812b316d4SPeter Lieven     for (;;) {
117912b316d4SPeter Lieven         int x, h;
118012b316d4SPeter Lieven         unsigned long x2;
118112b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
118212b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(vs),
118312b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(vs));
118412b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(vs)) {
118512b316d4SPeter Lieven             /* no more dirty bits */
118612b316d4SPeter Lieven             break;
11873e230dd2SCorentin Chary         }
118812b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(vs);
118912b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(vs);
119012b316d4SPeter Lieven         x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
119112b316d4SPeter Lieven                                 VNC_DIRTY_BPL(vs), x);
119212b316d4SPeter Lieven         bitmap_clear(vs->dirty[y], x, x2 - x);
119312b316d4SPeter Lieven         h = find_and_clear_dirty_height(vs, y, x, x2, height);
11942f487a3dSPeter Lieven         x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
11952f487a3dSPeter Lieven         if (x2 > x) {
119612b316d4SPeter Lieven             n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
119712b316d4SPeter Lieven                                   (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
11983e230dd2SCorentin Chary         }
11990e7d6f60SPeter Lieven         if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
12000e7d6f60SPeter Lieven             y += h;
12010e7d6f60SPeter Lieven             if (y == height) {
12020e7d6f60SPeter Lieven                 break;
12030e7d6f60SPeter Lieven             }
12040e7d6f60SPeter Lieven         }
12052f487a3dSPeter Lieven     }
1206bd023f95SCorentin Chary 
1207ada8d2e4SDaniel P. Berrange     vs->job_update = vs->update;
1208728a7ac9SDaniel P. Berrange     vs->update = VNC_STATE_UPDATE_NONE;
1209ada8d2e4SDaniel P. Berrange     vnc_job_push(job);
121063658280SGerd Hoffmann     vs->has_dirty = 0;
1211bd023f95SCorentin Chary     return n;
12123e230dd2SCorentin Chary }
12133e230dd2SCorentin Chary 
12143e230dd2SCorentin Chary /* audio */
12153e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
12163e230dd2SCorentin Chary {
12173e230dd2SCorentin Chary     VncState *vs = opaque;
12183e230dd2SCorentin Chary 
1219f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
12203e230dd2SCorentin Chary     switch (cmd) {
12213e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1222adc8fce8SDaniel P. Berrangé         trace_vnc_msg_server_audio_end(vs, vs->ioc);
1223bd023f95SCorentin Chary         vnc_lock_output(vs);
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_END);
1227bd023f95SCorentin Chary         vnc_unlock_output(vs);
12283e230dd2SCorentin Chary         vnc_flush(vs);
12293e230dd2SCorentin Chary         break;
12303e230dd2SCorentin Chary 
12313e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1232adc8fce8SDaniel P. Berrangé         trace_vnc_msg_server_audio_begin(vs, vs->ioc);
1233bd023f95SCorentin Chary         vnc_lock_output(vs);
12343e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12353e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12363e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1237bd023f95SCorentin Chary         vnc_unlock_output(vs);
12383e230dd2SCorentin Chary         vnc_flush(vs);
12393e230dd2SCorentin Chary         break;
12403e230dd2SCorentin Chary     }
12413e230dd2SCorentin Chary }
12423e230dd2SCorentin Chary 
12433e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
12443e230dd2SCorentin Chary {
12453e230dd2SCorentin Chary }
12463e230dd2SCorentin Chary 
124757a878edSPhilippe Mathieu-Daudé static void audio_capture(void *opaque, const void *buf, int size)
12483e230dd2SCorentin Chary {
12493e230dd2SCorentin Chary     VncState *vs = opaque;
12503e230dd2SCorentin Chary 
1251f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1252adc8fce8SDaniel P. Berrangé     trace_vnc_msg_server_audio_data(vs, vs->ioc, buf, size);
1253bd023f95SCorentin Chary     vnc_lock_output(vs);
1254e2b72cb6SDaniel P. Berrange     if (vs->output.offset < vs->throttle_output_offset) {
12553e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
12563e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
12573e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
12583e230dd2SCorentin Chary         vnc_write_u32(vs, size);
12593e230dd2SCorentin Chary         vnc_write(vs, buf, size);
12606aa22a29SDaniel P. Berrange     } else {
12616aa22a29SDaniel P. Berrange         trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1262e2b72cb6SDaniel P. Berrange     }
1263bd023f95SCorentin Chary     vnc_unlock_output(vs);
12643e230dd2SCorentin Chary     vnc_flush(vs);
12653e230dd2SCorentin Chary }
12663e230dd2SCorentin Chary 
12673e230dd2SCorentin Chary static void audio_add(VncState *vs)
12683e230dd2SCorentin Chary {
12693e230dd2SCorentin Chary     struct audio_capture_ops ops;
12703e230dd2SCorentin Chary 
12713e230dd2SCorentin Chary     if (vs->audio_cap) {
1272027a79c3SCole Robinson         error_report("audio already running");
12733e230dd2SCorentin Chary         return;
12743e230dd2SCorentin Chary     }
12753e230dd2SCorentin Chary 
12763e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
12773e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
12783e230dd2SCorentin Chary     ops.capture = audio_capture;
12793e230dd2SCorentin Chary 
1280f0b9f36dSKővágó, Zoltán     vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
12813e230dd2SCorentin Chary     if (!vs->audio_cap) {
1282027a79c3SCole Robinson         error_report("Failed to add audio capture");
12833e230dd2SCorentin Chary     }
12843e230dd2SCorentin Chary }
12853e230dd2SCorentin Chary 
12863e230dd2SCorentin Chary static void audio_del(VncState *vs)
12873e230dd2SCorentin Chary {
12883e230dd2SCorentin Chary     if (vs->audio_cap) {
12893e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
12903e230dd2SCorentin Chary         vs->audio_cap = NULL;
12913e230dd2SCorentin Chary     }
12923e230dd2SCorentin Chary }
12933e230dd2SCorentin Chary 
12943e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
12953e230dd2SCorentin Chary {
129604d2529dSDaniel P. Berrange     if (vs->disconnecting) {
12973e230dd2SCorentin Chary         return;
129804d2529dSDaniel P. Berrange     }
1299ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_start(vs, vs->ioc);
13008cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
130104d2529dSDaniel P. Berrange     if (vs->ioc_tag) {
130204d2529dSDaniel P. Berrange         g_source_remove(vs->ioc_tag);
1303a75d6f07SBrandon Carpenter         vs->ioc_tag = 0;
130404d2529dSDaniel P. Berrange     }
130504d2529dSDaniel P. Berrange     qio_channel_close(vs->ioc, NULL);
130604d2529dSDaniel P. Berrange     vs->disconnecting = TRUE;
13073e230dd2SCorentin Chary }
13083e230dd2SCorentin Chary 
13097536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
13103e230dd2SCorentin Chary {
13117d964c9dSCorentin Chary     int i;
13127d964c9dSCorentin Chary 
1313ad6374c4SDaniel P. Berrange     trace_vnc_client_disconnect_finish(vs, vs->ioc);
1314ad6374c4SDaniel P. Berrange 
1315bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1316bd023f95SCorentin Chary 
1317bd023f95SCorentin Chary     vnc_lock_output(vs);
1318fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
13193e230dd2SCorentin Chary 
13203e230dd2SCorentin Chary     buffer_free(&vs->input);
13213e230dd2SCorentin Chary     buffer_free(&vs->output);
13223e230dd2SCorentin Chary 
1323fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
13243e230dd2SCorentin Chary 
13253e230dd2SCorentin Chary     vnc_zlib_clear(vs);
13263e230dd2SCorentin Chary     vnc_tight_clear(vs);
1327148954faSCorentin Chary     vnc_zrle_clear(vs);
13283e230dd2SCorentin Chary 
13293e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13303e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
13313e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13323e230dd2SCorentin Chary     audio_del(vs);
1333c2f2ba49SGerd Hoffmann     qkbd_state_lift_all_keys(vs->vd->kbd);
13343e230dd2SCorentin Chary 
133590cd03a3SDaniel P. Berrange     if (vs->mouse_mode_notifier.notify != NULL) {
13366fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
133790cd03a3SDaniel P. Berrange     }
133890cd03a3SDaniel P. Berrange     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1339c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1340c7628bffSGerd Hoffmann         /* last client gone */
1341c7628bffSGerd Hoffmann         vnc_update_server_surface(vs->vd);
1342c7628bffSGerd Hoffmann     }
13431dbbe6f1SRao Lei     vnc_unlock_output(vs);
13441dbbe6f1SRao Lei 
13451b17f1e9SMarc-André Lureau     if (vs->cbpeer.notifier.notify) {
13460bf41cabSGerd Hoffmann         qemu_clipboard_peer_unregister(&vs->cbpeer);
13470bf41cabSGerd Hoffmann     }
13483e230dd2SCorentin Chary 
1349bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
13506fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1351175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
13526fd8e79aSTim Hardeck     }
1353175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1354175b2a6eSCorentin Chary 
13557d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
13567267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
13577d964c9dSCorentin Chary     }
13587267c094SAnthony Liguori     g_free(vs->lossy_rect);
135904d2529dSDaniel P. Berrange 
136004d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->ioc));
136104d2529dSDaniel P. Berrange     vs->ioc = NULL;
136204d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->sioc));
136304d2529dSDaniel P. Berrange     vs->sioc = NULL;
1364f31f9c10SGerd Hoffmann     vs->magic = 0;
13656bf21f3dSLi Qiang     g_free(vs->zrle);
13666bf21f3dSLi Qiang     g_free(vs->tight);
13677267c094SAnthony Liguori     g_free(vs);
13683e230dd2SCorentin Chary }
13693e230dd2SCorentin Chary 
137034ab29c2SVladimir Sementsov-Ogievskiy size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error *err)
13713e230dd2SCorentin Chary {
137204d2529dSDaniel P. Berrange     if (ret <= 0) {
137304d2529dSDaniel P. Berrange         if (ret == 0) {
1374ad6374c4SDaniel P. Berrange             trace_vnc_client_eof(vs, vs->ioc);
1375537848eeSMichael Tokarev             vnc_disconnect_start(vs);
137604d2529dSDaniel P. Berrange         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1377ad6374c4SDaniel P. Berrange             trace_vnc_client_io_error(vs, vs->ioc,
137834ab29c2SVladimir Sementsov-Ogievskiy                                       err ? error_get_pretty(err) : "Unknown");
1379537848eeSMichael Tokarev             vnc_disconnect_start(vs);
13803e230dd2SCorentin Chary         }
13813e230dd2SCorentin Chary 
138234ab29c2SVladimir Sementsov-Ogievskiy         error_free(err);
13833e230dd2SCorentin Chary         return 0;
13843e230dd2SCorentin Chary     }
13853e230dd2SCorentin Chary     return ret;
13863e230dd2SCorentin Chary }
13873e230dd2SCorentin Chary 
13883e230dd2SCorentin Chary 
13893e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
13903e230dd2SCorentin Chary {
13913e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
13923e230dd2SCorentin Chary     vnc_disconnect_start(vs);
13933e230dd2SCorentin Chary }
13943e230dd2SCorentin Chary 
13953e305e4aSDaniel P. Berrange 
13963e230dd2SCorentin Chary /*
13973e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
13983e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
13993e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
14003e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
14013e230dd2SCorentin Chary  *
14023e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
14033e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
14043e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
14053e230dd2SCorentin Chary  * is active
14063e230dd2SCorentin Chary  *
14073e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
14083e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
140930b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
14103e230dd2SCorentin Chary  */
141130b80fd5SDaniel P. Berrange size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
14123e230dd2SCorentin Chary {
141304d2529dSDaniel P. Berrange     Error *err = NULL;
1414fdd1ab6aSDaniel P. Berrange     ssize_t ret;
141534ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_write(vs->ioc, (const char *)data, datalen, &err);
14163e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
141734ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
14183e230dd2SCorentin Chary }
14193e230dd2SCorentin Chary 
14203e230dd2SCorentin Chary 
14213e230dd2SCorentin Chary /*
14223e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
14233e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
14243e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
14253e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
14263e230dd2SCorentin Chary  *
14273e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
14283e230dd2SCorentin Chary  * the buffered output data if the socket would block.  Returns
142930b80fd5SDaniel P. Berrange  * 0 on I/O error, and disconnects the client socket.
14303e230dd2SCorentin Chary  */
143130b80fd5SDaniel P. Berrange static size_t vnc_client_write_plain(VncState *vs)
14323e230dd2SCorentin Chary {
14336aa22a29SDaniel P. Berrange     size_t offset;
143430b80fd5SDaniel P. Berrange     size_t ret;
14353e230dd2SCorentin Chary 
14363e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14373e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
14383e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
14393e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
14403e230dd2SCorentin Chary 
14413e230dd2SCorentin Chary     if (vs->sasl.conn &&
14423e230dd2SCorentin Chary         vs->sasl.runSSF &&
14433e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
14443e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
14453e230dd2SCorentin Chary         if (ret)
14463e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
14473e230dd2SCorentin Chary     } else
14483e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14493e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
14503e230dd2SCorentin Chary     if (!ret)
14513e230dd2SCorentin Chary         return 0;
14523e230dd2SCorentin Chary 
1453ada8d2e4SDaniel P. Berrange     if (ret >= vs->force_update_offset) {
14546aa22a29SDaniel P. Berrange         if (vs->force_update_offset != 0) {
14556aa22a29SDaniel P. Berrange             trace_vnc_client_unthrottle_forced(vs, vs->ioc);
14566aa22a29SDaniel P. Berrange         }
1457ada8d2e4SDaniel P. Berrange         vs->force_update_offset = 0;
1458ada8d2e4SDaniel P. Berrange     } else {
1459ada8d2e4SDaniel P. Berrange         vs->force_update_offset -= ret;
1460ada8d2e4SDaniel P. Berrange     }
14616aa22a29SDaniel P. Berrange     offset = vs->output.offset;
146232ed2680STim Hardeck     buffer_advance(&vs->output, ret);
14636aa22a29SDaniel P. Berrange     if (offset >= vs->throttle_output_offset &&
14646aa22a29SDaniel P. Berrange         vs->output.offset < vs->throttle_output_offset) {
14656aa22a29SDaniel P. Berrange         trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
14666aa22a29SDaniel P. Berrange     }
14673e230dd2SCorentin Chary 
14683e230dd2SCorentin Chary     if (vs->output.offset == 0) {
146904d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
147004d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
147104d2529dSDaniel P. Berrange         }
147204d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
14732ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
14742ddafce7SDing Hui             vnc_client_io, vs, NULL);
14753e230dd2SCorentin Chary     }
14763e230dd2SCorentin Chary 
14773e230dd2SCorentin Chary     return ret;
14783e230dd2SCorentin Chary }
14793e230dd2SCorentin Chary 
14803e230dd2SCorentin Chary 
14813e230dd2SCorentin Chary /*
14823e230dd2SCorentin Chary  * First function called whenever there is data to be written to
14833e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
14843e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
14853e230dd2SCorentin Chary  */
148604d2529dSDaniel P. Berrange static void vnc_client_write_locked(VncState *vs)
14873e230dd2SCorentin Chary {
14883e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14893e230dd2SCorentin Chary     if (vs->sasl.conn &&
14903e230dd2SCorentin Chary         vs->sasl.runSSF &&
14913e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
14923e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
14933e230dd2SCorentin Chary     } else
14943e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14957536ee4bSTim Hardeck     {
14963e230dd2SCorentin Chary         vnc_client_write_plain(vs);
14973e230dd2SCorentin Chary     }
14987536ee4bSTim Hardeck }
14993e230dd2SCorentin Chary 
150004d2529dSDaniel P. Berrange static void vnc_client_write(VncState *vs)
1501bd023f95SCorentin Chary {
1502f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1503bd023f95SCorentin Chary     vnc_lock_output(vs);
1504d5f04223SDaniel P. Berrange     if (vs->output.offset) {
150504d2529dSDaniel P. Berrange         vnc_client_write_locked(vs);
150604d2529dSDaniel P. Berrange     } else if (vs->ioc != NULL) {
150704d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
150804d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
150904d2529dSDaniel P. Berrange         }
151004d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
15112ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
15122ddafce7SDing Hui             vnc_client_io, vs, NULL);
1513bd023f95SCorentin Chary     }
1514bd023f95SCorentin Chary     vnc_unlock_output(vs);
1515bd023f95SCorentin Chary }
1516bd023f95SCorentin Chary 
15173e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
15183e230dd2SCorentin Chary {
15193e230dd2SCorentin Chary     vs->read_handler = func;
15203e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
15213e230dd2SCorentin Chary }
15223e230dd2SCorentin Chary 
15233e230dd2SCorentin Chary 
15243e230dd2SCorentin Chary /*
15253e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
15263e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
15273e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
15283e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
15293e230dd2SCorentin Chary  *
15303e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
15313e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
15323e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
15333e230dd2SCorentin Chary  * is active
15343e230dd2SCorentin Chary  *
15353e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
15363e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
153730b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15383e230dd2SCorentin Chary  */
153930b80fd5SDaniel P. Berrange size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
15403e230dd2SCorentin Chary {
1541fdd1ab6aSDaniel P. Berrange     ssize_t ret;
154204d2529dSDaniel P. Berrange     Error *err = NULL;
154334ab29c2SVladimir Sementsov-Ogievskiy     ret = qio_channel_read(vs->ioc, (char *)data, datalen, &err);
15443e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
154534ab29c2SVladimir Sementsov-Ogievskiy     return vnc_client_io_error(vs, ret, err);
15463e230dd2SCorentin Chary }
15473e230dd2SCorentin Chary 
15483e230dd2SCorentin Chary 
15493e230dd2SCorentin Chary /*
15503e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
15513e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
15523e230dd2SCorentin Chary  * data as possible without blocking.
15533e230dd2SCorentin Chary  *
155430b80fd5SDaniel P. Berrange  * Returns the number of bytes read, which may be less than
155530b80fd5SDaniel P. Berrange  * the requested 'datalen' if the socket would block. Returns
155630b80fd5SDaniel P. Berrange  * 0 on I/O error or EOF, and disconnects the client socket.
15573e230dd2SCorentin Chary  */
155830b80fd5SDaniel P. Berrange static size_t vnc_client_read_plain(VncState *vs)
15593e230dd2SCorentin Chary {
156030b80fd5SDaniel P. Berrange     size_t ret;
15613e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
15623e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
15633e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
15643e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
15653e230dd2SCorentin Chary     if (!ret)
15663e230dd2SCorentin Chary         return 0;
15673e230dd2SCorentin Chary     vs->input.offset += ret;
15683e230dd2SCorentin Chary     return ret;
15693e230dd2SCorentin Chary }
15703e230dd2SCorentin Chary 
1571175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1572175b2a6eSCorentin Chary {
1573175b2a6eSCorentin Chary     VncState *vs = opaque;
1574175b2a6eSCorentin Chary 
1575f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1576175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1577175b2a6eSCorentin Chary }
15783e230dd2SCorentin Chary 
15793e230dd2SCorentin Chary /*
15803e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
15813e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
15823e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
1583ea697449SDaniel P. Berrange  * Returns 0 on success, -1 if client disconnected
15843e230dd2SCorentin Chary  */
1585ea697449SDaniel P. Berrange static int vnc_client_read(VncState *vs)
15863e230dd2SCorentin Chary {
158730b80fd5SDaniel P. Berrange     size_t ret;
15883e230dd2SCorentin Chary 
15893e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
15903e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
15913e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
15923e230dd2SCorentin Chary     else
15933e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
15943e230dd2SCorentin Chary         ret = vnc_client_read_plain(vs);
15953e230dd2SCorentin Chary     if (!ret) {
159604d2529dSDaniel P. Berrange         if (vs->disconnecting) {
15973e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1598ea697449SDaniel P. Berrange             return -1;
159904d2529dSDaniel P. Berrange         }
1600ea697449SDaniel P. Berrange         return 0;
16013e230dd2SCorentin Chary     }
16023e230dd2SCorentin Chary 
16033e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
16043e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
16053e230dd2SCorentin Chary         int ret;
16063e230dd2SCorentin Chary 
16073e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
160804d2529dSDaniel P. Berrange         if (vs->disconnecting) {
16093e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1610ea697449SDaniel P. Berrange             return -1;
16113e230dd2SCorentin Chary         }
16123e230dd2SCorentin Chary 
16133e230dd2SCorentin Chary         if (!ret) {
161432ed2680STim Hardeck             buffer_advance(&vs->input, len);
16153e230dd2SCorentin Chary         } else {
16163e230dd2SCorentin Chary             vs->read_handler_expect = ret;
16173e230dd2SCorentin Chary         }
16183e230dd2SCorentin Chary     }
1619ea697449SDaniel P. Berrange     return 0;
16203e230dd2SCorentin Chary }
16213e230dd2SCorentin Chary 
162204d2529dSDaniel P. Berrange gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
162304d2529dSDaniel P. Berrange                        GIOCondition condition, void *opaque)
162404d2529dSDaniel P. Berrange {
162504d2529dSDaniel P. Berrange     VncState *vs = opaque;
1626f31f9c10SGerd Hoffmann 
1627f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
16282ddafce7SDing Hui 
16292ddafce7SDing Hui     if (condition & (G_IO_HUP | G_IO_ERR)) {
16302ddafce7SDing Hui         vnc_disconnect_start(vs);
16312ddafce7SDing Hui         return TRUE;
16322ddafce7SDing Hui     }
16332ddafce7SDing Hui 
163404d2529dSDaniel P. Berrange     if (condition & G_IO_IN) {
1635ea697449SDaniel P. Berrange         if (vnc_client_read(vs) < 0) {
16361bc3117aSGerd Hoffmann             /* vs is free()ed here */
16371bc3117aSGerd Hoffmann             return TRUE;
1638ea697449SDaniel P. Berrange         }
163904d2529dSDaniel P. Berrange     }
164004d2529dSDaniel P. Berrange     if (condition & G_IO_OUT) {
164104d2529dSDaniel P. Berrange         vnc_client_write(vs);
164204d2529dSDaniel P. Berrange     }
16431bc3117aSGerd Hoffmann 
1644d49b87f0SKlim Kireev     if (vs->disconnecting) {
1645d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1646d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1647d49b87f0SKlim Kireev         }
1648d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1649d49b87f0SKlim Kireev     }
165004d2529dSDaniel P. Berrange     return TRUE;
165104d2529dSDaniel P. Berrange }
165204d2529dSDaniel P. Berrange 
165304d2529dSDaniel P. Berrange 
1654f887cf16SDaniel P. Berrange /*
1655f887cf16SDaniel P. Berrange  * Scale factor to apply to vs->throttle_output_offset when checking for
1656f887cf16SDaniel P. Berrange  * hard limit. Worst case normal usage could be x2, if we have a complete
1657f887cf16SDaniel P. Berrange  * incremental update and complete forced update in the output buffer.
1658f887cf16SDaniel P. Berrange  * So x3 should be good enough, but we pick x5 to be conservative and thus
1659f887cf16SDaniel P. Berrange  * (hopefully) never trigger incorrectly.
1660f887cf16SDaniel P. Berrange  */
1661f887cf16SDaniel P. Berrange #define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1662f887cf16SDaniel P. Berrange 
16633e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
16643e230dd2SCorentin Chary {
1665f31f9c10SGerd Hoffmann     assert(vs->magic == VNC_MAGIC);
1666f887cf16SDaniel P. Berrange     if (vs->disconnecting) {
1667f887cf16SDaniel P. Berrange         return;
1668f887cf16SDaniel P. Berrange     }
1669f887cf16SDaniel P. Berrange     /* Protection against malicious client/guest to prevent our output
1670f887cf16SDaniel P. Berrange      * buffer growing without bound if client stops reading data. This
1671f887cf16SDaniel P. Berrange      * should rarely trigger, because we have earlier throttling code
1672f887cf16SDaniel P. Berrange      * which stops issuing framebuffer updates and drops audio data
1673f887cf16SDaniel P. Berrange      * if the throttle_output_offset value is exceeded. So we only reach
1674f887cf16SDaniel P. Berrange      * this higher level if a huge number of pseudo-encodings get
1675f887cf16SDaniel P. Berrange      * triggered while data can't be sent on the socket.
1676f887cf16SDaniel P. Berrange      *
1677f887cf16SDaniel P. Berrange      * NB throttle_output_offset can be zero during early protocol
1678f887cf16SDaniel P. Berrange      * handshake, or from the job thread's VncState clone
1679f887cf16SDaniel P. Berrange      */
1680f887cf16SDaniel P. Berrange     if (vs->throttle_output_offset != 0 &&
1681dffa1de0SDaniel P. Berrangé         (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1682dffa1de0SDaniel P. Berrangé         vs->throttle_output_offset) {
16836aa22a29SDaniel P. Berrange         trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
16846aa22a29SDaniel P. Berrange                                       vs->throttle_output_offset);
1685f887cf16SDaniel P. Berrange         vnc_disconnect_start(vs);
1686f887cf16SDaniel P. Berrange         return;
1687f887cf16SDaniel P. Berrange     }
16883e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
16893e230dd2SCorentin Chary 
169004d2529dSDaniel P. Berrange     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
169104d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
169204d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
169304d2529dSDaniel P. Berrange         }
169404d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
16952ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_OUT,
16962ddafce7SDing Hui             vnc_client_io, vs, NULL);
16973e230dd2SCorentin Chary     }
16983e230dd2SCorentin Chary 
16993e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
17003e230dd2SCorentin Chary }
17013e230dd2SCorentin Chary 
17023e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
17033e230dd2SCorentin Chary {
17043e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
17053e230dd2SCorentin Chary }
17063e230dd2SCorentin Chary 
17073e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
17083e230dd2SCorentin Chary {
17093e230dd2SCorentin Chary     uint8_t buf[4];
17103e230dd2SCorentin Chary 
17113e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
17123e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
17133e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
17143e230dd2SCorentin Chary     buf[3] = value & 0xFF;
17153e230dd2SCorentin Chary 
17163e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
17173e230dd2SCorentin Chary }
17183e230dd2SCorentin Chary 
17193e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
17203e230dd2SCorentin Chary {
17213e230dd2SCorentin Chary     uint8_t buf[2];
17223e230dd2SCorentin Chary 
17233e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
17243e230dd2SCorentin Chary     buf[1] = value & 0xFF;
17253e230dd2SCorentin Chary 
17263e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
17273e230dd2SCorentin Chary }
17283e230dd2SCorentin Chary 
17293e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
17303e230dd2SCorentin Chary {
17313e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
17323e230dd2SCorentin Chary }
17333e230dd2SCorentin Chary 
17343e230dd2SCorentin Chary void vnc_flush(VncState *vs)
17353e230dd2SCorentin Chary {
1736bd023f95SCorentin Chary     vnc_lock_output(vs);
1737d5f04223SDaniel P. Berrange     if (vs->ioc != NULL && vs->output.offset) {
1738bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1739bd023f95SCorentin Chary     }
1740d49b87f0SKlim Kireev     if (vs->disconnecting) {
1741d49b87f0SKlim Kireev         if (vs->ioc_tag != 0) {
1742d49b87f0SKlim Kireev             g_source_remove(vs->ioc_tag);
1743d49b87f0SKlim Kireev         }
1744d49b87f0SKlim Kireev         vs->ioc_tag = 0;
1745d49b87f0SKlim Kireev     }
1746bd023f95SCorentin Chary     vnc_unlock_output(vs);
17473e230dd2SCorentin Chary }
17483e230dd2SCorentin Chary 
174971a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
17503e230dd2SCorentin Chary {
17513e230dd2SCorentin Chary     return data[offset];
17523e230dd2SCorentin Chary }
17533e230dd2SCorentin Chary 
175471a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
17553e230dd2SCorentin Chary {
17563e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
17573e230dd2SCorentin Chary }
17583e230dd2SCorentin Chary 
175971a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
17603e230dd2SCorentin Chary {
17613e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
17623e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
17633e230dd2SCorentin Chary }
17643e230dd2SCorentin Chary 
17653e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
17663e230dd2SCorentin Chary {
17673e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
17683e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
17693e230dd2SCorentin Chary }
17703e230dd2SCorentin Chary 
17719e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
17723e230dd2SCorentin Chary {
17733e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
177414768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
17753e230dd2SCorentin Chary 
17763e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1777bd023f95SCorentin Chary         vnc_lock_output(vs);
17783e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
17793e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
17803e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
17813e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1782bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1783bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
17843e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1785bd023f95SCorentin Chary         vnc_unlock_output(vs);
17863e230dd2SCorentin Chary         vnc_flush(vs);
17873e230dd2SCorentin Chary     }
17883e230dd2SCorentin Chary     vs->absolute = absolute;
17893e230dd2SCorentin Chary }
17903e230dd2SCorentin Chary 
17913e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
17923e230dd2SCorentin Chary {
17937fb1cf16SEric Blake     static uint32_t bmap[INPUT_BUTTON__MAX] = {
179414768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
179514768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
179614768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
1797f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1798f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
179914768ebaSGerd Hoffmann     };
180014768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1801bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1802bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
18033e230dd2SCorentin Chary 
180414768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
180514768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
180614768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
180714768ebaSGerd Hoffmann     }
18083e230dd2SCorentin Chary 
18093e230dd2SCorentin Chary     if (vs->absolute) {
18109cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
18119cfa7ab9SPhilippe Voinov         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
18123e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
181314768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
181414768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
18153e230dd2SCorentin Chary     } else {
181614768ebaSGerd Hoffmann         if (vs->last_x != -1) {
181714768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
181814768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
181914768ebaSGerd Hoffmann         }
18203e230dd2SCorentin Chary         vs->last_x = x;
18213e230dd2SCorentin Chary         vs->last_y = y;
18223e230dd2SCorentin Chary     }
182314768ebaSGerd Hoffmann     qemu_input_event_sync();
18243e230dd2SCorentin Chary }
18253e230dd2SCorentin Chary 
1826c2f2ba49SGerd Hoffmann static void press_key(VncState *vs, QKeyCode qcode)
18273e230dd2SCorentin Chary {
1828c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, true);
1829c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, false);
18303e230dd2SCorentin Chary }
18313e230dd2SCorentin Chary 
1832ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1833ab99e5c1SLei Li {
1834ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1835ab99e5c1SLei Li         return;
1836ab99e5c1SLei Li     }
1837ab99e5c1SLei Li 
1838ab99e5c1SLei Li     vnc_lock_output(vs);
1839ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1840ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1841ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1842ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1843a54f0d2bSPierre Ossman     vnc_write_u8(vs, vs->vd->ledstate);
1844ab99e5c1SLei Li     vnc_unlock_output(vs);
1845ab99e5c1SLei Li     vnc_flush(vs);
1846ab99e5c1SLei Li }
1847ab99e5c1SLei Li 
18483e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
18493e230dd2SCorentin Chary {
1850a54f0d2bSPierre Ossman     VncDisplay *vd = opaque;
1851a54f0d2bSPierre Ossman     VncState *client;
18523e230dd2SCorentin Chary 
185340066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
185440066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
185540066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
185640066175SGerd Hoffmann 
1857a54f0d2bSPierre Ossman     if (ledstate == vd->ledstate) {
1858a54f0d2bSPierre Ossman         return;
185996f3d174SLei Li     }
1860ab99e5c1SLei Li 
1861a54f0d2bSPierre Ossman     vd->ledstate = ledstate;
1862a54f0d2bSPierre Ossman 
1863a54f0d2bSPierre Ossman     QTAILQ_FOREACH(client, &vd->clients, next) {
1864a54f0d2bSPierre Ossman         vnc_led_state_change(client);
1865ab99e5c1SLei Li     }
18663e230dd2SCorentin Chary }
18673e230dd2SCorentin Chary 
18683e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
18693e230dd2SCorentin Chary {
1870c2f2ba49SGerd Hoffmann     QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1871c2f2ba49SGerd Hoffmann 
18723e230dd2SCorentin Chary     /* QEMU console switch */
1873c2f2ba49SGerd Hoffmann     switch (qcode) {
1874c2f2ba49SGerd Hoffmann     case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1875c2f2ba49SGerd Hoffmann         if (vs->vd->dcl.con == NULL && down &&
1876c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1877c2f2ba49SGerd Hoffmann             qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
18783e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
1879c2f2ba49SGerd Hoffmann             qkbd_state_lift_all_keys(vs->vd->kbd);
1880c2f2ba49SGerd Hoffmann             console_select(qcode - Q_KEY_CODE_1);
18813e230dd2SCorentin Chary             return;
18823e230dd2SCorentin Chary         }
1883c2f2ba49SGerd Hoffmann     default:
18843e230dd2SCorentin Chary         break;
18853e230dd2SCorentin Chary     }
18863e230dd2SCorentin Chary 
1887e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1888e7b2aaccSLei Li        state extension.
1889e7b2aaccSLei Li     */
18909892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1891e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
18923e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
18933e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
18943e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
18953e230dd2SCorentin Chary            toggles numlock away from the VNC window.
18963e230dd2SCorentin Chary         */
18973e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1898c2f2ba49SGerd Hoffmann             if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
189940066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
1900c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
19013e230dd2SCorentin Chary             }
19023e230dd2SCorentin Chary         } else {
1903c2f2ba49SGerd Hoffmann             if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
190440066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
1905c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_NUM_LOCK);
19063e230dd2SCorentin Chary             }
19073e230dd2SCorentin Chary         }
19083e230dd2SCorentin Chary     }
19093e230dd2SCorentin Chary 
19109892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1911e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
19123e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
19133e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
19143e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
19153e230dd2SCorentin Chary            toggles capslock away from the VNC window.
19163e230dd2SCorentin Chary         */
19173e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1918c2f2ba49SGerd Hoffmann         bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1919c2f2ba49SGerd Hoffmann         bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
19203e230dd2SCorentin Chary         if (capslock) {
19213e230dd2SCorentin Chary             if (uppercase == shift) {
192240066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
1923c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
19243e230dd2SCorentin Chary             }
19253e230dd2SCorentin Chary         } else {
19263e230dd2SCorentin Chary             if (uppercase != shift) {
192740066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
1928c2f2ba49SGerd Hoffmann                 press_key(vs, Q_KEY_CODE_CAPS_LOCK);
19293e230dd2SCorentin Chary             }
19303e230dd2SCorentin Chary         }
19313e230dd2SCorentin Chary     }
19323e230dd2SCorentin Chary 
1933c2f2ba49SGerd Hoffmann     qkbd_state_key_event(vs->vd->kbd, qcode, down);
1934c2f2ba49SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
1935c2f2ba49SGerd Hoffmann         bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1936c2f2ba49SGerd Hoffmann         bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
19373e230dd2SCorentin Chary         /* QEMU console emulation */
19383e230dd2SCorentin Chary         if (down) {
19393e230dd2SCorentin Chary             switch (keycode) {
19403e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
19413e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
19423e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
19433e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
19443e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
19453e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
19463e230dd2SCorentin Chary                 break;
19473e230dd2SCorentin Chary             case 0xc8:
1948cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_UP);
19493e230dd2SCorentin Chary                 break;
19503e230dd2SCorentin Chary             case 0xd0:
1951cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_DOWN);
19523e230dd2SCorentin Chary                 break;
19533e230dd2SCorentin Chary             case 0xcb:
1954cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_LEFT);
19553e230dd2SCorentin Chary                 break;
19563e230dd2SCorentin Chary             case 0xcd:
1957cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_RIGHT);
19583e230dd2SCorentin Chary                 break;
19593e230dd2SCorentin Chary             case 0xd3:
1960cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_DELETE);
19613e230dd2SCorentin Chary                 break;
19623e230dd2SCorentin Chary             case 0xc7:
1963cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_HOME);
19643e230dd2SCorentin Chary                 break;
19653e230dd2SCorentin Chary             case 0xcf:
1966cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_END);
19673e230dd2SCorentin Chary                 break;
19683e230dd2SCorentin Chary             case 0xc9:
1969cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_PAGEUP);
19703e230dd2SCorentin Chary                 break;
19713e230dd2SCorentin Chary             case 0xd1:
1972cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, QEMU_KEY_PAGEDOWN);
19733e230dd2SCorentin Chary                 break;
19743e230dd2SCorentin Chary 
19753e230dd2SCorentin Chary             case 0x47:
1976cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '7' : QEMU_KEY_HOME);
19773e230dd2SCorentin Chary                 break;
19783e230dd2SCorentin Chary             case 0x48:
1979cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '8' : QEMU_KEY_UP);
19803e230dd2SCorentin Chary                 break;
19813e230dd2SCorentin Chary             case 0x49:
1982cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '9' : QEMU_KEY_PAGEUP);
19833e230dd2SCorentin Chary                 break;
19843e230dd2SCorentin Chary             case 0x4b:
1985cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '4' : QEMU_KEY_LEFT);
19863e230dd2SCorentin Chary                 break;
19873e230dd2SCorentin Chary             case 0x4c:
1988cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, '5');
19893e230dd2SCorentin Chary                 break;
19903e230dd2SCorentin Chary             case 0x4d:
1991cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '6' : QEMU_KEY_RIGHT);
19923e230dd2SCorentin Chary                 break;
19933e230dd2SCorentin Chary             case 0x4f:
1994cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '1' : QEMU_KEY_END);
19953e230dd2SCorentin Chary                 break;
19963e230dd2SCorentin Chary             case 0x50:
1997cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '2' : QEMU_KEY_DOWN);
19983e230dd2SCorentin Chary                 break;
19993e230dd2SCorentin Chary             case 0x51:
2000cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '3' : QEMU_KEY_PAGEDOWN);
20013e230dd2SCorentin Chary                 break;
20023e230dd2SCorentin Chary             case 0x52:
2003cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, '0');
20043e230dd2SCorentin Chary                 break;
20053e230dd2SCorentin Chary             case 0x53:
2006cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, numlock ? '.' : QEMU_KEY_DELETE);
20073e230dd2SCorentin Chary                 break;
20083e230dd2SCorentin Chary 
20093e230dd2SCorentin Chary             case 0xb5:
2010cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, '/');
20113e230dd2SCorentin Chary                 break;
20123e230dd2SCorentin Chary             case 0x37:
2013cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, '*');
20143e230dd2SCorentin Chary                 break;
20153e230dd2SCorentin Chary             case 0x4a:
2016cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, '-');
20173e230dd2SCorentin Chary                 break;
20183e230dd2SCorentin Chary             case 0x4e:
2019cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, '+');
20203e230dd2SCorentin Chary                 break;
20213e230dd2SCorentin Chary             case 0x9c:
2022cc6ba2c6SMarc-André Lureau                 qemu_text_console_put_keysym(NULL, '\n');
20233e230dd2SCorentin Chary                 break;
20243e230dd2SCorentin Chary 
20253e230dd2SCorentin Chary             default:
2026e26437c2SGerd Hoffmann                 if (control) {
2027cc6ba2c6SMarc-André Lureau                     qemu_text_console_put_keysym(NULL, sym & 0x1f);
2028e26437c2SGerd Hoffmann                 } else {
2029cc6ba2c6SMarc-André Lureau                     qemu_text_console_put_keysym(NULL, sym);
2030e26437c2SGerd Hoffmann                 }
20313e230dd2SCorentin Chary                 break;
20323e230dd2SCorentin Chary             }
20333e230dd2SCorentin Chary         }
20343e230dd2SCorentin Chary     }
20353e230dd2SCorentin Chary }
20363e230dd2SCorentin Chary 
203740066175SGerd Hoffmann static const char *code2name(int keycode)
203840066175SGerd Hoffmann {
2039977c736fSMarkus Armbruster     return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
204040066175SGerd Hoffmann }
204140066175SGerd Hoffmann 
20423e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
20433e230dd2SCorentin Chary {
20443e230dd2SCorentin Chary     int keycode;
20453e230dd2SCorentin Chary     int lsym = sym;
20463e230dd2SCorentin Chary 
204781c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
20483e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
20493e230dd2SCorentin Chary     }
20503e230dd2SCorentin Chary 
2051abb4f2c9SGerd Hoffmann     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
205219c1b9fdSGerd Hoffmann                               vs->vd->kbd, down) & SCANCODE_KEYMASK;
205340066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
20543e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
20553e230dd2SCorentin Chary }
20563e230dd2SCorentin Chary 
20573e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
20583e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
20593e230dd2SCorentin Chary {
20603e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
206140066175SGerd Hoffmann     if (keyboard_layout) {
20623e230dd2SCorentin Chary         key_event(vs, down, sym);
206340066175SGerd Hoffmann     } else {
206440066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
20653e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
20663e230dd2SCorentin Chary     }
206740066175SGerd Hoffmann }
20683e230dd2SCorentin Chary 
20693e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
2070bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
20713e230dd2SCorentin Chary {
2072bea60dd7SPeter Lieven     if (incremental) {
2073fef1bbadSDaniel P. Berrange         if (vs->update != VNC_STATE_UPDATE_FORCE) {
2074fef1bbadSDaniel P. Berrange             vs->update = VNC_STATE_UPDATE_INCREMENTAL;
20753e230dd2SCorentin Chary         }
2076fef1bbadSDaniel P. Berrange     } else {
2077fef1bbadSDaniel P. Berrange         vs->update = VNC_STATE_UPDATE_FORCE;
2078f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2079104b8d19SGerd Hoffmann         if (vnc_has_feature(vs, VNC_FEATURE_RESIZE_EXT)) {
2080104b8d19SGerd Hoffmann             vnc_desktop_resize_ext(vs, 0);
2081104b8d19SGerd Hoffmann         }
20823e230dd2SCorentin Chary     }
2083fef1bbadSDaniel P. Berrange }
20843e230dd2SCorentin Chary 
20853e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
20863e230dd2SCorentin Chary {
2087bd023f95SCorentin Chary     vnc_lock_output(vs);
20883e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20893e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20903e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2091d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2092bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2093bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20943e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
2095bd023f95SCorentin Chary     vnc_unlock_output(vs);
20963e230dd2SCorentin Chary     vnc_flush(vs);
20973e230dd2SCorentin Chary }
20983e230dd2SCorentin Chary 
20993e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
21003e230dd2SCorentin Chary {
2101bd023f95SCorentin Chary     vnc_lock_output(vs);
21023e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
21033e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
21043e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2105d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2106bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2107bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
21083e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2109bd023f95SCorentin Chary     vnc_unlock_output(vs);
21103e230dd2SCorentin Chary     vnc_flush(vs);
21113e230dd2SCorentin Chary }
21123e230dd2SCorentin Chary 
21137b5fa0b5SDaniel P. Berrangé static void send_xvp_message(VncState *vs, int code)
21147b5fa0b5SDaniel P. Berrangé {
21157b5fa0b5SDaniel P. Berrangé     vnc_lock_output(vs);
21167b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, VNC_MSG_SERVER_XVP);
21177b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 0); /* pad */
21187b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, 1); /* version */
21197b5fa0b5SDaniel P. Berrangé     vnc_write_u8(vs, code);
21207b5fa0b5SDaniel P. Berrangé     vnc_unlock_output(vs);
21217b5fa0b5SDaniel P. Berrangé     vnc_flush(vs);
21227b5fa0b5SDaniel P. Berrangé }
21237b5fa0b5SDaniel P. Berrangé 
21243e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
21253e230dd2SCorentin Chary {
21263e230dd2SCorentin Chary     int i;
21273e230dd2SCorentin Chary     unsigned int enc = 0;
21283e230dd2SCorentin Chary 
21293e230dd2SCorentin Chary     vs->features = 0;
21303e230dd2SCorentin Chary     vs->vnc_encoding = 0;
21316bf21f3dSLi Qiang     vs->tight->compression = 9;
21326bf21f3dSLi Qiang     vs->tight->quality = -1; /* Lossless by default */
21333e230dd2SCorentin Chary     vs->absolute = -1;
21343e230dd2SCorentin Chary 
21353e230dd2SCorentin Chary     /*
21363e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2137e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
21383e230dd2SCorentin Chary      * will be set at the end of the loop.
21393e230dd2SCorentin Chary      */
21403e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
21413e230dd2SCorentin Chary         enc = encodings[i];
21423e230dd2SCorentin Chary         switch (enc) {
21433e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
21443e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21453e230dd2SCorentin Chary             break;
21463e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
21473e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
21483e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21493e230dd2SCorentin Chary             break;
21503e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
21513e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
21523e230dd2SCorentin Chary             vs->vnc_encoding = enc;
21533e230dd2SCorentin Chary             break;
215495f8510eSKshitij Suri #ifdef CONFIG_PNG
2155efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2156efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2157efe556adSCorentin Chary             vs->vnc_encoding = enc;
2158efe556adSCorentin Chary             break;
2159fe3e7f2dSJoel Martin #endif
21603e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
2161557ba0e5SCameron Esfahani             /*
2162557ba0e5SCameron Esfahani              * VNC_ENCODING_ZRLE compresses better than VNC_ENCODING_ZLIB.
2163557ba0e5SCameron Esfahani              * So prioritize ZRLE, even if the client hints that it prefers
2164557ba0e5SCameron Esfahani              * ZLIB.
2165557ba0e5SCameron Esfahani              */
2166557ba0e5SCameron Esfahani             if ((vs->features & VNC_FEATURE_ZRLE_MASK) == 0) {
21673e230dd2SCorentin Chary                 vs->features |= VNC_FEATURE_ZLIB_MASK;
21683e230dd2SCorentin Chary                 vs->vnc_encoding = enc;
2169557ba0e5SCameron Esfahani             }
21703e230dd2SCorentin Chary             break;
2171148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2172148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2173148954faSCorentin Chary             vs->vnc_encoding = enc;
2174148954faSCorentin Chary             break;
2175148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2176148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2177148954faSCorentin Chary             vs->vnc_encoding = enc;
2178148954faSCorentin Chary             break;
21793e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
21803e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
21813e230dd2SCorentin Chary             break;
2182763deea7SGerd Hoffmann         case VNC_ENCODING_DESKTOP_RESIZE_EXT:
2183763deea7SGerd Hoffmann             vs->features |= VNC_FEATURE_RESIZE_EXT_MASK;
2184763deea7SGerd Hoffmann             break;
21853e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
21863e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
21873e230dd2SCorentin Chary             break;
21883e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
21893e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2190074a86d0SGerd Hoffmann             break;
2191074a86d0SGerd Hoffmann         case VNC_ENCODING_ALPHA_CURSOR:
2192074a86d0SGerd Hoffmann             vs->features |= VNC_FEATURE_ALPHA_CURSOR_MASK;
21933e230dd2SCorentin Chary             break;
21943e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
21953e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
21963e230dd2SCorentin Chary             break;
21973e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
21989e58d7a7SPaolo Bonzini             if (vs->vd->audio_state) {
21999e58d7a7SPaolo Bonzini                 vs->features |= VNC_FEATURE_AUDIO_MASK;
22003e230dd2SCorentin Chary                 send_ext_audio_ack(vs);
22019e58d7a7SPaolo Bonzini             }
22023e230dd2SCorentin Chary             break;
22033e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
22043e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
22053e230dd2SCorentin Chary             break;
2206ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2207ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2208ab99e5c1SLei Li             break;
22097b5fa0b5SDaniel P. Berrangé         case VNC_ENCODING_XVP:
22107b5fa0b5SDaniel P. Berrangé             if (vs->vd->power_control) {
2211477b3010SPaolo Bonzini                 vs->features |= VNC_FEATURE_XVP_MASK;
22127b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_INIT);
22137b5fa0b5SDaniel P. Berrangé             }
22147b5fa0b5SDaniel P. Berrangé             break;
22150bf41cabSGerd Hoffmann         case VNC_ENCODING_CLIPBOARD_EXT:
22160bf41cabSGerd Hoffmann             vs->features |= VNC_FEATURE_CLIPBOARD_EXT_MASK;
22170bf41cabSGerd Hoffmann             vnc_server_cut_text_caps(vs);
22180bf41cabSGerd Hoffmann             break;
22193e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
22206bf21f3dSLi Qiang             vs->tight->compression = (enc & 0x0F);
22213e230dd2SCorentin Chary             break;
22223e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2223b31f519eSCorentin Chary             if (vs->vd->lossy) {
22246bf21f3dSLi Qiang                 vs->tight->quality = (enc & 0x0F);
2225b31f519eSCorentin Chary             }
22263e230dd2SCorentin Chary             break;
22273e230dd2SCorentin Chary         default:
22283e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
22293e230dd2SCorentin Chary             break;
22303e230dd2SCorentin Chary         }
22313e230dd2SCorentin Chary     }
2232d239726cSGerd Hoffmann     vnc_desktop_resize(vs);
22339e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2234d239726cSGerd Hoffmann     vnc_led_state_change(vs);
2235d239726cSGerd Hoffmann     vnc_cursor_define(vs);
2236074a86d0SGerd Hoffmann }
22373e230dd2SCorentin Chary 
22383e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
22393e230dd2SCorentin Chary {
22409f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
22419f64916dSGerd Hoffmann 
22429f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
22433e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
22443e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
22453e230dd2SCorentin Chary     } else {
22463e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
22473e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
22483e230dd2SCorentin Chary     }
22493e230dd2SCorentin Chary }
22503e230dd2SCorentin Chary 
22510c426e45SAlexander Graf static void send_color_map(VncState *vs)
22520c426e45SAlexander Graf {
22530c426e45SAlexander Graf     int i;
22540c426e45SAlexander Graf 
2255947191b4SPeng Liang     vnc_lock_output(vs);
22560c426e45SAlexander Graf     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
22570c426e45SAlexander Graf     vnc_write_u8(vs,  0);    /* padding     */
22580c426e45SAlexander Graf     vnc_write_u16(vs, 0);    /* first color */
22590c426e45SAlexander Graf     vnc_write_u16(vs, 256);  /* # of colors */
22600c426e45SAlexander Graf 
22610c426e45SAlexander Graf     for (i = 0; i < 256; i++) {
22620c426e45SAlexander Graf         PixelFormat *pf = &vs->client_pf;
22630c426e45SAlexander Graf 
22640c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
22650c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
22660c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
22670c426e45SAlexander Graf     }
2268947191b4SPeng Liang     vnc_unlock_output(vs);
22690c426e45SAlexander Graf }
22700c426e45SAlexander Graf 
2271ec9fb41aSGerd Hoffmann static void set_pixel_format(VncState *vs, int bits_per_pixel,
22723e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
22733e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
22743e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
22753e230dd2SCorentin Chary {
22763e230dd2SCorentin Chary     if (!true_color_flag) {
22770c426e45SAlexander Graf         /* Expose a reasonable default 256 color map */
22780c426e45SAlexander Graf         bits_per_pixel = 8;
22790c426e45SAlexander Graf         red_max = 7;
22800c426e45SAlexander Graf         green_max = 7;
22810c426e45SAlexander Graf         blue_max = 3;
22820c426e45SAlexander Graf         red_shift = 0;
22830c426e45SAlexander Graf         green_shift = 3;
22840c426e45SAlexander Graf         blue_shift = 6;
22853e230dd2SCorentin Chary     }
22863e230dd2SCorentin Chary 
2287e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2288e6908bfeSPetr Matousek     case 8:
2289e6908bfeSPetr Matousek     case 16:
2290e6908bfeSPetr Matousek     case 32:
2291e6908bfeSPetr Matousek         break;
2292e6908bfeSPetr Matousek     default:
2293e6908bfeSPetr Matousek         vnc_client_error(vs);
2294e6908bfeSPetr Matousek         return;
2295e6908bfeSPetr Matousek     }
2296e6908bfeSPetr Matousek 
22974c65fed8SPrasad J Pandit     vs->client_pf.rmax = red_max ? red_max : 0xFF;
22987c9209e7SCédric Le Goater     vs->client_pf.rbits = ctpopl(red_max);
22999f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
23009f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
23014c65fed8SPrasad J Pandit     vs->client_pf.gmax = green_max ? green_max : 0xFF;
23027c9209e7SCédric Le Goater     vs->client_pf.gbits = ctpopl(green_max);
23039f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
23049f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
23054c65fed8SPrasad J Pandit     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
23067c9209e7SCédric Le Goater     vs->client_pf.bbits = ctpopl(blue_max);
23079f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
23089f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
23099f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
23109f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
23119f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
23129f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
23133e230dd2SCorentin Chary 
23140c426e45SAlexander Graf     if (!true_color_flag) {
23150c426e45SAlexander Graf         send_color_map(vs);
23160c426e45SAlexander Graf     }
23170c426e45SAlexander Graf 
23183e230dd2SCorentin Chary     set_pixel_conversion(vs);
23193e230dd2SCorentin Chary 
23201d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
23211d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
23223e230dd2SCorentin Chary }
23233e230dd2SCorentin Chary 
23243e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
23253e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
23263e230dd2SCorentin Chary 
23279f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
23289f64916dSGerd Hoffmann 
23299f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
23309f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
23313e230dd2SCorentin Chary 
2332e03b5686SMarc-André Lureau #if HOST_BIG_ENDIAN
23333e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
23343e230dd2SCorentin Chary #else
23353e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
23363e230dd2SCorentin Chary #endif
23373e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
23389f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
23399f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
23409f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
23419f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
23429f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
23439f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
23449f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
23453e230dd2SCorentin Chary 
23463e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
23473e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
23483e230dd2SCorentin Chary }
23493e230dd2SCorentin Chary 
23503e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
23513e230dd2SCorentin Chary {
23523e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
23533e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2354bd023f95SCorentin Chary         vnc_lock_output(vs);
23553e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
23563e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
23573e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2358d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
23593d3a528dSDaniel P. Berrangé                                vs->client_width,
23603d3a528dSDaniel P. Berrangé                                vs->client_height,
2361d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
23623e230dd2SCorentin Chary         pixel_format_message(vs);
2363bd023f95SCorentin Chary         vnc_unlock_output(vs);
23643e230dd2SCorentin Chary         vnc_flush(vs);
23653e230dd2SCorentin Chary     } else {
23663e230dd2SCorentin Chary         set_pixel_conversion(vs);
23673e230dd2SCorentin Chary     }
23683e230dd2SCorentin Chary }
23693e230dd2SCorentin Chary 
23703e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
23713e230dd2SCorentin Chary {
23723e230dd2SCorentin Chary     int i;
23733e230dd2SCorentin Chary     uint16_t limit;
2374cf070658SDaniel P. Berrangé     uint32_t freq;
23753e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
23763e230dd2SCorentin Chary 
23773e230dd2SCorentin Chary     if (data[0] > 3) {
23780f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
23793e230dd2SCorentin Chary     }
23803e230dd2SCorentin Chary 
23813e230dd2SCorentin Chary     switch (data[0]) {
23823e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
23833e230dd2SCorentin Chary         if (len == 1)
23843e230dd2SCorentin Chary             return 20;
23853e230dd2SCorentin Chary 
2386ec9fb41aSGerd Hoffmann         set_pixel_format(vs, read_u8(data, 4),
23873e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
23883e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
23893e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
23903e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
23913e230dd2SCorentin Chary         break;
23923e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
23933e230dd2SCorentin Chary         if (len == 1)
23943e230dd2SCorentin Chary             return 4;
23953e230dd2SCorentin Chary 
23963e230dd2SCorentin Chary         if (len == 4) {
23973e230dd2SCorentin Chary             limit = read_u16(data, 2);
23983e230dd2SCorentin Chary             if (limit > 0)
23993e230dd2SCorentin Chary                 return 4 + (limit * 4);
24003e230dd2SCorentin Chary         } else
24013e230dd2SCorentin Chary             limit = read_u16(data, 2);
24023e230dd2SCorentin Chary 
24033e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
24043e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
24053e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
24063e230dd2SCorentin Chary         }
24073e230dd2SCorentin Chary 
24083e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
24093e230dd2SCorentin Chary         break;
24103e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
24113e230dd2SCorentin Chary         if (len == 1)
24123e230dd2SCorentin Chary             return 10;
24133e230dd2SCorentin Chary 
24143e230dd2SCorentin Chary         framebuffer_update_request(vs,
24153e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
24163e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
24173e230dd2SCorentin Chary         break;
24183e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
24193e230dd2SCorentin Chary         if (len == 1)
24203e230dd2SCorentin Chary             return 8;
24213e230dd2SCorentin Chary 
24223e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
24233e230dd2SCorentin Chary         break;
24243e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
24253e230dd2SCorentin Chary         if (len == 1)
24263e230dd2SCorentin Chary             return 6;
24273e230dd2SCorentin Chary 
24283e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
24293e230dd2SCorentin Chary         break;
24303e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2431f9a70e79SPeter Lieven         if (len == 1) {
24323e230dd2SCorentin Chary             return 8;
2433f9a70e79SPeter Lieven         }
24340bf41cabSGerd Hoffmann         uint32_t dlen = abs(read_s32(data, 4));
2435d307040bSMauro Matteo Cascella         if (len == 8) {
2436f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2437f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2438f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2439f9a70e79SPeter Lieven                 vnc_client_error(vs);
2440f9a70e79SPeter Lieven                 break;
2441f9a70e79SPeter Lieven             }
2442f9a70e79SPeter Lieven             if (dlen > 0) {
24433e230dd2SCorentin Chary                 return 8 + dlen;
24443e230dd2SCorentin Chary             }
2445f9a70e79SPeter Lieven         }
24463e230dd2SCorentin Chary 
24470bf41cabSGerd Hoffmann         if (read_s32(data, 4) < 0) {
2448d307040bSMauro Matteo Cascella             if (dlen < 4) {
2449d307040bSMauro Matteo Cascella                 error_report("vnc: malformed payload (header less than 4 bytes)"
2450d307040bSMauro Matteo Cascella                              " in extended clipboard pseudo-encoding.");
2451d307040bSMauro Matteo Cascella                 vnc_client_error(vs);
2452d307040bSMauro Matteo Cascella                 break;
2453d307040bSMauro Matteo Cascella             }
2454d307040bSMauro Matteo Cascella             vnc_client_cut_text_ext(vs, dlen, read_u32(data, 8), data + 12);
24550bf41cabSGerd Hoffmann             break;
24560bf41cabSGerd Hoffmann         }
24570bf41cabSGerd Hoffmann         vnc_client_cut_text(vs, read_u32(data, 4), data + 8);
24583e230dd2SCorentin Chary         break;
24597b5fa0b5SDaniel P. Berrangé     case VNC_MSG_CLIENT_XVP:
2460477b3010SPaolo Bonzini         if (!vnc_has_feature(vs, VNC_FEATURE_XVP)) {
24617b5fa0b5SDaniel P. Berrangé             error_report("vnc: xvp client message while disabled");
24627b5fa0b5SDaniel P. Berrangé             vnc_client_error(vs);
24637b5fa0b5SDaniel P. Berrangé             break;
24647b5fa0b5SDaniel P. Berrangé         }
24657b5fa0b5SDaniel P. Berrangé         if (len == 1) {
24667b5fa0b5SDaniel P. Berrangé             return 4;
24677b5fa0b5SDaniel P. Berrangé         }
24687b5fa0b5SDaniel P. Berrangé         if (len == 4) {
24697b5fa0b5SDaniel P. Berrangé             uint8_t version = read_u8(data, 2);
24707b5fa0b5SDaniel P. Berrangé             uint8_t action = read_u8(data, 3);
24717b5fa0b5SDaniel P. Berrangé 
24727b5fa0b5SDaniel P. Berrangé             if (version != 1) {
24737b5fa0b5SDaniel P. Berrangé                 error_report("vnc: xvp client message version %d != 1",
24747b5fa0b5SDaniel P. Berrangé                              version);
24757b5fa0b5SDaniel P. Berrangé                 vnc_client_error(vs);
24767b5fa0b5SDaniel P. Berrangé                 break;
24777b5fa0b5SDaniel P. Berrangé             }
24787b5fa0b5SDaniel P. Berrangé 
24797b5fa0b5SDaniel P. Berrangé             switch (action) {
24807b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_SHUTDOWN:
24817b5fa0b5SDaniel P. Berrangé                 qemu_system_powerdown_request();
24827b5fa0b5SDaniel P. Berrangé                 break;
24837b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_REBOOT:
24847b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24857b5fa0b5SDaniel P. Berrangé                 break;
24867b5fa0b5SDaniel P. Berrangé             case VNC_XVP_ACTION_RESET:
24877b5fa0b5SDaniel P. Berrangé                 qemu_system_reset_request(SHUTDOWN_CAUSE_HOST_QMP_SYSTEM_RESET);
24887b5fa0b5SDaniel P. Berrangé                 break;
24897b5fa0b5SDaniel P. Berrangé             default:
24907b5fa0b5SDaniel P. Berrangé                 send_xvp_message(vs, VNC_XVP_CODE_FAIL);
24917b5fa0b5SDaniel P. Berrangé                 break;
24927b5fa0b5SDaniel P. Berrangé             }
24937b5fa0b5SDaniel P. Berrangé         }
24947b5fa0b5SDaniel P. Berrangé         break;
24953e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
24963e230dd2SCorentin Chary         if (len == 1)
24973e230dd2SCorentin Chary             return 2;
24983e230dd2SCorentin Chary 
24993e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
25003e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
25013e230dd2SCorentin Chary             if (len == 2)
25023e230dd2SCorentin Chary                 return 12;
25033e230dd2SCorentin Chary 
25043e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
25053e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
25063e230dd2SCorentin Chary             break;
25073e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
25089e58d7a7SPaolo Bonzini             if (!vnc_has_feature(vs, VNC_FEATURE_AUDIO)) {
25099e58d7a7SPaolo Bonzini                 error_report("Audio message %d with audio disabled", read_u8(data, 2));
25109e58d7a7SPaolo Bonzini                 vnc_client_error(vs);
25119e58d7a7SPaolo Bonzini                 break;
25129e58d7a7SPaolo Bonzini             }
25139e58d7a7SPaolo Bonzini 
25143e230dd2SCorentin Chary             if (len == 2)
25153e230dd2SCorentin Chary                 return 4;
25163e230dd2SCorentin Chary 
25173e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
25183e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2519adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_enable(vs, vs->ioc);
25203e230dd2SCorentin Chary                 audio_add(vs);
25213e230dd2SCorentin Chary                 break;
25223e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2523adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_disable(vs, vs->ioc);
25243e230dd2SCorentin Chary                 audio_del(vs);
25253e230dd2SCorentin Chary                 break;
25263e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
25273e230dd2SCorentin Chary                 if (len == 4)
25283e230dd2SCorentin Chary                     return 10;
25293e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
253085bc5852SKővágó, Zoltán                 case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
253185bc5852SKővágó, Zoltán                 case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
253285bc5852SKővágó, Zoltán                 case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
253385bc5852SKővágó, Zoltán                 case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
253485bc5852SKővágó, Zoltán                 case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
253585bc5852SKővágó, Zoltán                 case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
25363e230dd2SCorentin Chary                 default:
2537153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
25383e230dd2SCorentin Chary                     vnc_client_error(vs);
25393e230dd2SCorentin Chary                     break;
25403e230dd2SCorentin Chary                 }
25413e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
25423e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2543090fdc83SMarc-André Lureau                     VNC_DEBUG("Invalid audio channel count %d\n",
25443e230dd2SCorentin Chary                               read_u8(data, 5));
25453e230dd2SCorentin Chary                     vnc_client_error(vs);
25463e230dd2SCorentin Chary                     break;
25473e230dd2SCorentin Chary                 }
2548cf070658SDaniel P. Berrangé                 freq = read_u32(data, 6);
2549cf070658SDaniel P. Berrangé                 /* No official limit for protocol, but 48khz is a sensible
2550cf070658SDaniel P. Berrangé                  * upper bound for trustworthy clients, and this limit
2551cf070658SDaniel P. Berrangé                  * protects calculations involving 'vs->as.freq' later.
2552cf070658SDaniel P. Berrangé                  */
2553cf070658SDaniel P. Berrangé                 if (freq > 48000) {
2554cf070658SDaniel P. Berrangé                     VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2555cf070658SDaniel P. Berrangé                     vnc_client_error(vs);
2556cf070658SDaniel P. Berrangé                     break;
2557cf070658SDaniel P. Berrangé                 }
2558cf070658SDaniel P. Berrangé                 vs->as.freq = freq;
2559adc8fce8SDaniel P. Berrangé                 trace_vnc_msg_client_audio_format(
2560adc8fce8SDaniel P. Berrangé                     vs, vs->ioc, vs->as.fmt, vs->as.nchannels, vs->as.freq);
25613e230dd2SCorentin Chary                 break;
25623e230dd2SCorentin Chary             default:
25630cb9c588SPaolo Bonzini                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 2));
25643e230dd2SCorentin Chary                 vnc_client_error(vs);
25653e230dd2SCorentin Chary                 break;
25663e230dd2SCorentin Chary             }
25673e230dd2SCorentin Chary             break;
25683e230dd2SCorentin Chary 
25693e230dd2SCorentin Chary         default:
2570153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
25713e230dd2SCorentin Chary             vnc_client_error(vs);
25723e230dd2SCorentin Chary             break;
25733e230dd2SCorentin Chary         }
25743e230dd2SCorentin Chary         break;
2575763deea7SGerd Hoffmann     case VNC_MSG_CLIENT_SET_DESKTOP_SIZE:
2576763deea7SGerd Hoffmann     {
2577763deea7SGerd Hoffmann         size_t size;
2578763deea7SGerd Hoffmann         uint8_t screens;
2579adc8fce8SDaniel P. Berrangé         int w, h;
2580763deea7SGerd Hoffmann 
2581763deea7SGerd Hoffmann         if (len < 8) {
2582763deea7SGerd Hoffmann             return 8;
2583763deea7SGerd Hoffmann         }
2584763deea7SGerd Hoffmann 
2585763deea7SGerd Hoffmann         screens = read_u8(data, 6);
2586763deea7SGerd Hoffmann         size    = 8 + screens * 16;
2587763deea7SGerd Hoffmann         if (len < size) {
2588763deea7SGerd Hoffmann             return size;
2589763deea7SGerd Hoffmann         }
2590adc8fce8SDaniel P. Berrangé         w = read_u16(data, 2);
2591adc8fce8SDaniel P. Berrangé         h = read_u16(data, 4);
2592763deea7SGerd Hoffmann 
2593adc8fce8SDaniel P. Berrangé         trace_vnc_msg_client_set_desktop_size(vs, vs->ioc, w, h, screens);
2594763deea7SGerd Hoffmann         if (dpy_ui_info_supported(vs->vd->dcl.con)) {
2595763deea7SGerd Hoffmann             QemuUIInfo info;
2596763deea7SGerd Hoffmann             memset(&info, 0, sizeof(info));
2597adc8fce8SDaniel P. Berrangé             info.width = w;
2598adc8fce8SDaniel P. Berrangé             info.height = h;
2599ca19ef52SMarc-André Lureau             dpy_set_ui_info(vs->vd->dcl.con, &info, false);
2600763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 4 /* Request forwarded */);
2601763deea7SGerd Hoffmann         } else {
2602763deea7SGerd Hoffmann             vnc_desktop_resize_ext(vs, 3 /* Invalid screen layout */);
2603763deea7SGerd Hoffmann         }
2604763deea7SGerd Hoffmann 
2605763deea7SGerd Hoffmann         break;
2606763deea7SGerd Hoffmann     }
26073e230dd2SCorentin Chary     default:
2608153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
26093e230dd2SCorentin Chary         vnc_client_error(vs);
26103e230dd2SCorentin Chary         break;
26113e230dd2SCorentin Chary     }
26123e230dd2SCorentin Chary 
2613e2b72cb6SDaniel P. Berrange     vnc_update_throttle_offset(vs);
26143e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
26153e230dd2SCorentin Chary     return 0;
26163e230dd2SCorentin Chary }
26173e230dd2SCorentin Chary 
26183e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
26193e230dd2SCorentin Chary {
26203e230dd2SCorentin Chary     char buf[1024];
26218cf36489SGerd Hoffmann     VncShareMode mode;
26223e230dd2SCorentin Chary     int size;
26233e230dd2SCorentin Chary 
26248cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
26258cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
26268cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
26278cf36489SGerd Hoffmann         /*
26288cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
26298cf36489SGerd Hoffmann          *
26308cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
26318cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
26328cf36489SGerd Hoffmann          * reasons.
26338cf36489SGerd Hoffmann          */
26348cf36489SGerd Hoffmann         break;
26358cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
26368cf36489SGerd Hoffmann         /*
26378cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
26388cf36489SGerd Hoffmann          *
26398cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
26408cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
26418cf36489SGerd Hoffmann          * as no exclusive connection exists.
26428cf36489SGerd Hoffmann          *
26438cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
26448cf36489SGerd Hoffmann          */
26458cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
26468cf36489SGerd Hoffmann             VncState *client;
26478cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
26488cf36489SGerd Hoffmann                 if (vs == client) {
26498cf36489SGerd Hoffmann                     continue;
26508cf36489SGerd Hoffmann                 }
26518cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
26528cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
26538cf36489SGerd Hoffmann                     continue;
26548cf36489SGerd Hoffmann                 }
26558cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
26568cf36489SGerd Hoffmann             }
26578cf36489SGerd Hoffmann         }
26588cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
26598cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
26608cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
26618cf36489SGerd Hoffmann                 return 0;
26628cf36489SGerd Hoffmann             }
26638cf36489SGerd Hoffmann         }
26648cf36489SGerd Hoffmann         break;
26658cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
26668cf36489SGerd Hoffmann         /*
26678cf36489SGerd Hoffmann          * Policy: Shared connects only.
26688cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
26698cf36489SGerd Hoffmann          *
26708cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
26718cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
26728cf36489SGerd Hoffmann          * client disconnect everybody else.
26738cf36489SGerd Hoffmann          */
26748cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
26758cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
26768cf36489SGerd Hoffmann             return 0;
26778cf36489SGerd Hoffmann         }
26788cf36489SGerd Hoffmann         break;
26798cf36489SGerd Hoffmann     }
26808cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
26818cf36489SGerd Hoffmann 
2682e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2683e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2684e5f34cddSGerd Hoffmann         return 0;
2685e5f34cddSGerd Hoffmann     }
2686e5f34cddSGerd Hoffmann 
26874c956bd8SDaniel P. Berrange     assert(pixman_image_get_width(vs->vd->server) < 65536 &&
26884c956bd8SDaniel P. Berrange            pixman_image_get_width(vs->vd->server) >= 0);
26894c956bd8SDaniel P. Berrange     assert(pixman_image_get_height(vs->vd->server) < 65536 &&
26904c956bd8SDaniel P. Berrange            pixman_image_get_height(vs->vd->server) >= 0);
2691bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2692bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
26933e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
26943e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
26953e230dd2SCorentin Chary 
26963e230dd2SCorentin Chary     pixel_format_message(vs);
26973e230dd2SCorentin Chary 
269897efe4f9SThomas Huth     if (qemu_name) {
26993e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
270097efe4f9SThomas Huth         if (size > sizeof(buf)) {
270197efe4f9SThomas Huth             size = sizeof(buf);
270297efe4f9SThomas Huth         }
270397efe4f9SThomas Huth     } else {
27043e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
270597efe4f9SThomas Huth     }
27063e230dd2SCorentin Chary 
27073e230dd2SCorentin Chary     vnc_write_u32(vs, size);
27083e230dd2SCorentin Chary     vnc_write(vs, buf, size);
27093e230dd2SCorentin Chary     vnc_flush(vs);
27103e230dd2SCorentin Chary 
27113e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2712fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
27133e230dd2SCorentin Chary 
27143e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
27153e230dd2SCorentin Chary 
27163e230dd2SCorentin Chary     return 0;
27173e230dd2SCorentin Chary }
27183e230dd2SCorentin Chary 
27193e230dd2SCorentin Chary void start_client_init(VncState *vs)
27203e230dd2SCorentin Chary {
27213e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
27223e230dd2SCorentin Chary }
27233e230dd2SCorentin Chary 
27244347e638SRichard Henderson static void authentication_failed(VncState *vs)
27254347e638SRichard Henderson {
27264347e638SRichard Henderson     vnc_write_u32(vs, 1); /* Reject auth */
27274347e638SRichard Henderson     if (vs->minor >= 8) {
27284347e638SRichard Henderson         static const char err[] = "Authentication failed";
27294347e638SRichard Henderson         vnc_write_u32(vs, sizeof(err));
27304347e638SRichard Henderson         vnc_write(vs, err, sizeof(err));
27314347e638SRichard Henderson     }
27324347e638SRichard Henderson     vnc_flush(vs);
27334347e638SRichard Henderson     vnc_client_error(vs);
27344347e638SRichard Henderson }
27354347e638SRichard Henderson 
273683bee4b5SDaniel P. Berrangé static void
273783bee4b5SDaniel P. Berrangé vnc_munge_des_rfb_key(unsigned char *key, size_t nkey)
273883bee4b5SDaniel P. Berrangé {
273983bee4b5SDaniel P. Berrangé     size_t i;
274083bee4b5SDaniel P. Berrangé     for (i = 0; i < nkey; i++) {
274183bee4b5SDaniel P. Berrangé         uint8_t r = key[i];
274283bee4b5SDaniel P. Berrangé         r = (r & 0xf0) >> 4 | (r & 0x0f) << 4;
274383bee4b5SDaniel P. Berrangé         r = (r & 0xcc) >> 2 | (r & 0x33) << 2;
274483bee4b5SDaniel P. Berrangé         r = (r & 0xaa) >> 1 | (r & 0x55) << 1;
274583bee4b5SDaniel P. Berrangé         key[i] = r;
274683bee4b5SDaniel P. Berrangé     }
274783bee4b5SDaniel P. Berrangé }
274883bee4b5SDaniel P. Berrangé 
27493e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
27503e230dd2SCorentin Chary {
27513e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2752800567a6SDaniel P. Berrange     size_t i, pwlen;
27533e230dd2SCorentin Chary     unsigned char key[8];
27543c9405a0SGerd Hoffmann     time_t now = time(NULL);
275560928458SGonglei     QCryptoCipher *cipher = NULL;
2756800567a6SDaniel P. Berrange     Error *err = NULL;
27573e230dd2SCorentin Chary 
27581cd20f8bSAnthony Liguori     if (!vs->vd->password) {
27597364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
27606bffdf0fSGerd Hoffmann         goto reject;
27613e230dd2SCorentin Chary     }
27623c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
27637364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
27643c9405a0SGerd Hoffmann         goto reject;
27653c9405a0SGerd Hoffmann     }
27663e230dd2SCorentin Chary 
27673e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
27683e230dd2SCorentin Chary 
27693e230dd2SCorentin Chary     /* Calculate the expected challenge response */
27703e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
27713e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
27723e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
277383bee4b5SDaniel P. Berrangé     vnc_munge_des_rfb_key(key, sizeof(key));
2774800567a6SDaniel P. Berrange 
2775800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
277683bee4b5SDaniel P. Berrangé         QCRYPTO_CIPHER_ALG_DES,
2777800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2778800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2779800567a6SDaniel P. Berrange         &err);
2780800567a6SDaniel P. Berrange     if (!cipher) {
27817364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2782800567a6SDaniel P. Berrange                             error_get_pretty(err));
2783800567a6SDaniel P. Berrange         error_free(err);
2784800567a6SDaniel P. Berrange         goto reject;
2785800567a6SDaniel P. Berrange     }
2786800567a6SDaniel P. Berrange 
2787a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2788800567a6SDaniel P. Berrange                                vs->challenge,
2789800567a6SDaniel P. Berrange                                response,
2790800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2791800567a6SDaniel P. Berrange                                &err) < 0) {
27927364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2793800567a6SDaniel P. Berrange                             error_get_pretty(err));
2794800567a6SDaniel P. Berrange         error_free(err);
2795800567a6SDaniel P. Berrange         goto reject;
2796800567a6SDaniel P. Berrange     }
27973e230dd2SCorentin Chary 
27983e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
27993e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
28007364dbdaSDaniel P. Berrange         trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
28016bffdf0fSGerd Hoffmann         goto reject;
28026bffdf0fSGerd Hoffmann     } else {
28037364dbdaSDaniel P. Berrange         trace_vnc_auth_pass(vs, vs->auth);
28046bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
28056bffdf0fSGerd Hoffmann         vnc_flush(vs);
28066bffdf0fSGerd Hoffmann 
28076bffdf0fSGerd Hoffmann         start_client_init(vs);
28086bffdf0fSGerd Hoffmann     }
280960928458SGonglei 
281060928458SGonglei     qcrypto_cipher_free(cipher);
28116bffdf0fSGerd Hoffmann     return 0;
28126bffdf0fSGerd Hoffmann 
28136bffdf0fSGerd Hoffmann reject:
28144347e638SRichard Henderson     authentication_failed(vs);
281560928458SGonglei     qcrypto_cipher_free(cipher);
28163e230dd2SCorentin Chary     return 0;
28173e230dd2SCorentin Chary }
28183e230dd2SCorentin Chary 
28193e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
28203e230dd2SCorentin Chary {
2821f7b2502cSRichard Henderson     Error *err = NULL;
2822f7b2502cSRichard Henderson 
2823f7b2502cSRichard Henderson     if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2824f7b2502cSRichard Henderson         trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2825f7b2502cSRichard Henderson                             error_get_pretty(err));
2826f7b2502cSRichard Henderson         error_free(err);
2827f7b2502cSRichard Henderson         authentication_failed(vs);
2828f7b2502cSRichard Henderson         return;
2829f7b2502cSRichard Henderson     }
2830f7b2502cSRichard Henderson 
28313e230dd2SCorentin Chary     /* Send client a 'random' challenge */
28323e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
28333e230dd2SCorentin Chary     vnc_flush(vs);
28343e230dd2SCorentin Chary 
28353e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
28363e230dd2SCorentin Chary }
28373e230dd2SCorentin Chary 
28383e230dd2SCorentin Chary 
28393e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
28403e230dd2SCorentin Chary {
28413e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
28423e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
28437e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
28447364dbdaSDaniel P. Berrange        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
28454347e638SRichard Henderson        authentication_failed(vs);
28463e230dd2SCorentin Chary     } else { /* Accept requested auth */
28477364dbdaSDaniel P. Berrange        trace_vnc_auth_start(vs, vs->auth);
28487e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
28493e230dd2SCorentin Chary        case VNC_AUTH_NONE:
28503e230dd2SCorentin Chary            if (vs->minor >= 8) {
28513e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
28523e230dd2SCorentin Chary                vnc_flush(vs);
28533e230dd2SCorentin Chary            }
28547364dbdaSDaniel P. Berrange            trace_vnc_auth_pass(vs, vs->auth);
28553e230dd2SCorentin Chary            start_client_init(vs);
28563e230dd2SCorentin Chary            break;
28573e230dd2SCorentin Chary 
28583e230dd2SCorentin Chary        case VNC_AUTH_VNC:
28593e230dd2SCorentin Chary            start_auth_vnc(vs);
28603e230dd2SCorentin Chary            break;
28613e230dd2SCorentin Chary 
28623e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
28633e230dd2SCorentin Chary            start_auth_vencrypt(vs);
28643e230dd2SCorentin Chary            break;
28653e230dd2SCorentin Chary 
28663e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
28673e230dd2SCorentin Chary        case VNC_AUTH_SASL:
28683e230dd2SCorentin Chary            start_auth_sasl(vs);
28693e230dd2SCorentin Chary            break;
28703e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
28713e230dd2SCorentin Chary 
28723e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
28737364dbdaSDaniel P. Berrange            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
28744347e638SRichard Henderson            authentication_failed(vs);
28753e230dd2SCorentin Chary        }
28763e230dd2SCorentin Chary     }
28773e230dd2SCorentin Chary     return 0;
28783e230dd2SCorentin Chary }
28793e230dd2SCorentin Chary 
28803e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
28813e230dd2SCorentin Chary {
28823e230dd2SCorentin Chary     char local[13];
28833e230dd2SCorentin Chary 
28843e230dd2SCorentin Chary     memcpy(local, version, 12);
28853e230dd2SCorentin Chary     local[12] = 0;
28863e230dd2SCorentin Chary 
28873e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
28883e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
28893e230dd2SCorentin Chary         vnc_client_error(vs);
28903e230dd2SCorentin Chary         return 0;
28913e230dd2SCorentin Chary     }
28923e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
28933e230dd2SCorentin Chary     if (vs->major != 3 ||
28943e230dd2SCorentin Chary         (vs->minor != 3 &&
28953e230dd2SCorentin Chary          vs->minor != 4 &&
28963e230dd2SCorentin Chary          vs->minor != 5 &&
28973e230dd2SCorentin Chary          vs->minor != 7 &&
28983e230dd2SCorentin Chary          vs->minor != 8)) {
28993e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
29003e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
29013e230dd2SCorentin Chary         vnc_flush(vs);
29023e230dd2SCorentin Chary         vnc_client_error(vs);
29033e230dd2SCorentin Chary         return 0;
29043e230dd2SCorentin Chary     }
29053e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
29063e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
29073e230dd2SCorentin Chary      */
29083e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
29093e230dd2SCorentin Chary         vs->minor = 3;
29103e230dd2SCorentin Chary 
29113e230dd2SCorentin Chary     if (vs->minor == 3) {
29127364dbdaSDaniel P. Berrange         trace_vnc_auth_start(vs, vs->auth);
29137e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
29147e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
29153e230dd2SCorentin Chary             vnc_flush(vs);
29167364dbdaSDaniel P. Berrange             trace_vnc_auth_pass(vs, vs->auth);
29173e230dd2SCorentin Chary             start_client_init(vs);
29187e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
29193e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
29207e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
29213e230dd2SCorentin Chary             vnc_flush(vs);
29223e230dd2SCorentin Chary             start_auth_vnc(vs);
29233e230dd2SCorentin Chary        } else {
29247364dbdaSDaniel P. Berrange             trace_vnc_auth_fail(vs, vs->auth,
29257364dbdaSDaniel P. Berrange                                 "Unsupported auth method for v3.3", "");
29263e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
29273e230dd2SCorentin Chary             vnc_flush(vs);
29283e230dd2SCorentin Chary             vnc_client_error(vs);
29293e230dd2SCorentin Chary        }
29303e230dd2SCorentin Chary     } else {
29313e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
29327e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
29333e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
29343e230dd2SCorentin Chary         vnc_flush(vs);
29353e230dd2SCorentin Chary     }
29363e230dd2SCorentin Chary 
29373e230dd2SCorentin Chary     return 0;
29383e230dd2SCorentin Chary }
29393e230dd2SCorentin Chary 
2940999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2941999342a0SCorentin Chary {
2942999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2943999342a0SCorentin Chary 
2944999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2945999342a0SCorentin Chary }
2946999342a0SCorentin Chary 
29477d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
29487d964c9dSCorentin Chary {
29497d964c9dSCorentin Chary     int i, j;
29507d964c9dSCorentin Chary 
29517d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
29527d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
29537d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
29547d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
29557d964c9dSCorentin Chary 
2956207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2957207f328aSCorentin Chary         for (i = x; i <= w; i++) {
29587d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
29597d964c9dSCorentin Chary         }
29607d964c9dSCorentin Chary     }
29617d964c9dSCorentin Chary }
29627d964c9dSCorentin Chary 
29637d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
29647d964c9dSCorentin Chary {
29657d964c9dSCorentin Chary     VncState *vs;
29667d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
29677d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
29687d964c9dSCorentin Chary     int has_dirty = 0;
29697d964c9dSCorentin Chary 
29705a3804dbSMarc-André Lureau     y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
29715a3804dbSMarc-André Lureau     x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
29727d964c9dSCorentin Chary 
29737d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2974bc2429b9SCorentin Chary         int j;
29757d964c9dSCorentin Chary 
29767d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
29777d964c9dSCorentin Chary         if (vs->output.offset) {
29787d964c9dSCorentin Chary             continue;
29797d964c9dSCorentin Chary         }
29807d964c9dSCorentin Chary 
29817d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
29827d964c9dSCorentin Chary             continue;
29837d964c9dSCorentin Chary         }
2984207f328aSCorentin Chary 
29857d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
29867d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2987b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2988b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2989b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
29907d964c9dSCorentin Chary         }
29917d964c9dSCorentin Chary         has_dirty++;
29927d964c9dSCorentin Chary     }
2993207f328aSCorentin Chary 
29947d964c9dSCorentin Chary     return has_dirty;
29957d964c9dSCorentin Chary }
29967d964c9dSCorentin Chary 
29977d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2998999342a0SCorentin Chary {
2999eebe0b79SGerd Hoffmann     int width = MIN(pixman_image_get_width(vd->guest.fb),
3000eebe0b79SGerd Hoffmann                     pixman_image_get_width(vd->server));
3001eebe0b79SGerd Hoffmann     int height = MIN(pixman_image_get_height(vd->guest.fb),
3002eebe0b79SGerd Hoffmann                      pixman_image_get_height(vd->server));
3003999342a0SCorentin Chary     int x, y;
3004999342a0SCorentin Chary     struct timeval res;
30057d964c9dSCorentin Chary     int has_dirty = 0;
3006999342a0SCorentin Chary 
30079f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
30089f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
3009999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
3010999342a0SCorentin Chary 
3011999342a0SCorentin Chary             rect->updated = false;
3012999342a0SCorentin Chary         }
3013999342a0SCorentin Chary     }
3014999342a0SCorentin Chary 
3015ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
3016999342a0SCorentin Chary 
3017999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
30187d964c9dSCorentin Chary         return has_dirty;
3019999342a0SCorentin Chary     }
3020999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
3021999342a0SCorentin Chary 
30229f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
30239f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
3024999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
3025999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
3026999342a0SCorentin Chary             struct timeval min, max;
3027999342a0SCorentin Chary 
3028999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
3029999342a0SCorentin Chary                 continue ;
3030999342a0SCorentin Chary             }
3031999342a0SCorentin Chary 
3032999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
3033ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
3034999342a0SCorentin Chary 
3035999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
3036999342a0SCorentin Chary                 rect->freq = 0;
30377d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
3038999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
3039999342a0SCorentin Chary                 continue ;
3040999342a0SCorentin Chary             }
3041999342a0SCorentin Chary 
3042999342a0SCorentin Chary             min = rect->times[rect->idx];
3043999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
3044ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
3045999342a0SCorentin Chary 
3046999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
3047999342a0SCorentin Chary             rect->freq /= count;
3048999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
3049999342a0SCorentin Chary         }
3050999342a0SCorentin Chary     }
30517d964c9dSCorentin Chary     return has_dirty;
3052999342a0SCorentin Chary }
3053999342a0SCorentin Chary 
3054999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
3055999342a0SCorentin Chary {
3056999342a0SCorentin Chary     int i, j;
3057999342a0SCorentin Chary     double total = 0;
3058999342a0SCorentin Chary     int num = 0;
3059999342a0SCorentin Chary 
30605a3804dbSMarc-André Lureau     x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
30615a3804dbSMarc-André Lureau     y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
3062999342a0SCorentin Chary 
3063999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
3064999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
3065999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
3066999342a0SCorentin Chary             num++;
3067999342a0SCorentin Chary         }
3068999342a0SCorentin Chary     }
3069999342a0SCorentin Chary 
3070999342a0SCorentin Chary     if (num) {
3071999342a0SCorentin Chary         return total / num;
3072999342a0SCorentin Chary     } else {
3073999342a0SCorentin Chary         return 0;
3074999342a0SCorentin Chary     }
3075999342a0SCorentin Chary }
3076999342a0SCorentin Chary 
3077999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
3078999342a0SCorentin Chary {
3079999342a0SCorentin Chary     VncRectStat *rect;
3080999342a0SCorentin Chary 
3081999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
3082999342a0SCorentin Chary     if (rect->updated) {
3083999342a0SCorentin Chary         return;
3084999342a0SCorentin Chary     }
3085999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
3086999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
3087999342a0SCorentin Chary     rect->updated = true;
3088999342a0SCorentin Chary }
3089999342a0SCorentin Chary 
30903e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
30913e230dd2SCorentin Chary {
3092bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
3093bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
3094bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
3095bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
3096eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
309712b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
30983e230dd2SCorentin Chary     VncState *vs;
30993e230dd2SCorentin Chary     int has_dirty = 0;
31009f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
31016c08964bSWen, Jianxian     unsigned long offset;
31026c08964bSWen, Jianxian     int x;
31036c08964bSWen, Jianxian     uint8_t *guest_ptr, *server_ptr;
31043e230dd2SCorentin Chary 
310580e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
3106999342a0SCorentin Chary 
310780e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
3108999342a0SCorentin Chary         gettimeofday(&tv, NULL);
31097d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
311080e0c8c3SCorentin Chary     }
3111999342a0SCorentin Chary 
31126c08964bSWen, Jianxian     offset = find_next_bit((unsigned long *) &vd->guest.dirty,
31136c08964bSWen, Jianxian                            height * VNC_DIRTY_BPL(&vd->guest), 0);
31146c08964bSWen, Jianxian     if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
31156c08964bSWen, Jianxian         /* no dirty bits in guest surface */
31166c08964bSWen, Jianxian         return has_dirty;
31176c08964bSWen, Jianxian     }
31186c08964bSWen, Jianxian 
31193e230dd2SCorentin Chary     /*
31203e230dd2SCorentin Chary      * Walk through the guest dirty map.
31213e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
31223e230dd2SCorentin Chary      * Update server dirty map.
31233e230dd2SCorentin Chary      */
3124bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
3125eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
3126eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
3127bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
3128bea60dd7SPeter Lieven                     server_stride);
31299f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
31309f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
31319f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
313212b316d4SPeter Lieven     } else {
3133eb8934b0SGerd Hoffmann         int guest_bpp =
3134eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
313512b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
313612b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
3137949ed4c2SPhilippe Mathieu-Daudé         guest_ll = pixman_image_get_width(vd->guest.fb)
3138949ed4c2SPhilippe Mathieu-Daudé                    * DIV_ROUND_UP(guest_bpp, 8);
31399f64916dSGerd Hoffmann     }
3140eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
314112b316d4SPeter Lieven 
314212b316d4SPeter Lieven     for (;;) {
314312b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
314412b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
314512b316d4SPeter Lieven 
314612b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
31473e230dd2SCorentin Chary 
31489f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
3149bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
31509f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
31519f64916dSGerd Hoffmann         } else {
315212b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
31539f64916dSGerd Hoffmann         }
315412b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
31553e230dd2SCorentin Chary 
315612b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
315712b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
3158bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
315912b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
31603e230dd2SCorentin Chary                 continue;
3161b4c85ddcSPeter Lieven             }
3162eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
3163eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
3164bea60dd7SPeter Lieven             }
3165eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
3166bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
31673e230dd2SCorentin Chary                 continue;
3168b4c85ddcSPeter Lieven             }
3169bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
317012b316d4SPeter Lieven             if (!vd->non_adaptive) {
317112b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
317212b316d4SPeter Lieven                                  y, &tv);
317312b316d4SPeter Lieven             }
31743e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
317512b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
31763e230dd2SCorentin Chary             }
31773e230dd2SCorentin Chary             has_dirty++;
31783e230dd2SCorentin Chary         }
317912b316d4SPeter Lieven 
318012b316d4SPeter Lieven         y++;
31816c08964bSWen, Jianxian         offset = find_next_bit((unsigned long *) &vd->guest.dirty,
31826c08964bSWen, Jianxian                                height * VNC_DIRTY_BPL(&vd->guest),
31836c08964bSWen, Jianxian                                y * VNC_DIRTY_BPL(&vd->guest));
31846c08964bSWen, Jianxian         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
31856c08964bSWen, Jianxian             /* no more dirty bits */
31866c08964bSWen, Jianxian             break;
31876c08964bSWen, Jianxian         }
31883e230dd2SCorentin Chary     }
31899f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
31903e230dd2SCorentin Chary     return has_dirty;
31913e230dd2SCorentin Chary }
31923e230dd2SCorentin Chary 
31930f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
31943e230dd2SCorentin Chary {
31950f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
31963e230dd2SCorentin Chary     VncState *vs, *vn;
31973e230dd2SCorentin Chary     int has_dirty, rects = 0;
31983e230dd2SCorentin Chary 
31999d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
32009d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
32019d6b2070SChenLiang         return;
32029d6b2070SChenLiang     }
32039d6b2070SChenLiang 
32041d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
32053e230dd2SCorentin Chary 
3206bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
32070f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3208bd023f95SCorentin Chary         return;
3209bd023f95SCorentin Chary     }
3210bd023f95SCorentin Chary 
32113e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
3212bd023f95SCorentin Chary     vnc_unlock_display(vd);
32133e230dd2SCorentin Chary 
32143e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
32156af998dbSDaniel P. Berrange         rects += vnc_update_client(vs, has_dirty);
32163e230dd2SCorentin Chary         /* vs might be free()ed here */
32173e230dd2SCorentin Chary     }
3218bd023f95SCorentin Chary 
32193e230dd2SCorentin Chary     if (has_dirty && rects) {
32200f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
32210f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
32220f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
32230f7b2864SGerd Hoffmann         }
32243e230dd2SCorentin Chary     } else {
32250f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
32260f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
32270f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
32283e230dd2SCorentin Chary         }
32293e230dd2SCorentin Chary     }
32303e230dd2SCorentin Chary }
32313e230dd2SCorentin Chary 
323204d2529dSDaniel P. Berrange static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
32332c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
32343e230dd2SCorentin Chary {
3235fedf0d35SMarkus Armbruster     VncState *vs = g_new0(VncState, 1);
323690cd03a3SDaniel P. Berrange     bool first_client = QTAILQ_EMPTY(&vd->clients);
32377d964c9dSCorentin Chary     int i;
32387d964c9dSCorentin Chary 
3239ad6374c4SDaniel P. Berrange     trace_vnc_client_connect(vs, sioc);
32406bf21f3dSLi Qiang     vs->zrle = g_new0(VncZrle, 1);
32416bf21f3dSLi Qiang     vs->tight = g_new0(VncTight, 1);
3242f31f9c10SGerd Hoffmann     vs->magic = VNC_MAGIC;
324304d2529dSDaniel P. Berrange     vs->sioc = sioc;
324404d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->sioc));
324504d2529dSDaniel P. Berrange     vs->ioc = QIO_CHANNEL(sioc);
324604d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->ioc));
3247d616ccc5SGerd Hoffmann     vs->vd = vd;
32487e7e2ebcSDaniel P. Berrange 
324904d2529dSDaniel P. Berrange     buffer_init(&vs->input,          "vnc-input/%p", sioc);
325004d2529dSDaniel P. Berrange     buffer_init(&vs->output,         "vnc-output/%p", sioc);
325104d2529dSDaniel P. Berrange     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3252543b9580SGerd Hoffmann 
32536bf21f3dSLi Qiang     buffer_init(&vs->tight->tight,    "vnc-tight/%p", sioc);
32546bf21f3dSLi Qiang     buffer_init(&vs->tight->zlib,     "vnc-tight-zlib/%p", sioc);
32556bf21f3dSLi Qiang     buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3256543b9580SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
32576bf21f3dSLi Qiang     buffer_init(&vs->tight->jpeg,     "vnc-tight-jpeg/%p", sioc);
3258543b9580SGerd Hoffmann #endif
325995f8510eSKshitij Suri #ifdef CONFIG_PNG
32606bf21f3dSLi Qiang     buffer_init(&vs->tight->png,      "vnc-tight-png/%p", sioc);
3261543b9580SGerd Hoffmann #endif
326204d2529dSDaniel P. Berrange     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
32636bf21f3dSLi Qiang     buffer_init(&vs->zrle->zrle,      "vnc-zrle/%p", sioc);
32646bf21f3dSLi Qiang     buffer_init(&vs->zrle->fb,        "vnc-zrle-fb/%p", sioc);
32656bf21f3dSLi Qiang     buffer_init(&vs->zrle->zlib,      "vnc-zrle-zlib/%p", sioc);
3266543b9580SGerd Hoffmann 
32677e7e2ebcSDaniel P. Berrange     if (skipauth) {
32687e7e2ebcSDaniel P. Berrange         vs->auth = VNC_AUTH_NONE;
32697e7e2ebcSDaniel P. Berrange         vs->subauth = VNC_AUTH_INVALID;
32707e7e2ebcSDaniel P. Berrange     } else {
3271f9148c8aSDaniel P. Berrange         if (websocket) {
3272f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
3273f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
3274f9148c8aSDaniel P. Berrange         } else {
32757e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
32767e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
32777e7e2ebcSDaniel P. Berrange         }
3278f9148c8aSDaniel P. Berrange     }
327904d2529dSDaniel P. Berrange     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
328004d2529dSDaniel P. Berrange               sioc, websocket, vs->auth, vs->subauth);
32817e7e2ebcSDaniel P. Berrange 
32827267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
32837d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3284fedf0d35SMarkus Armbruster         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
32857d964c9dSCorentin Chary     }
32863e230dd2SCorentin Chary 
328704d2529dSDaniel P. Berrange     VNC_DEBUG("New client on socket %p\n", vs->sioc);
32880f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
328904d2529dSDaniel P. Berrange     qio_channel_set_blocking(vs->ioc, false, NULL);
3290a75d6f07SBrandon Carpenter     if (vs->ioc_tag) {
3291a75d6f07SBrandon Carpenter         g_source_remove(vs->ioc_tag);
3292a75d6f07SBrandon Carpenter     }
32937536ee4bSTim Hardeck     if (websocket) {
32947536ee4bSTim Hardeck         vs->websocket = 1;
329538e5756aSDaniel P. Berrange         if (vd->tlscreds) {
329604d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
32972ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
32982ddafce7SDing Hui                 vncws_tls_handshake_io, vs, NULL);
32993e305e4aSDaniel P. Berrange         } else {
330004d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
33012ddafce7SDing Hui                 vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
33022ddafce7SDing Hui                 vncws_handshake_io, vs, NULL);
33030057a0d5STim Hardeck         }
330404d2529dSDaniel P. Berrange     } else {
330504d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
33062ddafce7SDing Hui             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
33072ddafce7SDing Hui             vnc_client_io, vs, NULL);
33087536ee4bSTim Hardeck     }
33093e230dd2SCorentin Chary 
33103e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3311fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
33128cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
33133e230dd2SCorentin Chary 
33143e230dd2SCorentin Chary     vs->last_x = -1;
33153e230dd2SCorentin Chary     vs->last_y = -1;
33163e230dd2SCorentin Chary 
33173e230dd2SCorentin Chary     vs->as.freq = 44100;
33183e230dd2SCorentin Chary     vs->as.nchannels = 2;
331985bc5852SKővágó, Zoltán     vs->as.fmt = AUDIO_FORMAT_S16;
33203e230dd2SCorentin Chary     vs->as.endianness = 0;
33213e230dd2SCorentin Chary 
3322bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3323175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3324bd023f95SCorentin Chary 
3325e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3326c7628bffSGerd Hoffmann     if (first_client) {
3327c7628bffSGerd Hoffmann         vnc_update_server_surface(vd);
3328c7628bffSGerd Hoffmann     }
33293e230dd2SCorentin Chary 
33301d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
33313e230dd2SCorentin Chary 
333290cd03a3SDaniel P. Berrange     if (!vs->websocket) {
3333dbee9897SDaniel P. Berrange         vnc_start_protocol(vs);
333490cd03a3SDaniel P. Berrange     }
333590cd03a3SDaniel P. Berrange 
333690cd03a3SDaniel P. Berrange     if (vd->num_connecting > vd->connections_limit) {
333790cd03a3SDaniel P. Berrange         QTAILQ_FOREACH(vs, &vd->clients, next) {
333890cd03a3SDaniel P. Berrange             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
333990cd03a3SDaniel P. Berrange                 vnc_disconnect_start(vs);
334090cd03a3SDaniel P. Berrange                 return;
334190cd03a3SDaniel P. Berrange             }
334290cd03a3SDaniel P. Berrange         }
334390cd03a3SDaniel P. Berrange     }
334490cd03a3SDaniel P. Berrange }
334590cd03a3SDaniel P. Berrange 
3346dbee9897SDaniel P. Berrange void vnc_start_protocol(VncState *vs)
334790cd03a3SDaniel P. Berrange {
33483e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
33493e230dd2SCorentin Chary     vnc_flush(vs);
33503e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
33513e230dd2SCorentin Chary 
33523e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
33533e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
33543e230dd2SCorentin Chary }
33553e230dd2SCorentin Chary 
335613e1d0e7SDaniel P. Berrange static void vnc_listen_io(QIONetListener *listener,
335713e1d0e7SDaniel P. Berrange                           QIOChannelSocket *cioc,
335804d2529dSDaniel P. Berrange                           void *opaque)
33593e230dd2SCorentin Chary {
3360bf01c179SDaniel P. Berrange     VncDisplay *vd = opaque;
336113e1d0e7SDaniel P. Berrange     bool isWebsock = listener == vd->wslistener;
33624ee74fa7SDaniel P. Berrange 
336313e1d0e7SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(cioc),
33644ee74fa7SDaniel P. Berrange                          isWebsock ? "vnc-ws-server" : "vnc-server");
336513e1d0e7SDaniel P. Berrange     qio_channel_set_delay(QIO_CHANNEL(cioc), false);
336613e1d0e7SDaniel P. Berrange     vnc_connect(vd, cioc, false, isWebsock);
33677536ee4bSTim Hardeck }
33687536ee4bSTim Hardeck 
33697c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
33707c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
33710f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
33727c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3373c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
337434da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
33757c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
33767c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
33777c20b4a3SGerd Hoffmann };
33787c20b4a3SGerd Hoffmann 
3379ab4f931eSFei Li void vnc_display_init(const char *id, Error **errp)
33803e230dd2SCorentin Chary {
3381bf01c179SDaniel P. Berrange     VncDisplay *vd;
33824db14629SGerd Hoffmann 
33834db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
33844db14629SGerd Hoffmann         return;
33854db14629SGerd Hoffmann     }
3386bf01c179SDaniel P. Berrange     vd = g_malloc0(sizeof(*vd));
33873e230dd2SCorentin Chary 
3388bf01c179SDaniel P. Berrange     vd->id = strdup(id);
3389bf01c179SDaniel P. Berrange     QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
33903e230dd2SCorentin Chary 
3391bf01c179SDaniel P. Berrange     QTAILQ_INIT(&vd->clients);
3392bf01c179SDaniel P. Berrange     vd->expires = TIME_MAX;
33933e230dd2SCorentin Chary 
339440066175SGerd Hoffmann     if (keyboard_layout) {
339540066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
3396ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym,
3397ab4f931eSFei Li                                               keyboard_layout, errp);
339840066175SGerd Hoffmann     } else {
3399ab4f931eSFei Li         vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
340040066175SGerd Hoffmann     }
34013e230dd2SCorentin Chary 
3402bf01c179SDaniel P. Berrange     if (!vd->kbd_layout) {
3403ab4f931eSFei Li         return;
3404bf01c179SDaniel P. Berrange     }
34053e230dd2SCorentin Chary 
3406bf01c179SDaniel P. Berrange     vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3407bf01c179SDaniel P. Berrange     vd->connections_limit = 32;
340812e29b16SDaniel P. Berrange 
3409bf01c179SDaniel P. Berrange     qemu_mutex_init(&vd->mutex);
3410bd023f95SCorentin Chary     vnc_start_worker_thread();
3411bd023f95SCorentin Chary 
3412bf01c179SDaniel P. Berrange     vd->dcl.ops = &dcl_ops;
3413bf01c179SDaniel P. Berrange     register_displaychangelistener(&vd->dcl);
3414c2f2ba49SGerd Hoffmann     vd->kbd = qkbd_state_init(vd->dcl.con);
34153e230dd2SCorentin Chary }
34163e230dd2SCorentin Chary 
34173e230dd2SCorentin Chary 
3418bf01c179SDaniel P. Berrange static void vnc_display_close(VncDisplay *vd)
34193e230dd2SCorentin Chary {
3420bf01c179SDaniel P. Berrange     if (!vd) {
34213e230dd2SCorentin Chary         return;
342204d2529dSDaniel P. Berrange     }
3423bf01c179SDaniel P. Berrange     vd->is_unix = false;
34244ee74fa7SDaniel P. Berrange 
342513e1d0e7SDaniel P. Berrange     if (vd->listener) {
342613e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->listener);
342713e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->listener));
342804d2529dSDaniel P. Berrange     }
342913e1d0e7SDaniel P. Berrange     vd->listener = NULL;
343013e1d0e7SDaniel P. Berrange 
343113e1d0e7SDaniel P. Berrange     if (vd->wslistener) {
343213e1d0e7SDaniel P. Berrange         qio_net_listener_disconnect(vd->wslistener);
343313e1d0e7SDaniel P. Berrange         object_unref(OBJECT(vd->wslistener));
34347536ee4bSTim Hardeck     }
343513e1d0e7SDaniel P. Berrange     vd->wslistener = NULL;
34364ee74fa7SDaniel P. Berrange 
3437bf01c179SDaniel P. Berrange     vd->auth = VNC_AUTH_INVALID;
3438bf01c179SDaniel P. Berrange     vd->subauth = VNC_AUTH_INVALID;
3439bf01c179SDaniel P. Berrange     if (vd->tlscreds) {
3440521534dfSZihao Chang         object_unref(OBJECT(vd->tlscreds));
3441bf01c179SDaniel P. Berrange         vd->tlscreds = NULL;
3442bf01c179SDaniel P. Berrange     }
3443b76806d4SDaniel P. Berrange     if (vd->tlsauthz) {
3444b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->tlsauthz));
3445b76806d4SDaniel P. Berrange         vd->tlsauthz = NULL;
3446b76806d4SDaniel P. Berrange     }
3447b76806d4SDaniel P. Berrange     g_free(vd->tlsauthzid);
3448b76806d4SDaniel P. Berrange     vd->tlsauthzid = NULL;
3449a54f0d2bSPierre Ossman     if (vd->lock_key_sync) {
3450a54f0d2bSPierre Ossman         qemu_remove_led_event_handler(vd->led);
34512dc120beSGerd Hoffmann         vd->led = NULL;
3452a54f0d2bSPierre Ossman     }
3453b76806d4SDaniel P. Berrange #ifdef CONFIG_VNC_SASL
3454b76806d4SDaniel P. Berrange     if (vd->sasl.authz) {
3455b76806d4SDaniel P. Berrange         object_unparent(OBJECT(vd->sasl.authz));
3456b76806d4SDaniel P. Berrange         vd->sasl.authz = NULL;
3457b76806d4SDaniel P. Berrange     }
3458b76806d4SDaniel P. Berrange     g_free(vd->sasl.authzid);
3459b76806d4SDaniel P. Berrange     vd->sasl.authzid = NULL;
3460b76806d4SDaniel P. Berrange #endif
34613e230dd2SCorentin Chary }
34623e230dd2SCorentin Chary 
346314f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
34641cd20f8bSAnthony Liguori {
3465bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
34661cd20f8bSAnthony Liguori 
3467bf01c179SDaniel P. Berrange     if (!vd) {
3468a6aa9d3eSLuiz Capitulino         return -EINVAL;
34691cd20f8bSAnthony Liguori     }
3470bf01c179SDaniel P. Berrange     if (vd->auth == VNC_AUTH_NONE) {
3471cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
34727ea7d36eSMarkus Armbruster                                 "password auth using '-vnc ${dpy},password'.\n");
3473cf864569SGerd Hoffmann         return -EINVAL;
34741cd20f8bSAnthony Liguori     }
34751cd20f8bSAnthony Liguori 
3476bf01c179SDaniel P. Berrange     g_free(vd->password);
3477bf01c179SDaniel P. Berrange     vd->password = g_strdup(password);
3478a6aa9d3eSLuiz Capitulino 
3479a6aa9d3eSLuiz Capitulino     return 0;
34803e230dd2SCorentin Chary }
34813e230dd2SCorentin Chary 
348214f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
34833c9405a0SGerd Hoffmann {
3484bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
34853c9405a0SGerd Hoffmann 
3486bf01c179SDaniel P. Berrange     if (!vd) {
34871643f2b2SGerd Hoffmann         return -EINVAL;
34881643f2b2SGerd Hoffmann     }
34891643f2b2SGerd Hoffmann 
3490bf01c179SDaniel P. Berrange     vd->expires = expires;
34913c9405a0SGerd Hoffmann     return 0;
34923c9405a0SGerd Hoffmann }
34933c9405a0SGerd Hoffmann 
3494bf01c179SDaniel P. Berrange static void vnc_display_print_local_addr(VncDisplay *vd)
34953e230dd2SCorentin Chary {
3496bd269ebcSMarkus Armbruster     SocketAddress *addr;
34973e230dd2SCorentin Chary 
349813e1d0e7SDaniel P. Berrange     if (!vd->listener || !vd->listener->nsioc) {
34994ee74fa7SDaniel P. Berrange         return;
35004ee74fa7SDaniel P. Berrange     }
35014ee74fa7SDaniel P. Berrange 
3502b94b3c02SMarkus Armbruster     addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], NULL);
350304d2529dSDaniel P. Berrange     if (!addr) {
350433df7bf3SPaolo Bonzini         return;
350504d2529dSDaniel P. Berrange     }
350604d2529dSDaniel P. Berrange 
3507bd269ebcSMarkus Armbruster     if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3508bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
350933df7bf3SPaolo Bonzini         return;
351004d2529dSDaniel P. Berrange     }
351133df7bf3SPaolo Bonzini     error_printf_unless_qmp("VNC server running on %s:%s\n",
3512bd269ebcSMarkus Armbruster                             addr->u.inet.host,
3513bd269ebcSMarkus Armbruster                             addr->u.inet.port);
3514bd269ebcSMarkus Armbruster     qapi_free_SocketAddress(addr);
35153e230dd2SCorentin Chary }
35163e230dd2SCorentin Chary 
35174db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
35184db14629SGerd Hoffmann     .name = "vnc",
35194db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
35204db14629SGerd Hoffmann     .implied_opt_name = "vnc",
35214db14629SGerd Hoffmann     .desc = {
35224db14629SGerd Hoffmann         {
35234db14629SGerd Hoffmann             .name = "vnc",
35244db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
35254db14629SGerd Hoffmann         },{
35264db14629SGerd Hoffmann             .name = "websocket",
35274db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
35284db14629SGerd Hoffmann         },{
35293e305e4aSDaniel P. Berrange             .name = "tls-creds",
35303e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
35313e305e4aSDaniel P. Berrange         },{
35324db14629SGerd Hoffmann             .name = "share",
35334db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
35344db14629SGerd Hoffmann         },{
35351d0d59feSGerd Hoffmann             .name = "display",
35361d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
35371d0d59feSGerd Hoffmann         },{
35381d0d59feSGerd Hoffmann             .name = "head",
35391d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
35401d0d59feSGerd Hoffmann         },{
3541e5f34cddSGerd Hoffmann             .name = "connections",
3542e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3543e5f34cddSGerd Hoffmann         },{
354488428b7aSGonglei             .name = "to",
354588428b7aSGonglei             .type = QEMU_OPT_NUMBER,
354688428b7aSGonglei         },{
354788428b7aSGonglei             .name = "ipv4",
354888428b7aSGonglei             .type = QEMU_OPT_BOOL,
354988428b7aSGonglei         },{
355088428b7aSGonglei             .name = "ipv6",
355188428b7aSGonglei             .type = QEMU_OPT_BOOL,
355288428b7aSGonglei         },{
35534db14629SGerd Hoffmann             .name = "password",
35544db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35554db14629SGerd Hoffmann         },{
35566c6840e9SDaniel P. Berrangé             .name = "password-secret",
35576c6840e9SDaniel P. Berrangé             .type = QEMU_OPT_STRING,
35586c6840e9SDaniel P. Berrangé         },{
35594db14629SGerd Hoffmann             .name = "reverse",
35604db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35614db14629SGerd Hoffmann         },{
35624db14629SGerd Hoffmann             .name = "lock-key-sync",
35634db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35644db14629SGerd Hoffmann         },{
3565c5ce8333SGerd Hoffmann             .name = "key-delay-ms",
3566c5ce8333SGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3567c5ce8333SGerd Hoffmann         },{
35684db14629SGerd Hoffmann             .name = "sasl",
35694db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35704db14629SGerd Hoffmann         },{
357155cf09a0SDaniel P. Berrange             .name = "tls-authz",
357255cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
357355cf09a0SDaniel P. Berrange         },{
357455cf09a0SDaniel P. Berrange             .name = "sasl-authz",
357555cf09a0SDaniel P. Berrange             .type = QEMU_OPT_STRING,
357655cf09a0SDaniel P. Berrange         },{
35774db14629SGerd Hoffmann             .name = "lossy",
35784db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
35794db14629SGerd Hoffmann         },{
35804db14629SGerd Hoffmann             .name = "non-adaptive",
35814db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
3582f0b9f36dSKővágó, Zoltán         },{
3583f0b9f36dSKővágó, Zoltán             .name = "audiodev",
3584f0b9f36dSKővágó, Zoltán             .type = QEMU_OPT_STRING,
35857b5fa0b5SDaniel P. Berrangé         },{
35867b5fa0b5SDaniel P. Berrangé             .name = "power-control",
35877b5fa0b5SDaniel P. Berrangé             .type = QEMU_OPT_BOOL,
35884db14629SGerd Hoffmann         },
35894db14629SGerd Hoffmann         { /* end of list */ }
35904db14629SGerd Hoffmann     },
35914db14629SGerd Hoffmann };
35924db14629SGerd Hoffmann 
35930dd72e15SDaniel P. Berrange 
35943e305e4aSDaniel P. Berrange static int
3595eda24e18SDaniel P. Berrange vnc_display_setup_auth(int *auth,
3596eda24e18SDaniel P. Berrange                        int *subauth,
3597eda24e18SDaniel P. Berrange                        QCryptoTLSCreds *tlscreds,
35980dd72e15SDaniel P. Berrange                        bool password,
35990dd72e15SDaniel P. Berrange                        bool sasl,
36003e305e4aSDaniel P. Berrange                        bool websocket,
36013e305e4aSDaniel P. Berrange                        Error **errp)
36020dd72e15SDaniel P. Berrange {
36030dd72e15SDaniel P. Berrange     /*
36040dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
36050dd72e15SDaniel P. Berrange      *
36060dd72e15SDaniel P. Berrange      *   1. none
36070dd72e15SDaniel P. Berrange      *   2. vnc
36080dd72e15SDaniel P. Berrange      *   3. sasl
36090dd72e15SDaniel P. Berrange      *
36100dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
36110dd72e15SDaniel P. Berrange      *
36120dd72e15SDaniel P. Berrange      *   1. clear
36130dd72e15SDaniel P. Berrange      *   2. tls
36140dd72e15SDaniel P. Berrange      *
36150dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
36160dd72e15SDaniel P. Berrange      *
36170dd72e15SDaniel P. Berrange      *   1. anon
36180dd72e15SDaniel P. Berrange      *   2. x509
36190dd72e15SDaniel P. Berrange      *
36200dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
36210dd72e15SDaniel P. Berrange      *
36220dd72e15SDaniel P. Berrange      *   1. clear + none
36230dd72e15SDaniel P. Berrange      *   2. clear + vnc
36240dd72e15SDaniel P. Berrange      *   3. clear + sasl
36250dd72e15SDaniel P. Berrange      *   4. tls + anon + none
36260dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
36270dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
36280dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
36290dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
36300dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
36310dd72e15SDaniel P. Berrange      *
36320dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
36330dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
36340dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
36350dd72e15SDaniel P. Berrange      * sub-auth types.
3636f9148c8aSDaniel P. Berrange      *
3637f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3638f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3639f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3640f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3641f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3642f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3643f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3644f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3645f9148c8aSDaniel P. Berrange      *
3646f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3647f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3648f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
36490dd72e15SDaniel P. Berrange      */
3650eda24e18SDaniel P. Berrange     if (websocket || !tlscreds) {
36510dd72e15SDaniel P. Berrange         if (password) {
36520dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
3653eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_VNC;
36540dd72e15SDaniel P. Berrange         } else if (sasl) {
36550dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3656eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_SASL;
36570dd72e15SDaniel P. Berrange         } else {
36580dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
3659eda24e18SDaniel P. Berrange             *auth = VNC_AUTH_NONE;
36600dd72e15SDaniel P. Berrange         }
3661eda24e18SDaniel P. Berrange         *subauth = VNC_AUTH_INVALID;
3662f9148c8aSDaniel P. Berrange     } else {
3663eda24e18SDaniel P. Berrange         bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3664eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3665eda24e18SDaniel P. Berrange         bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3666eda24e18SDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3667eda24e18SDaniel P. Berrange 
3668eda24e18SDaniel P. Berrange         if (!is_x509 && !is_anon) {
3669eda24e18SDaniel P. Berrange             error_setg(errp,
3670eda24e18SDaniel P. Berrange                        "Unsupported TLS cred type %s",
3671eda24e18SDaniel P. Berrange                        object_get_typename(OBJECT(tlscreds)));
3672eda24e18SDaniel P. Berrange             return -1;
3673eda24e18SDaniel P. Berrange         }
3674eda24e18SDaniel P. Berrange         *auth = VNC_AUTH_VENCRYPT;
3675eda24e18SDaniel P. Berrange         if (password) {
3676eda24e18SDaniel P. Berrange             if (is_x509) {
3677eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3678eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3679eda24e18SDaniel P. Berrange             } else {
3680eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3681eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3682eda24e18SDaniel P. Berrange             }
3683eda24e18SDaniel P. Berrange 
3684eda24e18SDaniel P. Berrange         } else if (sasl) {
3685eda24e18SDaniel P. Berrange             if (is_x509) {
3686eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3687eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3688eda24e18SDaniel P. Berrange             } else {
3689eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3690eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3691eda24e18SDaniel P. Berrange             }
3692eda24e18SDaniel P. Berrange         } else {
3693eda24e18SDaniel P. Berrange             if (is_x509) {
3694eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3695eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3696eda24e18SDaniel P. Berrange             } else {
3697eda24e18SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3698eda24e18SDaniel P. Berrange                 *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3699eda24e18SDaniel P. Berrange             }
3700f9148c8aSDaniel P. Berrange         }
37010dd72e15SDaniel P. Berrange     }
37023e305e4aSDaniel P. Berrange     return 0;
37030dd72e15SDaniel P. Berrange }
37040dd72e15SDaniel P. Berrange 
37053e305e4aSDaniel P. Berrange 
3706275e0d61SDaniel P. Berrange static int vnc_display_get_address(const char *addrstr,
3707275e0d61SDaniel P. Berrange                                    bool websocket,
3708e5766eb4SGerd Hoffmann                                    bool reverse,
3709275e0d61SDaniel P. Berrange                                    int displaynum,
3710275e0d61SDaniel P. Berrange                                    int to,
3711275e0d61SDaniel P. Berrange                                    bool has_ipv4,
3712275e0d61SDaniel P. Berrange                                    bool has_ipv6,
3713275e0d61SDaniel P. Berrange                                    bool ipv4,
3714275e0d61SDaniel P. Berrange                                    bool ipv6,
3715bd269ebcSMarkus Armbruster                                    SocketAddress **retaddr,
3716275e0d61SDaniel P. Berrange                                    Error **errp)
3717275e0d61SDaniel P. Berrange {
3718275e0d61SDaniel P. Berrange     int ret = -1;
3719bd269ebcSMarkus Armbruster     SocketAddress *addr = NULL;
3720275e0d61SDaniel P. Berrange 
3721bd269ebcSMarkus Armbruster     addr = g_new0(SocketAddress, 1);
3722275e0d61SDaniel P. Berrange 
3723275e0d61SDaniel P. Berrange     if (strncmp(addrstr, "unix:", 5) == 0) {
3724bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3725bd269ebcSMarkus Armbruster         addr->u.q_unix.path = g_strdup(addrstr + 5);
3726275e0d61SDaniel P. Berrange 
3727275e0d61SDaniel P. Berrange         if (websocket) {
3728275e0d61SDaniel P. Berrange             error_setg(errp, "UNIX sockets not supported with websock");
3729275e0d61SDaniel P. Berrange             goto cleanup;
3730275e0d61SDaniel P. Berrange         }
3731275e0d61SDaniel P. Berrange 
3732275e0d61SDaniel P. Berrange         if (to) {
3733275e0d61SDaniel P. Berrange             error_setg(errp, "Port range not support with UNIX socket");
3734275e0d61SDaniel P. Berrange             goto cleanup;
3735275e0d61SDaniel P. Berrange         }
3736275e0d61SDaniel P. Berrange         ret = 0;
3737275e0d61SDaniel P. Berrange     } else {
3738275e0d61SDaniel P. Berrange         const char *port;
3739275e0d61SDaniel P. Berrange         size_t hostlen;
3740bd1386ccSEric Blake         uint64_t baseport = 0;
3741275e0d61SDaniel P. Berrange         InetSocketAddress *inet;
3742275e0d61SDaniel P. Berrange 
3743275e0d61SDaniel P. Berrange         port = strrchr(addrstr, ':');
3744275e0d61SDaniel P. Berrange         if (!port) {
3745275e0d61SDaniel P. Berrange             if (websocket) {
3746275e0d61SDaniel P. Berrange                 hostlen = 0;
3747275e0d61SDaniel P. Berrange                 port = addrstr;
3748275e0d61SDaniel P. Berrange             } else {
3749275e0d61SDaniel P. Berrange                 error_setg(errp, "no vnc port specified");
3750275e0d61SDaniel P. Berrange                 goto cleanup;
3751275e0d61SDaniel P. Berrange             }
3752275e0d61SDaniel P. Berrange         } else {
3753275e0d61SDaniel P. Berrange             hostlen = port - addrstr;
3754275e0d61SDaniel P. Berrange             port++;
3755275e0d61SDaniel P. Berrange             if (*port == '\0') {
3756275e0d61SDaniel P. Berrange                 error_setg(errp, "vnc port cannot be empty");
3757275e0d61SDaniel P. Berrange                 goto cleanup;
3758275e0d61SDaniel P. Berrange             }
3759275e0d61SDaniel P. Berrange         }
3760275e0d61SDaniel P. Berrange 
3761bd269ebcSMarkus Armbruster         addr->type = SOCKET_ADDRESS_TYPE_INET;
3762bd269ebcSMarkus Armbruster         inet = &addr->u.inet;
37633f9c41c5SPaolo Bonzini         if (hostlen && addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3764275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr + 1, hostlen - 2);
3765275e0d61SDaniel P. Berrange         } else {
3766275e0d61SDaniel P. Berrange             inet->host = g_strndup(addrstr, hostlen);
3767275e0d61SDaniel P. Berrange         }
3768275e0d61SDaniel P. Berrange         /* plain VNC port is just an offset, for websocket
3769275e0d61SDaniel P. Berrange          * port is absolute */
3770275e0d61SDaniel P. Berrange         if (websocket) {
3771275e0d61SDaniel P. Berrange             if (g_str_equal(addrstr, "") ||
3772275e0d61SDaniel P. Berrange                 g_str_equal(addrstr, "on")) {
3773396f935aSDaniel P. Berrange                 if (displaynum == -1) {
3774396f935aSDaniel P. Berrange                     error_setg(errp, "explicit websocket port is required");
3775396f935aSDaniel P. Berrange                     goto cleanup;
3776396f935aSDaniel P. Berrange                 }
3777275e0d61SDaniel P. Berrange                 inet->port = g_strdup_printf(
3778275e0d61SDaniel P. Berrange                     "%d", displaynum + 5700);
3779275e0d61SDaniel P. Berrange                 if (to) {
3780275e0d61SDaniel P. Berrange                     inet->has_to = true;
3781275e0d61SDaniel P. Berrange                     inet->to = to + 5700;
3782275e0d61SDaniel P. Berrange                 }
3783275e0d61SDaniel P. Berrange             } else {
3784275e0d61SDaniel P. Berrange                 inet->port = g_strdup(port);
3785275e0d61SDaniel P. Berrange             }
3786275e0d61SDaniel P. Berrange         } else {
3787e5766eb4SGerd Hoffmann             int offset = reverse ? 0 : 5900;
3788bd1386ccSEric Blake             if (parse_uint_full(port, 10, &baseport) < 0) {
3789275e0d61SDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", port);
3790275e0d61SDaniel P. Berrange                 goto cleanup;
3791275e0d61SDaniel P. Berrange             }
3792275e0d61SDaniel P. Berrange             if (baseport > 65535 ||
3793e5766eb4SGerd Hoffmann                 baseport + offset > 65535) {
3794275e0d61SDaniel P. Berrange                 error_setg(errp, "port %s out of range", port);
3795275e0d61SDaniel P. Berrange                 goto cleanup;
3796275e0d61SDaniel P. Berrange             }
3797275e0d61SDaniel P. Berrange             inet->port = g_strdup_printf(
3798e5766eb4SGerd Hoffmann                 "%d", (int)baseport + offset);
3799275e0d61SDaniel P. Berrange 
3800275e0d61SDaniel P. Berrange             if (to) {
3801275e0d61SDaniel P. Berrange                 inet->has_to = true;
3802e5766eb4SGerd Hoffmann                 inet->to = to + offset;
3803275e0d61SDaniel P. Berrange             }
3804275e0d61SDaniel P. Berrange         }
3805275e0d61SDaniel P. Berrange 
3806275e0d61SDaniel P. Berrange         inet->ipv4 = ipv4;
3807275e0d61SDaniel P. Berrange         inet->has_ipv4 = has_ipv4;
3808275e0d61SDaniel P. Berrange         inet->ipv6 = ipv6;
3809275e0d61SDaniel P. Berrange         inet->has_ipv6 = has_ipv6;
3810275e0d61SDaniel P. Berrange 
3811275e0d61SDaniel P. Berrange         ret = baseport;
3812275e0d61SDaniel P. Berrange     }
3813275e0d61SDaniel P. Berrange 
3814275e0d61SDaniel P. Berrange     *retaddr = addr;
3815275e0d61SDaniel P. Berrange 
3816275e0d61SDaniel P. Berrange  cleanup:
3817275e0d61SDaniel P. Berrange     if (ret < 0) {
3818bd269ebcSMarkus Armbruster         qapi_free_SocketAddress(addr);
3819275e0d61SDaniel P. Berrange     }
3820275e0d61SDaniel P. Berrange     return ret;
3821275e0d61SDaniel P. Berrange }
3822275e0d61SDaniel P. Berrange 
3823275e0d61SDaniel P. Berrange static int vnc_display_get_addresses(QemuOpts *opts,
3824e5766eb4SGerd Hoffmann                                      bool reverse,
3825d708f99dSVladimir Sementsov-Ogievskiy                                      SocketAddressList **saddr_list_ret,
3826d708f99dSVladimir Sementsov-Ogievskiy                                      SocketAddressList **wsaddr_list_ret,
3827275e0d61SDaniel P. Berrange                                      Error **errp)
3828275e0d61SDaniel P. Berrange {
3829bd269ebcSMarkus Armbruster     SocketAddress *saddr = NULL;
3830bd269ebcSMarkus Armbruster     SocketAddress *wsaddr = NULL;
3831d708f99dSVladimir Sementsov-Ogievskiy     g_autoptr(SocketAddressList) saddr_list = NULL;
3832d708f99dSVladimir Sementsov-Ogievskiy     SocketAddressList **saddr_tail = &saddr_list;
3833d708f99dSVladimir Sementsov-Ogievskiy     SocketAddress *single_saddr = NULL;
3834d708f99dSVladimir Sementsov-Ogievskiy     g_autoptr(SocketAddressList) wsaddr_list = NULL;
3835d708f99dSVladimir Sementsov-Ogievskiy     SocketAddressList **wsaddr_tail = &wsaddr_list;
3836396f935aSDaniel P. Berrange     QemuOptsIter addriter;
3837396f935aSDaniel P. Berrange     const char *addr;
3838275e0d61SDaniel P. Berrange     int to = qemu_opt_get_number(opts, "to", 0);
3839275e0d61SDaniel P. Berrange     bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3840275e0d61SDaniel P. Berrange     bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3841275e0d61SDaniel P. Berrange     bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3842275e0d61SDaniel P. Berrange     bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3843396f935aSDaniel P. Berrange     int displaynum = -1;
3844275e0d61SDaniel P. Berrange 
3845396f935aSDaniel P. Berrange     addr = qemu_opt_get(opts, "vnc");
3846396f935aSDaniel P. Berrange     if (addr == NULL || g_str_equal(addr, "none")) {
3847d708f99dSVladimir Sementsov-Ogievskiy         return 0;
3848396f935aSDaniel P. Berrange     }
3849396f935aSDaniel P. Berrange     if (qemu_opt_get(opts, "websocket") &&
3850275e0d61SDaniel P. Berrange         !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3851275e0d61SDaniel P. Berrange         error_setg(errp,
3852275e0d61SDaniel P. Berrange                    "SHA1 hash support is required for websockets");
3853d708f99dSVladimir Sementsov-Ogievskiy         return -1;
3854275e0d61SDaniel P. Berrange     }
3855275e0d61SDaniel P. Berrange 
3856396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "vnc");
3857396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3858396f935aSDaniel P. Berrange         int rv;
3859e5766eb4SGerd Hoffmann         rv = vnc_display_get_address(addr, false, reverse, 0, to,
3860275e0d61SDaniel P. Berrange                                      has_ipv4, has_ipv6,
3861275e0d61SDaniel P. Berrange                                      ipv4, ipv6,
3862275e0d61SDaniel P. Berrange                                      &saddr, errp);
3863396f935aSDaniel P. Berrange         if (rv < 0) {
3864d708f99dSVladimir Sementsov-Ogievskiy             return -1;
3865275e0d61SDaniel P. Berrange         }
3866396f935aSDaniel P. Berrange         /* Historical compat - first listen address can be used
3867396f935aSDaniel P. Berrange          * to set the default websocket port
3868396f935aSDaniel P. Berrange          */
3869396f935aSDaniel P. Berrange         if (displaynum == -1) {
3870396f935aSDaniel P. Berrange             displaynum = rv;
3871396f935aSDaniel P. Berrange         }
3872d708f99dSVladimir Sementsov-Ogievskiy         QAPI_LIST_APPEND(saddr_tail, saddr);
3873396f935aSDaniel P. Berrange     }
3874396f935aSDaniel P. Berrange 
3875d708f99dSVladimir Sementsov-Ogievskiy     if (saddr_list && !saddr_list->next) {
3876d708f99dSVladimir Sementsov-Ogievskiy         single_saddr = saddr_list->value;
3877d708f99dSVladimir Sementsov-Ogievskiy     } else {
3878d708f99dSVladimir Sementsov-Ogievskiy         /*
3879d708f99dSVladimir Sementsov-Ogievskiy          * If we had multiple primary displays, we don't do defaults
3880d708f99dSVladimir Sementsov-Ogievskiy          * for websocket, and require explicit config instead.
3881d708f99dSVladimir Sementsov-Ogievskiy          */
3882396f935aSDaniel P. Berrange         displaynum = -1;
3883396f935aSDaniel P. Berrange     }
3884396f935aSDaniel P. Berrange 
3885396f935aSDaniel P. Berrange     qemu_opt_iter_init(&addriter, opts, "websocket");
3886396f935aSDaniel P. Berrange     while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3887e5766eb4SGerd Hoffmann         if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3888275e0d61SDaniel P. Berrange                                     has_ipv4, has_ipv6,
3889275e0d61SDaniel P. Berrange                                     ipv4, ipv6,
3890275e0d61SDaniel P. Berrange                                     &wsaddr, errp) < 0) {
3891d708f99dSVladimir Sementsov-Ogievskiy             return -1;
3892275e0d61SDaniel P. Berrange         }
3893396f935aSDaniel P. Berrange 
3894396f935aSDaniel P. Berrange         /* Historical compat - if only a single listen address was
3895396f935aSDaniel P. Berrange          * provided, then this is used to set the default listen
3896396f935aSDaniel P. Berrange          * address for websocket too
3897396f935aSDaniel P. Berrange          */
3898d708f99dSVladimir Sementsov-Ogievskiy         if (single_saddr &&
3899d708f99dSVladimir Sementsov-Ogievskiy             single_saddr->type == SOCKET_ADDRESS_TYPE_INET &&
3900bd269ebcSMarkus Armbruster             wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3901bd269ebcSMarkus Armbruster             g_str_equal(wsaddr->u.inet.host, "") &&
3902d708f99dSVladimir Sementsov-Ogievskiy             !g_str_equal(single_saddr->u.inet.host, "")) {
3903bd269ebcSMarkus Armbruster             g_free(wsaddr->u.inet.host);
3904d708f99dSVladimir Sementsov-Ogievskiy             wsaddr->u.inet.host = g_strdup(single_saddr->u.inet.host);
3905275e0d61SDaniel P. Berrange         }
3906275e0d61SDaniel P. Berrange 
3907d708f99dSVladimir Sementsov-Ogievskiy         QAPI_LIST_APPEND(wsaddr_tail, wsaddr);
3908396f935aSDaniel P. Berrange     }
3909396f935aSDaniel P. Berrange 
3910d708f99dSVladimir Sementsov-Ogievskiy     *saddr_list_ret = g_steal_pointer(&saddr_list);
3911d708f99dSVladimir Sementsov-Ogievskiy     *wsaddr_list_ret = g_steal_pointer(&wsaddr_list);
3912d708f99dSVladimir Sementsov-Ogievskiy     return 0;
3913275e0d61SDaniel P. Berrange }
3914275e0d61SDaniel P. Berrange 
39158bd22f47SDaniel P. Berrange static int vnc_display_connect(VncDisplay *vd,
3916d708f99dSVladimir Sementsov-Ogievskiy                                SocketAddressList *saddr_list,
3917d708f99dSVladimir Sementsov-Ogievskiy                                SocketAddressList *wsaddr_list,
39188bd22f47SDaniel P. Berrange                                Error **errp)
39198bd22f47SDaniel P. Berrange {
39208bd22f47SDaniel P. Berrange     /* connect to viewer */
39218bd22f47SDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
3922d708f99dSVladimir Sementsov-Ogievskiy     if (wsaddr_list) {
39238bd22f47SDaniel P. Berrange         error_setg(errp, "Cannot use websockets in reverse mode");
39248bd22f47SDaniel P. Berrange         return -1;
39258bd22f47SDaniel P. Berrange     }
3926d708f99dSVladimir Sementsov-Ogievskiy     if (!saddr_list || saddr_list->next) {
3927396f935aSDaniel P. Berrange         error_setg(errp, "Expected a single address in reverse mode");
3928396f935aSDaniel P. Berrange         return -1;
3929396f935aSDaniel P. Berrange     }
3930bd269ebcSMarkus Armbruster     /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3931d708f99dSVladimir Sementsov-Ogievskiy     vd->is_unix = saddr_list->value->type == SOCKET_ADDRESS_TYPE_UNIX;
39328bd22f47SDaniel P. Berrange     sioc = qio_channel_socket_new();
39338bd22f47SDaniel P. Berrange     qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3934d708f99dSVladimir Sementsov-Ogievskiy     if (qio_channel_socket_connect_sync(sioc, saddr_list->value, errp) < 0) {
39355f8679feSAlex Chen         object_unref(OBJECT(sioc));
39368bd22f47SDaniel P. Berrange         return -1;
39378bd22f47SDaniel P. Berrange     }
39388bd22f47SDaniel P. Berrange     vnc_connect(vd, sioc, false, false);
39398bd22f47SDaniel P. Berrange     object_unref(OBJECT(sioc));
39408bd22f47SDaniel P. Berrange     return 0;
39418bd22f47SDaniel P. Berrange }
39428bd22f47SDaniel P. Berrange 
39438bd22f47SDaniel P. Berrange 
39448bd22f47SDaniel P. Berrange static int vnc_display_listen(VncDisplay *vd,
3945d708f99dSVladimir Sementsov-Ogievskiy                               SocketAddressList *saddr_list,
3946d708f99dSVladimir Sementsov-Ogievskiy                               SocketAddressList *wsaddr_list,
39478bd22f47SDaniel P. Berrange                               Error **errp)
39488bd22f47SDaniel P. Berrange {
3949d708f99dSVladimir Sementsov-Ogievskiy     SocketAddressList *el;
39508bd22f47SDaniel P. Berrange 
3951d708f99dSVladimir Sementsov-Ogievskiy     if (saddr_list) {
395213e1d0e7SDaniel P. Berrange         vd->listener = qio_net_listener_new();
395313e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->listener, "vnc-listen");
3954d708f99dSVladimir Sementsov-Ogievskiy         for (el = saddr_list; el; el = el->next) {
395513e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->listener,
3956d708f99dSVladimir Sementsov-Ogievskiy                                            el->value, 1,
39578bd22f47SDaniel P. Berrange                                            errp) < 0)  {
39588bd22f47SDaniel P. Berrange                 return -1;
39598bd22f47SDaniel P. Berrange             }
3960396f935aSDaniel P. Berrange         }
396113e1d0e7SDaniel P. Berrange 
396213e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->listener,
396313e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
396413e1d0e7SDaniel P. Berrange     }
396513e1d0e7SDaniel P. Berrange 
3966d708f99dSVladimir Sementsov-Ogievskiy     if (wsaddr_list) {
396713e1d0e7SDaniel P. Berrange         vd->wslistener = qio_net_listener_new();
396813e1d0e7SDaniel P. Berrange         qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3969d708f99dSVladimir Sementsov-Ogievskiy         for (el = wsaddr_list; el; el = el->next) {
397013e1d0e7SDaniel P. Berrange             if (qio_net_listener_open_sync(vd->wslistener,
3971d708f99dSVladimir Sementsov-Ogievskiy                                            el->value, 1,
39728bd22f47SDaniel P. Berrange                                            errp) < 0)  {
39738bd22f47SDaniel P. Berrange                 return -1;
39748bd22f47SDaniel P. Berrange             }
3975396f935aSDaniel P. Berrange         }
39768bd22f47SDaniel P. Berrange 
397713e1d0e7SDaniel P. Berrange         qio_net_listener_set_client_func(vd->wslistener,
397813e1d0e7SDaniel P. Berrange                                          vnc_listen_io, vd, NULL);
397913e1d0e7SDaniel P. Berrange     }
398013e1d0e7SDaniel P. Berrange 
39818bd22f47SDaniel P. Berrange     return 0;
39828bd22f47SDaniel P. Berrange }
39838bd22f47SDaniel P. Berrange 
3984abea1946SVladimir Sementsov-Ogievskiy bool vnc_display_update(DisplayUpdateOptionsVNC *arg, Error **errp)
3985abea1946SVladimir Sementsov-Ogievskiy {
3986abea1946SVladimir Sementsov-Ogievskiy     VncDisplay *vd = vnc_display_find(NULL);
3987abea1946SVladimir Sementsov-Ogievskiy 
3988abea1946SVladimir Sementsov-Ogievskiy     if (!vd) {
3989abea1946SVladimir Sementsov-Ogievskiy         error_setg(errp, "Can not find vnc display");
3990abea1946SVladimir Sementsov-Ogievskiy         return false;
3991abea1946SVladimir Sementsov-Ogievskiy     }
3992abea1946SVladimir Sementsov-Ogievskiy 
3993abea1946SVladimir Sementsov-Ogievskiy     if (arg->has_addresses) {
3994abea1946SVladimir Sementsov-Ogievskiy         if (vd->listener) {
3995abea1946SVladimir Sementsov-Ogievskiy             qio_net_listener_disconnect(vd->listener);
3996abea1946SVladimir Sementsov-Ogievskiy             object_unref(OBJECT(vd->listener));
3997abea1946SVladimir Sementsov-Ogievskiy             vd->listener = NULL;
3998abea1946SVladimir Sementsov-Ogievskiy         }
3999abea1946SVladimir Sementsov-Ogievskiy 
4000abea1946SVladimir Sementsov-Ogievskiy         if (vnc_display_listen(vd, arg->addresses, NULL, errp) < 0) {
4001abea1946SVladimir Sementsov-Ogievskiy             return false;
4002abea1946SVladimir Sementsov-Ogievskiy         }
4003abea1946SVladimir Sementsov-Ogievskiy     }
4004abea1946SVladimir Sementsov-Ogievskiy 
4005abea1946SVladimir Sementsov-Ogievskiy     return true;
4006abea1946SVladimir Sementsov-Ogievskiy }
40078bd22f47SDaniel P. Berrange 
40084db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
40093e230dd2SCorentin Chary {
4010bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
40114db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
4012d708f99dSVladimir Sementsov-Ogievskiy     g_autoptr(SocketAddressList) saddr_list = NULL;
4013d708f99dSVladimir Sementsov-Ogievskiy     g_autoptr(SocketAddressList) wsaddr_list = NULL;
4014e2a11d9dSGonglei     const char *share, *device_id;
40151d0d59feSGerd Hoffmann     QemuConsole *con;
4016a2c72de0SGonglei     bool password = false;
4017a2c72de0SGonglei     bool reverse = false;
40183e305e4aSDaniel P. Berrange     const char *credid;
4019a2c72de0SGonglei     bool sasl = false;
402055cf09a0SDaniel P. Berrange     const char *tlsauthz;
402155cf09a0SDaniel P. Berrange     const char *saslauthz;
40223e230dd2SCorentin Chary     int lock_key_sync = 1;
4023c5ce8333SGerd Hoffmann     int key_delay_ms;
4024f0b9f36dSKővágó, Zoltán     const char *audiodev;
40256c6840e9SDaniel P. Berrangé     const char *passwordSecret;
40263e230dd2SCorentin Chary 
4027bf01c179SDaniel P. Berrange     if (!vd) {
40282d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
40292d55f0e8SPaolo Bonzini         return;
40302d55f0e8SPaolo Bonzini     }
4031bf01c179SDaniel P. Berrange     vnc_display_close(vd);
40324db14629SGerd Hoffmann 
40334db14629SGerd Hoffmann     if (!opts) {
40342d55f0e8SPaolo Bonzini         return;
40354db14629SGerd Hoffmann     }
4036275e0d61SDaniel P. Berrange 
4037e5766eb4SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
4038d708f99dSVladimir Sementsov-Ogievskiy     if (vnc_display_get_addresses(opts, reverse, &saddr_list, &wsaddr_list,
4039d708f99dSVladimir Sementsov-Ogievskiy                                   errp) < 0) {
4040275e0d61SDaniel P. Berrange         goto fail;
4041275e0d61SDaniel P. Berrange     }
4042275e0d61SDaniel P. Berrange 
40436c6840e9SDaniel P. Berrangé 
40446c6840e9SDaniel P. Berrangé     passwordSecret = qemu_opt_get(opts, "password-secret");
40456c6840e9SDaniel P. Berrangé     if (passwordSecret) {
40466c6840e9SDaniel P. Berrangé         if (qemu_opt_get(opts, "password")) {
40476c6840e9SDaniel P. Berrangé             error_setg(errp,
40486c6840e9SDaniel P. Berrangé                        "'password' flag is redundant with 'password-secret'");
40496c6840e9SDaniel P. Berrangé             goto fail;
40506c6840e9SDaniel P. Berrangé         }
40516c6840e9SDaniel P. Berrangé         vd->password = qcrypto_secret_lookup_as_utf8(passwordSecret,
40526c6840e9SDaniel P. Berrangé                                                      errp);
40536c6840e9SDaniel P. Berrangé         if (!vd->password) {
40546c6840e9SDaniel P. Berrangé             goto fail;
40556c6840e9SDaniel P. Berrangé         }
40566c6840e9SDaniel P. Berrangé         password = true;
40576c6840e9SDaniel P. Berrangé     } else {
40584db14629SGerd Hoffmann         password = qemu_opt_get_bool(opts, "password", false);
40596c6840e9SDaniel P. Berrangé     }
4060800567a6SDaniel P. Berrange     if (password) {
4061800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
406283bee4b5SDaniel P. Berrangé                 QCRYPTO_CIPHER_ALG_DES, QCRYPTO_CIPHER_MODE_ECB)) {
4063800567a6SDaniel P. Berrange             error_setg(errp,
406483bee4b5SDaniel P. Berrangé                        "Cipher backend does not support DES algorithm");
4065800567a6SDaniel P. Berrange             goto fail;
4066800567a6SDaniel P. Berrange         }
4067800567a6SDaniel P. Berrange     }
40684db14629SGerd Hoffmann 
40694db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
4070d3b0db6dSAlexander Graf     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
40714db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
4072d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
4073d169f04bSDaniel P. Berrange     if (sasl) {
4074d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
4075d169f04bSDaniel P. Berrange         goto fail;
4076d169f04bSDaniel P. Berrange     }
4077d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
40783e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
40793e305e4aSDaniel P. Berrange     if (credid) {
40803e305e4aSDaniel P. Berrange         Object *creds;
40813e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
40823e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
40833e305e4aSDaniel P. Berrange         if (!creds) {
40843e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
40853e305e4aSDaniel P. Berrange                        credid);
40863e305e4aSDaniel P. Berrange             goto fail;
40873e305e4aSDaniel P. Berrange         }
4088bf01c179SDaniel P. Berrange         vd->tlscreds = (QCryptoTLSCreds *)
40893e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
40903e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
4091bf01c179SDaniel P. Berrange         if (!vd->tlscreds) {
40923e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
40933e305e4aSDaniel P. Berrange                        credid);
40943e305e4aSDaniel P. Berrange             goto fail;
40953e305e4aSDaniel P. Berrange         }
4096bf01c179SDaniel P. Berrange         object_ref(OBJECT(vd->tlscreds));
40973e305e4aSDaniel P. Berrange 
40983c52bf0cSPhilippe Mathieu-Daudé         if (!qcrypto_tls_creds_check_endpoint(vd->tlscreds,
40993c52bf0cSPhilippe Mathieu-Daudé                                               QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
41003c52bf0cSPhilippe Mathieu-Daudé                                               errp)) {
41013e305e4aSDaniel P. Berrange             goto fail;
41023e305e4aSDaniel P. Berrange         }
4103d169f04bSDaniel P. Berrange     }
410455cf09a0SDaniel P. Berrange     tlsauthz = qemu_opt_get(opts, "tls-authz");
410555cf09a0SDaniel P. Berrange     if (tlsauthz && !vd->tlscreds) {
410655cf09a0SDaniel P. Berrange         error_setg(errp, "'tls-authz' provided but TLS is not enabled");
410755cf09a0SDaniel P. Berrange         goto fail;
410855cf09a0SDaniel P. Berrange     }
410955cf09a0SDaniel P. Berrange 
411055cf09a0SDaniel P. Berrange     saslauthz = qemu_opt_get(opts, "sasl-authz");
411155cf09a0SDaniel P. Berrange     if (saslauthz && !sasl) {
411255cf09a0SDaniel P. Berrange         error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
411355cf09a0SDaniel P. Berrange         goto fail;
411455cf09a0SDaniel P. Berrange     }
41154db14629SGerd Hoffmann 
41164db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
41174db14629SGerd Hoffmann     if (share) {
41184db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
4119bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_IGNORE;
41204db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
4121bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
41224db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
4123bf01c179SDaniel P. Berrange             vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
41248cf36489SGerd Hoffmann         } else {
41252d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
41261ce52c78SPaolo Bonzini             goto fail;
41278cf36489SGerd Hoffmann         }
41284db14629SGerd Hoffmann     } else {
4129bf01c179SDaniel P. Berrange         vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
41303e230dd2SCorentin Chary     }
4131bf01c179SDaniel P. Berrange     vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
41323e230dd2SCorentin Chary 
41334db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
4134bf01c179SDaniel P. Berrange     vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
41354db14629SGerd Hoffmann #endif
4136bf01c179SDaniel P. Berrange     vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
4137e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
4138e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
4139e22492d3SPeter Lieven      * calculations otherwise */
4140bf01c179SDaniel P. Berrange     if (!vd->lossy) {
4141bf01c179SDaniel P. Berrange         vd->non_adaptive = true;
4142e22492d3SPeter Lieven     }
4143e22492d3SPeter Lieven 
41447b5fa0b5SDaniel P. Berrangé     vd->power_control = qemu_opt_get_bool(opts, "power-control", false);
41457b5fa0b5SDaniel P. Berrangé 
414655cf09a0SDaniel P. Berrange     if (tlsauthz) {
414755cf09a0SDaniel P. Berrange         vd->tlsauthzid = g_strdup(tlsauthz);
41483e230dd2SCorentin Chary     }
41493e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
415055cf09a0SDaniel P. Berrange     if (sasl) {
415155cf09a0SDaniel P. Berrange         if (saslauthz) {
415255cf09a0SDaniel P. Berrange             vd->sasl.authzid = g_strdup(saslauthz);
41533e230dd2SCorentin Chary         }
415455cf09a0SDaniel P. Berrange     }
41553e230dd2SCorentin Chary #endif
41563e230dd2SCorentin Chary 
4157eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
4158eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4159eda24e18SDaniel P. Berrange                                sasl, false, errp) < 0) {
4160eda24e18SDaniel P. Berrange         goto fail;
4161eda24e18SDaniel P. Berrange     }
41627364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
4163eda24e18SDaniel P. Berrange 
4164eda24e18SDaniel P. Berrange     if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
4165eda24e18SDaniel P. Berrange                                vd->tlscreds, password,
4166eda24e18SDaniel P. Berrange                                sasl, true, errp) < 0) {
41673e305e4aSDaniel P. Berrange         goto fail;
41683e305e4aSDaniel P. Berrange     }
41697364dbdaSDaniel P. Berrange     trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
41703e230dd2SCorentin Chary 
41713e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
4172b65310abSPaolo Bonzini     if (sasl && !vnc_sasl_server_init(errp)) {
41731ce52c78SPaolo Bonzini         goto fail;
41743e230dd2SCorentin Chary     }
41753e230dd2SCorentin Chary #endif
4176bf01c179SDaniel P. Berrange     vd->lock_key_sync = lock_key_sync;
4177a54f0d2bSPierre Ossman     if (lock_key_sync) {
4178a54f0d2bSPierre Ossman         vd->led = qemu_add_led_event_handler(kbd_leds, vd);
4179a54f0d2bSPierre Ossman     }
4180a54f0d2bSPierre Ossman     vd->ledstate = 0;
41813e230dd2SCorentin Chary 
4182f0b9f36dSKővágó, Zoltán     audiodev = qemu_opt_get(opts, "audiodev");
4183f0b9f36dSKővágó, Zoltán     if (audiodev) {
4184*176adafcSPaolo Bonzini         vd->audio_state = audio_state_by_name(audiodev, errp);
4185f0b9f36dSKővágó, Zoltán         if (!vd->audio_state) {
4186f0b9f36dSKővágó, Zoltán             goto fail;
4187f0b9f36dSKővágó, Zoltán         }
4188f0b9f36dSKővágó, Zoltán     }
4189f0b9f36dSKővágó, Zoltán 
41901d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
41911d0d59feSGerd Hoffmann     if (device_id) {
41921d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
4193f2c1d54cSGerd Hoffmann         Error *err = NULL;
41941d0d59feSGerd Hoffmann 
4195f2c1d54cSGerd Hoffmann         con = qemu_console_lookup_by_device_name(device_id, head, &err);
4196f2c1d54cSGerd Hoffmann         if (err) {
4197f2c1d54cSGerd Hoffmann             error_propagate(errp, err);
41981d0d59feSGerd Hoffmann             goto fail;
41991d0d59feSGerd Hoffmann         }
42001d0d59feSGerd Hoffmann     } else {
42011d0d59feSGerd Hoffmann         con = NULL;
42021d0d59feSGerd Hoffmann     }
42031d0d59feSGerd Hoffmann 
4204bf01c179SDaniel P. Berrange     if (con != vd->dcl.con) {
4205c2f2ba49SGerd Hoffmann         qkbd_state_free(vd->kbd);
4206bf01c179SDaniel P. Berrange         unregister_displaychangelistener(&vd->dcl);
4207bf01c179SDaniel P. Berrange         vd->dcl.con = con;
4208bf01c179SDaniel P. Berrange         register_displaychangelistener(&vd->dcl);
4209c2f2ba49SGerd Hoffmann         vd->kbd = qkbd_state_init(vd->dcl.con);
42101d0d59feSGerd Hoffmann     }
4211c2f2ba49SGerd Hoffmann     qkbd_state_set_delay(vd->kbd, key_delay_ms);
42121d0d59feSGerd Hoffmann 
4213d708f99dSVladimir Sementsov-Ogievskiy     if (saddr_list == NULL) {
4214d708f99dSVladimir Sementsov-Ogievskiy         return;
4215fa03cb7fSMarc-André Lureau     }
4216fa03cb7fSMarc-André Lureau 
42173e230dd2SCorentin Chary     if (reverse) {
4218d708f99dSVladimir Sementsov-Ogievskiy         if (vnc_display_connect(vd, saddr_list, wsaddr_list, errp) < 0) {
4219e0d03b8cSDaniel P. Berrange             goto fail;
42203e230dd2SCorentin Chary         }
42213e230dd2SCorentin Chary     } else {
4222d708f99dSVladimir Sementsov-Ogievskiy         if (vnc_display_listen(vd, saddr_list, wsaddr_list, errp) < 0) {
42233d00ac1aSCole Robinson             goto fail;
42243d00ac1aSCole Robinson         }
42253e230dd2SCorentin Chary     }
4226e0d03b8cSDaniel P. Berrange 
4227275e0d61SDaniel P. Berrange     if (qemu_opt_get(opts, "to")) {
4228bf01c179SDaniel P. Berrange         vnc_display_print_local_addr(vd);
422933df7bf3SPaolo Bonzini     }
423033df7bf3SPaolo Bonzini 
4231d708f99dSVladimir Sementsov-Ogievskiy     /* Success */
42322d55f0e8SPaolo Bonzini     return;
42331ce52c78SPaolo Bonzini 
42341ce52c78SPaolo Bonzini fail:
42354ee74fa7SDaniel P. Berrange     vnc_display_close(vd);
42363e230dd2SCorentin Chary }
423713661089SDaniel P. Berrange 
423814f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
423913661089SDaniel P. Berrange {
4240bf01c179SDaniel P. Berrange     VncDisplay *vd = vnc_display_find(id);
424104d2529dSDaniel P. Berrange     QIOChannelSocket *sioc;
424213661089SDaniel P. Berrange 
4243bf01c179SDaniel P. Berrange     if (!vd) {
4244d616ccc5SGerd Hoffmann         return;
4245d616ccc5SGerd Hoffmann     }
424604d2529dSDaniel P. Berrange 
424704d2529dSDaniel P. Berrange     sioc = qio_channel_socket_new_fd(csock, NULL);
424804d2529dSDaniel P. Berrange     if (sioc) {
424910bcfe58SDaniel P. Berrange         qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4250bf01c179SDaniel P. Berrange         vnc_connect(vd, sioc, skipauth, false);
425104d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
425204d2529dSDaniel P. Berrange     }
425313661089SDaniel P. Berrange }
42544db14629SGerd Hoffmann 
42559634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
42562779672fSGonglei {
42572779672fSGonglei     int i = 2;
42582779672fSGonglei     char *id;
42592779672fSGonglei 
42602779672fSGonglei     id = g_strdup("default");
42612779672fSGonglei     while (qemu_opts_find(olist, id)) {
42622779672fSGonglei         g_free(id);
42632779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
42642779672fSGonglei     }
42652779672fSGonglei     qemu_opts_set_id(opts, id);
42662779672fSGonglei }
42672779672fSGonglei 
4268653c9747SPaolo Bonzini void vnc_parse(const char *str)
42694db14629SGerd Hoffmann {
42704db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
4271653c9747SPaolo Bonzini     QemuOpts *opts = qemu_opts_parse_noisily(olist, str, !is_help_option(str));
427281607cbfSGonglei     const char *id;
42734db14629SGerd Hoffmann 
427481607cbfSGonglei     if (!opts) {
4275653c9747SPaolo Bonzini         exit(1);
427681607cbfSGonglei     }
427781607cbfSGonglei 
427881607cbfSGonglei     id = qemu_opts_id(opts);
42794db14629SGerd Hoffmann     if (!id) {
42804db14629SGerd Hoffmann         /* auto-assign id if not present */
42812779672fSGonglei         vnc_auto_assign_id(olist, opts);
42829634f4e3SGerd Hoffmann     }
42834db14629SGerd Hoffmann }
42844db14629SGerd Hoffmann 
428528d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
42869634f4e3SGerd Hoffmann {
42879634f4e3SGerd Hoffmann     Error *local_err = NULL;
42889634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
42899634f4e3SGerd Hoffmann 
42909634f4e3SGerd Hoffmann     assert(id);
4291ab4f931eSFei Li     vnc_display_init(id, &local_err);
4292ab4f931eSFei Li     if (local_err) {
4293612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4294612aea20SMarkus Armbruster         return -1;
4295ab4f931eSFei Li     }
42964db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
42974db14629SGerd Hoffmann     if (local_err != NULL) {
4298612aea20SMarkus Armbruster         error_propagate(errp, local_err);
4299612aea20SMarkus Armbruster         return -1;
43004db14629SGerd Hoffmann     }
43014db14629SGerd Hoffmann     return 0;
43024db14629SGerd Hoffmann }
43034db14629SGerd Hoffmann 
43044db14629SGerd Hoffmann static void vnc_register_config(void)
43054db14629SGerd Hoffmann {
43064db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
43074db14629SGerd Hoffmann }
430834294e2fSEduardo Habkost opts_init(vnc_register_config);
4309