xref: /openbmc/qemu/ui/vnc.c (revision b69a553b4af9bc87a8b2e0a7b7a7de4cc7f0557e)
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"
311d0d59feSGerd Hoffmann #include "hw/qdev.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
33d49b6836SMarkus Armbruster #include "qemu/error-report.h"
341de7afc9SPaolo Bonzini #include "qemu/sockets.h"
351de7afc9SPaolo Bonzini #include "qemu/timer.h"
361de7afc9SPaolo Bonzini #include "qemu/acl.h"
374db14629SGerd Hoffmann #include "qemu/config-file.h"
38cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
397b1b5d19SPaolo Bonzini #include "qapi/qmp/types.h"
402b54aa87SLuiz Capitulino #include "qmp-commands.h"
418d447d10SGerd Hoffmann #include "ui/input.h"
42fb6ba0d5SWenchao Xia #include "qapi-event.h"
438e9b0d24SDaniel P. Berrange #include "crypto/hash.h"
443e305e4aSDaniel P. Berrange #include "crypto/tlscredsanon.h"
453e305e4aSDaniel P. Berrange #include "crypto/tlscredsx509.h"
463e305e4aSDaniel P. Berrange #include "qom/object_interfaces.h"
47f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
483e230dd2SCorentin Chary 
490f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
503e230dd2SCorentin Chary #define VNC_REFRESH_INTERVAL_INC  50
510f7b2864SGerd Hoffmann #define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
52999342a0SCorentin Chary static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
53999342a0SCorentin Chary static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
543e230dd2SCorentin Chary 
553e230dd2SCorentin Chary #include "vnc_keysym.h"
56800567a6SDaniel P. Berrange #include "crypto/cipher.h"
573e230dd2SCorentin Chary 
58d616ccc5SGerd Hoffmann static QTAILQ_HEAD(, VncDisplay) vnc_displays =
59d616ccc5SGerd Hoffmann     QTAILQ_HEAD_INITIALIZER(vnc_displays);
603e230dd2SCorentin Chary 
613e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs);
627bc9318bSGerd Hoffmann static void vnc_release_modifiers(VncState *vs);
633e230dd2SCorentin Chary 
648cf36489SGerd Hoffmann static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
658cf36489SGerd Hoffmann {
668cf36489SGerd Hoffmann #ifdef _VNC_DEBUG
678cf36489SGerd Hoffmann     static const char *mn[] = {
688cf36489SGerd Hoffmann         [0]                           = "undefined",
698cf36489SGerd Hoffmann         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
708cf36489SGerd Hoffmann         [VNC_SHARE_MODE_SHARED]       = "shared",
718cf36489SGerd Hoffmann         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
728cf36489SGerd Hoffmann         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
738cf36489SGerd Hoffmann     };
7404d2529dSDaniel P. Berrange     fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
7504d2529dSDaniel P. Berrange             vs->ioc, mn[vs->share_mode], mn[mode]);
768cf36489SGerd Hoffmann #endif
778cf36489SGerd Hoffmann 
78e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
79e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
80e5f34cddSGerd Hoffmann         vs->vd->num_connecting--;
81e5f34cddSGerd Hoffmann         break;
82e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
83e5f34cddSGerd Hoffmann         vs->vd->num_shared--;
84e5f34cddSGerd Hoffmann         break;
85e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
868cf36489SGerd Hoffmann         vs->vd->num_exclusive--;
87e5f34cddSGerd Hoffmann         break;
88e5f34cddSGerd Hoffmann     default:
89e5f34cddSGerd Hoffmann         break;
908cf36489SGerd Hoffmann     }
91e5f34cddSGerd Hoffmann 
928cf36489SGerd Hoffmann     vs->share_mode = mode;
93e5f34cddSGerd Hoffmann 
94e5f34cddSGerd Hoffmann     switch (vs->share_mode) {
95e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_CONNECTING:
96e5f34cddSGerd Hoffmann         vs->vd->num_connecting++;
97e5f34cddSGerd Hoffmann         break;
98e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_SHARED:
99e5f34cddSGerd Hoffmann         vs->vd->num_shared++;
100e5f34cddSGerd Hoffmann         break;
101e5f34cddSGerd Hoffmann     case VNC_SHARE_MODE_EXCLUSIVE:
1028cf36489SGerd Hoffmann         vs->vd->num_exclusive++;
103e5f34cddSGerd Hoffmann         break;
104e5f34cddSGerd Hoffmann     default:
105e5f34cddSGerd Hoffmann         break;
1068cf36489SGerd Hoffmann     }
1078cf36489SGerd Hoffmann }
1088cf36489SGerd Hoffmann 
1093e230dd2SCorentin Chary 
11004d2529dSDaniel P. Berrange static void vnc_init_basic_info(SocketAddress *addr,
11198481bfcSEric Blake                                 VncBasicInfo *info,
11298481bfcSEric Blake                                 Error **errp)
1133e230dd2SCorentin Chary {
11404d2529dSDaniel P. Berrange     switch (addr->type) {
11504d2529dSDaniel P. Berrange     case SOCKET_ADDRESS_KIND_INET:
11632bafa8fSEric Blake         info->host = g_strdup(addr->u.inet.data->host);
11732bafa8fSEric Blake         info->service = g_strdup(addr->u.inet.data->port);
11832bafa8fSEric Blake         if (addr->u.inet.data->ipv6) {
11904d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV6;
12004d2529dSDaniel P. Berrange         } else {
12104d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_IPV4;
12204d2529dSDaniel P. Berrange         }
12304d2529dSDaniel P. Berrange         break;
1243e230dd2SCorentin Chary 
12504d2529dSDaniel P. Berrange     case SOCKET_ADDRESS_KIND_UNIX:
12604d2529dSDaniel P. Berrange         info->host = g_strdup("");
12732bafa8fSEric Blake         info->service = g_strdup(addr->u.q_unix.data->path);
12804d2529dSDaniel P. Berrange         info->family = NETWORK_ADDRESS_FAMILY_UNIX;
12904d2529dSDaniel P. Berrange         break;
13004d2529dSDaniel P. Berrange 
13104d2529dSDaniel P. Berrange     default:
13204d2529dSDaniel P. Berrange         error_setg(errp, "Unsupported socket kind %d",
13304d2529dSDaniel P. Berrange                    addr->type);
13404d2529dSDaniel P. Berrange         break;
13504d2529dSDaniel P. Berrange     }
13604d2529dSDaniel P. Berrange 
13798481bfcSEric Blake     return;
1383e230dd2SCorentin Chary }
1393e230dd2SCorentin Chary 
14004d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
14104d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
14298481bfcSEric Blake                                                  Error **errp)
1433e230dd2SCorentin Chary {
14404d2529dSDaniel P. Berrange     SocketAddress *addr = NULL;
1453e230dd2SCorentin Chary 
146624cdd46SDaniel P. Berrange     if (!ioc) {
147624cdd46SDaniel P. Berrange         error_setg(errp, "No listener socket available");
148624cdd46SDaniel P. Berrange         return;
149624cdd46SDaniel P. Berrange     }
150624cdd46SDaniel P. Berrange 
15104d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, errp);
15204d2529dSDaniel P. Berrange     if (!addr) {
15398481bfcSEric Blake         return;
1543e230dd2SCorentin Chary     }
1553e230dd2SCorentin Chary 
15604d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
15704d2529dSDaniel P. Berrange     qapi_free_SocketAddress(addr);
1583e230dd2SCorentin Chary }
1593e230dd2SCorentin Chary 
16004d2529dSDaniel P. Berrange static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
16104d2529dSDaniel P. Berrange                                                  VncBasicInfo *info,
16298481bfcSEric Blake                                                  Error **errp)
1633e230dd2SCorentin Chary {
16404d2529dSDaniel P. Berrange     SocketAddress *addr = NULL;
1653e230dd2SCorentin Chary 
16604d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_remote_address(ioc, errp);
16704d2529dSDaniel P. Berrange     if (!addr) {
16898481bfcSEric Blake         return;
1693e230dd2SCorentin Chary     }
1703e230dd2SCorentin Chary 
17104d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, errp);
17204d2529dSDaniel P. Berrange     qapi_free_SocketAddress(addr);
1733e230dd2SCorentin Chary }
1743e230dd2SCorentin Chary 
1753e230dd2SCorentin Chary static const char *vnc_auth_name(VncDisplay *vd) {
1763e230dd2SCorentin Chary     switch (vd->auth) {
1773e230dd2SCorentin Chary     case VNC_AUTH_INVALID:
1783e230dd2SCorentin Chary         return "invalid";
1793e230dd2SCorentin Chary     case VNC_AUTH_NONE:
1803e230dd2SCorentin Chary         return "none";
1813e230dd2SCorentin Chary     case VNC_AUTH_VNC:
1823e230dd2SCorentin Chary         return "vnc";
1833e230dd2SCorentin Chary     case VNC_AUTH_RA2:
1843e230dd2SCorentin Chary         return "ra2";
1853e230dd2SCorentin Chary     case VNC_AUTH_RA2NE:
1863e230dd2SCorentin Chary         return "ra2ne";
1873e230dd2SCorentin Chary     case VNC_AUTH_TIGHT:
1883e230dd2SCorentin Chary         return "tight";
1893e230dd2SCorentin Chary     case VNC_AUTH_ULTRA:
1903e230dd2SCorentin Chary         return "ultra";
1913e230dd2SCorentin Chary     case VNC_AUTH_TLS:
1923e230dd2SCorentin Chary         return "tls";
1933e230dd2SCorentin Chary     case VNC_AUTH_VENCRYPT:
1943e230dd2SCorentin Chary         switch (vd->subauth) {
1953e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_PLAIN:
1963e230dd2SCorentin Chary             return "vencrypt+plain";
1973e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSNONE:
1983e230dd2SCorentin Chary             return "vencrypt+tls+none";
1993e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSVNC:
2003e230dd2SCorentin Chary             return "vencrypt+tls+vnc";
2013e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSPLAIN:
2023e230dd2SCorentin Chary             return "vencrypt+tls+plain";
2033e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509NONE:
2043e230dd2SCorentin Chary             return "vencrypt+x509+none";
2053e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509VNC:
2063e230dd2SCorentin Chary             return "vencrypt+x509+vnc";
2073e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509PLAIN:
2083e230dd2SCorentin Chary             return "vencrypt+x509+plain";
2093e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_TLSSASL:
2103e230dd2SCorentin Chary             return "vencrypt+tls+sasl";
2113e230dd2SCorentin Chary         case VNC_AUTH_VENCRYPT_X509SASL:
2123e230dd2SCorentin Chary             return "vencrypt+x509+sasl";
2133e230dd2SCorentin Chary         default:
2143e230dd2SCorentin Chary             return "vencrypt";
2153e230dd2SCorentin Chary         }
2163e230dd2SCorentin Chary     case VNC_AUTH_SASL:
2173e230dd2SCorentin Chary         return "sasl";
2183e230dd2SCorentin Chary     }
2193e230dd2SCorentin Chary     return "unknown";
2203e230dd2SCorentin Chary }
2213e230dd2SCorentin Chary 
222d616ccc5SGerd Hoffmann static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
2233e230dd2SCorentin Chary {
224fb6ba0d5SWenchao Xia     VncServerInfo *info;
22598481bfcSEric Blake     Error *err = NULL;
2263e230dd2SCorentin Chary 
2273e7f136dSDaniel P. Berrange     info = g_malloc0(sizeof(*info));
228ddf21908SEric Blake     vnc_init_basic_info_from_server_addr(vd->lsock,
229ddf21908SEric Blake                                          qapi_VncServerInfo_base(info), &err);
230fb6ba0d5SWenchao Xia     info->has_auth = true;
231d616ccc5SGerd Hoffmann     info->auth = g_strdup(vnc_auth_name(vd));
23298481bfcSEric Blake     if (err) {
23398481bfcSEric Blake         qapi_free_VncServerInfo(info);
23498481bfcSEric Blake         info = NULL;
23598481bfcSEric Blake         error_free(err);
23698481bfcSEric Blake     }
237fb6ba0d5SWenchao Xia     return info;
2383e230dd2SCorentin Chary }
2393e230dd2SCorentin Chary 
2403e230dd2SCorentin Chary static void vnc_client_cache_auth(VncState *client)
2413e230dd2SCorentin Chary {
2423e230dd2SCorentin Chary     if (!client->info) {
2433e230dd2SCorentin Chary         return;
2443e230dd2SCorentin Chary     }
2453e230dd2SCorentin Chary 
2463e305e4aSDaniel P. Berrange     if (client->tls) {
2473e305e4aSDaniel P. Berrange         client->info->x509_dname =
2483e305e4aSDaniel P. Berrange             qcrypto_tls_session_get_peer_name(client->tls);
2493e305e4aSDaniel P. Berrange         client->info->has_x509_dname =
2503e305e4aSDaniel P. Berrange             client->info->x509_dname != NULL;
2513e230dd2SCorentin Chary     }
2523e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
2533e230dd2SCorentin Chary     if (client->sasl.conn &&
2543e230dd2SCorentin Chary         client->sasl.username) {
255fb6ba0d5SWenchao Xia         client->info->has_sasl_username = true;
256fb6ba0d5SWenchao Xia         client->info->sasl_username = g_strdup(client->sasl.username);
2573e230dd2SCorentin Chary     }
2583e230dd2SCorentin Chary #endif
2593e230dd2SCorentin Chary }
2603e230dd2SCorentin Chary 
2613e230dd2SCorentin Chary static void vnc_client_cache_addr(VncState *client)
2623e230dd2SCorentin Chary {
26398481bfcSEric Blake     Error *err = NULL;
2643e230dd2SCorentin Chary 
265fb6ba0d5SWenchao Xia     client->info = g_malloc0(sizeof(*client->info));
26604d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
267ddf21908SEric Blake                                          qapi_VncClientInfo_base(client->info),
26898481bfcSEric Blake                                          &err);
26998481bfcSEric Blake     if (err) {
27098481bfcSEric Blake         qapi_free_VncClientInfo(client->info);
27198481bfcSEric Blake         client->info = NULL;
27298481bfcSEric Blake         error_free(err);
273fb6ba0d5SWenchao Xia     }
2743e230dd2SCorentin Chary }
2753e230dd2SCorentin Chary 
276fb6ba0d5SWenchao Xia static void vnc_qmp_event(VncState *vs, QAPIEvent event)
2773e230dd2SCorentin Chary {
278fb6ba0d5SWenchao Xia     VncServerInfo *si;
2793e230dd2SCorentin Chary 
2803e230dd2SCorentin Chary     if (!vs->info) {
2813e230dd2SCorentin Chary         return;
2823e230dd2SCorentin Chary     }
2833e230dd2SCorentin Chary 
284d616ccc5SGerd Hoffmann     si = vnc_server_info_get(vs->vd);
285fb6ba0d5SWenchao Xia     if (!si) {
2863e230dd2SCorentin Chary         return;
2873e230dd2SCorentin Chary     }
2883e230dd2SCorentin Chary 
289fb6ba0d5SWenchao Xia     switch (event) {
290fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_CONNECTED:
291ddf21908SEric Blake         qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info),
292ddf21908SEric Blake                                       &error_abort);
293fb6ba0d5SWenchao Xia         break;
294fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_INITIALIZED:
295fb6ba0d5SWenchao Xia         qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
296fb6ba0d5SWenchao Xia         break;
297fb6ba0d5SWenchao Xia     case QAPI_EVENT_VNC_DISCONNECTED:
298fb6ba0d5SWenchao Xia         qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
299fb6ba0d5SWenchao Xia         break;
300fb6ba0d5SWenchao Xia     default:
301fb6ba0d5SWenchao Xia         break;
302fb6ba0d5SWenchao Xia     }
3033e230dd2SCorentin Chary 
304fb6ba0d5SWenchao Xia     qapi_free_VncServerInfo(si);
3053e230dd2SCorentin Chary }
3063e230dd2SCorentin Chary 
3072b54aa87SLuiz Capitulino static VncClientInfo *qmp_query_vnc_client(const VncState *client)
3083e230dd2SCorentin Chary {
3092b54aa87SLuiz Capitulino     VncClientInfo *info;
31004d2529dSDaniel P. Berrange     Error *err = NULL;
3112b54aa87SLuiz Capitulino 
3122b54aa87SLuiz Capitulino     info = g_malloc0(sizeof(*info));
31304d2529dSDaniel P. Berrange 
31404d2529dSDaniel P. Berrange     vnc_init_basic_info_from_remote_addr(client->sioc,
31504d2529dSDaniel P. Berrange                                          qapi_VncClientInfo_base(info),
31604d2529dSDaniel P. Berrange                                          &err);
31704d2529dSDaniel P. Berrange     if (err) {
31804d2529dSDaniel P. Berrange         error_free(err);
31904d2529dSDaniel P. Berrange         qapi_free_VncClientInfo(info);
32004d2529dSDaniel P. Berrange         return NULL;
32104d2529dSDaniel P. Berrange     }
32204d2529dSDaniel P. Berrange 
323ddf21908SEric Blake     info->websocket = client->websocket;
3243e230dd2SCorentin Chary 
3253e305e4aSDaniel P. Berrange     if (client->tls) {
3263e305e4aSDaniel P. Berrange         info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
3273e305e4aSDaniel P. Berrange         info->has_x509_dname = info->x509_dname != NULL;
3282b54aa87SLuiz Capitulino     }
3293e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
3302b54aa87SLuiz Capitulino     if (client->sasl.conn && client->sasl.username) {
3312b54aa87SLuiz Capitulino         info->has_sasl_username = true;
3322b54aa87SLuiz Capitulino         info->sasl_username = g_strdup(client->sasl.username);
3332b54aa87SLuiz Capitulino     }
3343e230dd2SCorentin Chary #endif
3352b54aa87SLuiz Capitulino 
3362b54aa87SLuiz Capitulino     return info;
3373e230dd2SCorentin Chary }
3383e230dd2SCorentin Chary 
339d616ccc5SGerd Hoffmann static VncDisplay *vnc_display_find(const char *id)
340d616ccc5SGerd Hoffmann {
341d616ccc5SGerd Hoffmann     VncDisplay *vd;
342d616ccc5SGerd Hoffmann 
343d616ccc5SGerd Hoffmann     if (id == NULL) {
344d616ccc5SGerd Hoffmann         return QTAILQ_FIRST(&vnc_displays);
345d616ccc5SGerd Hoffmann     }
346d616ccc5SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
347d616ccc5SGerd Hoffmann         if (strcmp(id, vd->id) == 0) {
348d616ccc5SGerd Hoffmann             return vd;
349d616ccc5SGerd Hoffmann         }
350d616ccc5SGerd Hoffmann     }
351d616ccc5SGerd Hoffmann     return NULL;
352d616ccc5SGerd Hoffmann }
353d616ccc5SGerd Hoffmann 
3542d29a436SGerd Hoffmann static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
3552d29a436SGerd Hoffmann {
3562d29a436SGerd Hoffmann     VncClientInfoList *cinfo, *prev = NULL;
3572d29a436SGerd Hoffmann     VncState *client;
3582d29a436SGerd Hoffmann 
3592d29a436SGerd Hoffmann     QTAILQ_FOREACH(client, &vd->clients, next) {
3602d29a436SGerd Hoffmann         cinfo = g_new0(VncClientInfoList, 1);
3612d29a436SGerd Hoffmann         cinfo->value = qmp_query_vnc_client(client);
3622d29a436SGerd Hoffmann         cinfo->next = prev;
3632d29a436SGerd Hoffmann         prev = cinfo;
3642d29a436SGerd Hoffmann     }
3652d29a436SGerd Hoffmann     return prev;
3662d29a436SGerd Hoffmann }
3672d29a436SGerd Hoffmann 
3682b54aa87SLuiz Capitulino VncInfo *qmp_query_vnc(Error **errp)
3693e230dd2SCorentin Chary {
3702b54aa87SLuiz Capitulino     VncInfo *info = g_malloc0(sizeof(*info));
371d616ccc5SGerd Hoffmann     VncDisplay *vd = vnc_display_find(NULL);
37204d2529dSDaniel P. Berrange     SocketAddress *addr = NULL;
3733e230dd2SCorentin Chary 
374bf7aa45eSGerd Hoffmann     if (vd == NULL || !vd->enabled) {
3752b54aa87SLuiz Capitulino         info->enabled = false;
3763e230dd2SCorentin Chary     } else {
3772b54aa87SLuiz Capitulino         info->enabled = true;
3782b54aa87SLuiz Capitulino 
3792b54aa87SLuiz Capitulino         /* for compatibility with the original command */
3802b54aa87SLuiz Capitulino         info->has_clients = true;
3812d29a436SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
3823e230dd2SCorentin Chary 
38304d2529dSDaniel P. Berrange         if (vd->lsock == NULL) {
384417b0b88SPaolo Bonzini             return info;
385417b0b88SPaolo Bonzini         }
386417b0b88SPaolo Bonzini 
38704d2529dSDaniel P. Berrange         addr = qio_channel_socket_get_local_address(vd->lsock, errp);
38804d2529dSDaniel P. Berrange         if (!addr) {
3892b54aa87SLuiz Capitulino             goto out_error;
3902b54aa87SLuiz Capitulino         }
3913e230dd2SCorentin Chary 
39204d2529dSDaniel P. Berrange         switch (addr->type) {
39304d2529dSDaniel P. Berrange         case SOCKET_ADDRESS_KIND_INET:
39432bafa8fSEric Blake             info->host = g_strdup(addr->u.inet.data->host);
39532bafa8fSEric Blake             info->service = g_strdup(addr->u.inet.data->port);
39632bafa8fSEric Blake             if (addr->u.inet.data->ipv6) {
39704d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV6;
39804d2529dSDaniel P. Berrange             } else {
39904d2529dSDaniel P. Berrange                 info->family = NETWORK_ADDRESS_FAMILY_IPV4;
40004d2529dSDaniel P. Berrange             }
40104d2529dSDaniel P. Berrange             break;
40204d2529dSDaniel P. Berrange 
40304d2529dSDaniel P. Berrange         case SOCKET_ADDRESS_KIND_UNIX:
40404d2529dSDaniel P. Berrange             info->host = g_strdup("");
40532bafa8fSEric Blake             info->service = g_strdup(addr->u.q_unix.data->path);
40604d2529dSDaniel P. Berrange             info->family = NETWORK_ADDRESS_FAMILY_UNIX;
40704d2529dSDaniel P. Berrange             break;
40804d2529dSDaniel P. Berrange 
40904d2529dSDaniel P. Berrange         default:
41004d2529dSDaniel P. Berrange             error_setg(errp, "Unsupported socket kind %d",
41104d2529dSDaniel P. Berrange                        addr->type);
4122b54aa87SLuiz Capitulino             goto out_error;
4133e230dd2SCorentin Chary         }
4142b54aa87SLuiz Capitulino 
4152b54aa87SLuiz Capitulino         info->has_host = true;
4162b54aa87SLuiz Capitulino         info->has_service = true;
4172b54aa87SLuiz Capitulino         info->has_family = true;
4182b54aa87SLuiz Capitulino 
4192b54aa87SLuiz Capitulino         info->has_auth = true;
420d616ccc5SGerd Hoffmann         info->auth = g_strdup(vnc_auth_name(vd));
4213e230dd2SCorentin Chary     }
4222b54aa87SLuiz Capitulino 
42304d2529dSDaniel P. Berrange     qapi_free_SocketAddress(addr);
4242b54aa87SLuiz Capitulino     return info;
4252b54aa87SLuiz Capitulino 
4262b54aa87SLuiz Capitulino out_error:
42704d2529dSDaniel P. Berrange     qapi_free_SocketAddress(addr);
4282b54aa87SLuiz Capitulino     qapi_free_VncInfo(info);
4292b54aa87SLuiz Capitulino     return NULL;
4303e230dd2SCorentin Chary }
4313e230dd2SCorentin Chary 
43204d2529dSDaniel P. Berrange static VncBasicInfoList *qmp_query_server_entry(QIOChannelSocket *ioc,
4334478aa76SGerd Hoffmann                                                 bool websocket,
434df887684SGerd Hoffmann                                                 VncBasicInfoList *prev)
435df887684SGerd Hoffmann {
436df887684SGerd Hoffmann     VncBasicInfoList *list;
437df887684SGerd Hoffmann     VncBasicInfo *info;
43804d2529dSDaniel P. Berrange     Error *err = NULL;
43904d2529dSDaniel P. Berrange     SocketAddress *addr;
440df887684SGerd Hoffmann 
44104d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(ioc, &err);
44204d2529dSDaniel P. Berrange     if (!addr) {
44304d2529dSDaniel P. Berrange         error_free(err);
444df887684SGerd Hoffmann         return prev;
445df887684SGerd Hoffmann     }
446df887684SGerd Hoffmann 
447df887684SGerd Hoffmann     info = g_new0(VncBasicInfo, 1);
44804d2529dSDaniel P. Berrange     vnc_init_basic_info(addr, info, &err);
44904d2529dSDaniel P. Berrange     qapi_free_SocketAddress(addr);
45004d2529dSDaniel P. Berrange     if (err) {
45104d2529dSDaniel P. Berrange         qapi_free_VncBasicInfo(info);
45204d2529dSDaniel P. Berrange         error_free(err);
45304d2529dSDaniel P. Berrange         return prev;
45404d2529dSDaniel P. Berrange     }
4554478aa76SGerd Hoffmann     info->websocket = websocket;
456df887684SGerd Hoffmann 
457df887684SGerd Hoffmann     list = g_new0(VncBasicInfoList, 1);
458df887684SGerd Hoffmann     list->value = info;
459df887684SGerd Hoffmann     list->next = prev;
460df887684SGerd Hoffmann     return list;
461df887684SGerd Hoffmann }
462df887684SGerd Hoffmann 
463df887684SGerd Hoffmann static void qmp_query_auth(VncDisplay *vd, VncInfo2 *info)
464df887684SGerd Hoffmann {
465df887684SGerd Hoffmann     switch (vd->auth) {
466df887684SGerd Hoffmann     case VNC_AUTH_VNC:
467df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_VNC;
468df887684SGerd Hoffmann         break;
469df887684SGerd Hoffmann     case VNC_AUTH_RA2:
470df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_RA2;
471df887684SGerd Hoffmann         break;
472df887684SGerd Hoffmann     case VNC_AUTH_RA2NE:
473df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_RA2NE;
474df887684SGerd Hoffmann         break;
475df887684SGerd Hoffmann     case VNC_AUTH_TIGHT:
476df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_TIGHT;
477df887684SGerd Hoffmann         break;
478df887684SGerd Hoffmann     case VNC_AUTH_ULTRA:
479df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_ULTRA;
480df887684SGerd Hoffmann         break;
481df887684SGerd Hoffmann     case VNC_AUTH_TLS:
482df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_TLS;
483df887684SGerd Hoffmann         break;
484df887684SGerd Hoffmann     case VNC_AUTH_VENCRYPT:
485df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_VENCRYPT;
486df887684SGerd Hoffmann         info->has_vencrypt = true;
487df887684SGerd Hoffmann         switch (vd->subauth) {
488df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_PLAIN:
489df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
490df887684SGerd Hoffmann             break;
491df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSNONE:
492df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
493df887684SGerd Hoffmann             break;
494df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSVNC:
495df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
496df887684SGerd Hoffmann             break;
497df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSPLAIN:
498df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
499df887684SGerd Hoffmann             break;
500df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509NONE:
501df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
502df887684SGerd Hoffmann             break;
503df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509VNC:
504df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
505df887684SGerd Hoffmann             break;
506df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509PLAIN:
507df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
508df887684SGerd Hoffmann             break;
509df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_TLSSASL:
510df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
511df887684SGerd Hoffmann             break;
512df887684SGerd Hoffmann         case VNC_AUTH_VENCRYPT_X509SASL:
513df887684SGerd Hoffmann             info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
514df887684SGerd Hoffmann             break;
515df887684SGerd Hoffmann         default:
516df887684SGerd Hoffmann             info->has_vencrypt = false;
517df887684SGerd Hoffmann             break;
518df887684SGerd Hoffmann         }
519df887684SGerd Hoffmann         break;
520df887684SGerd Hoffmann     case VNC_AUTH_SASL:
521df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_SASL;
522df887684SGerd Hoffmann         break;
523df887684SGerd Hoffmann     case VNC_AUTH_NONE:
524df887684SGerd Hoffmann     default:
525df887684SGerd Hoffmann         info->auth = VNC_PRIMARY_AUTH_NONE;
526df887684SGerd Hoffmann         break;
527df887684SGerd Hoffmann     }
528df887684SGerd Hoffmann }
529df887684SGerd Hoffmann 
530df887684SGerd Hoffmann VncInfo2List *qmp_query_vnc_servers(Error **errp)
531df887684SGerd Hoffmann {
532df887684SGerd Hoffmann     VncInfo2List *item, *prev = NULL;
533df887684SGerd Hoffmann     VncInfo2 *info;
534df887684SGerd Hoffmann     VncDisplay *vd;
535df887684SGerd Hoffmann     DeviceState *dev;
536df887684SGerd Hoffmann 
537df887684SGerd Hoffmann     QTAILQ_FOREACH(vd, &vnc_displays, next) {
538df887684SGerd Hoffmann         info = g_new0(VncInfo2, 1);
539df887684SGerd Hoffmann         info->id = g_strdup(vd->id);
540df887684SGerd Hoffmann         info->clients = qmp_query_client_list(vd);
541df887684SGerd Hoffmann         qmp_query_auth(vd, info);
542df887684SGerd Hoffmann         if (vd->dcl.con) {
543df887684SGerd Hoffmann             dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
544df887684SGerd Hoffmann                                                   "device", NULL));
545df887684SGerd Hoffmann             info->has_display = true;
546df887684SGerd Hoffmann             info->display = g_strdup(dev->id);
547df887684SGerd Hoffmann         }
54804d2529dSDaniel P. Berrange         if (vd->lsock != NULL) {
54904d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
55004d2529dSDaniel P. Berrange                 vd->lsock, false, info->server);
551df887684SGerd Hoffmann         }
55204d2529dSDaniel P. Berrange         if (vd->lwebsock != NULL) {
55304d2529dSDaniel P. Berrange             info->server = qmp_query_server_entry(
55404d2529dSDaniel P. Berrange                 vd->lwebsock, true, info->server);
555df887684SGerd Hoffmann         }
556df887684SGerd Hoffmann 
557df887684SGerd Hoffmann         item = g_new0(VncInfo2List, 1);
558df887684SGerd Hoffmann         item->value = info;
559df887684SGerd Hoffmann         item->next = prev;
560df887684SGerd Hoffmann         prev = item;
561df887684SGerd Hoffmann     }
562df887684SGerd Hoffmann     return prev;
563df887684SGerd Hoffmann }
564df887684SGerd Hoffmann 
5653e230dd2SCorentin Chary /* TODO
5663e230dd2SCorentin Chary    1) Get the queue working for IO.
5673e230dd2SCorentin Chary    2) there is some weirdness when using the -S option (the screen is grey
5683e230dd2SCorentin Chary       and not totally invalidated
5693e230dd2SCorentin Chary    3) resolutions > 1024
5703e230dd2SCorentin Chary */
5713e230dd2SCorentin Chary 
57238ee14f4SGerd Hoffmann static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
5733e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs);
5743e230dd2SCorentin Chary 
5753e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs);
5763e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
5773e230dd2SCorentin Chary                                        int x_position, int y_position,
5783e230dd2SCorentin Chary                                        int w, int h);
5790f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl);
5803e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd);
5813e230dd2SCorentin Chary 
582d05959c2SGerd Hoffmann static int vnc_width(VncDisplay *vd)
583d05959c2SGerd Hoffmann {
584d05959c2SGerd Hoffmann     return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
585d05959c2SGerd Hoffmann                                        VNC_DIRTY_PIXELS_PER_BIT));
586d05959c2SGerd Hoffmann }
587d05959c2SGerd Hoffmann 
588d05959c2SGerd Hoffmann static int vnc_height(VncDisplay *vd)
589d05959c2SGerd Hoffmann {
590d05959c2SGerd Hoffmann     return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
591d05959c2SGerd Hoffmann }
592d05959c2SGerd Hoffmann 
593bea60dd7SPeter Lieven static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
594bea60dd7SPeter Lieven                                VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
595f7b3d68cSGerd Hoffmann                                VncDisplay *vd,
596f7b3d68cSGerd Hoffmann                                int x, int y, int w, int h)
597f7b3d68cSGerd Hoffmann {
598f7b3d68cSGerd Hoffmann     int width = vnc_width(vd);
599f7b3d68cSGerd Hoffmann     int height = vnc_height(vd);
600f7b3d68cSGerd Hoffmann 
60191937225SPeter Lieven     /* this is needed this to ensure we updated all affected
60291937225SPeter Lieven      * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
603b4c85ddcSPeter Lieven     w += (x % VNC_DIRTY_PIXELS_PER_BIT);
604b4c85ddcSPeter Lieven     x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
6053e230dd2SCorentin Chary 
6069f64916dSGerd Hoffmann     x = MIN(x, width);
6079f64916dSGerd Hoffmann     y = MIN(y, height);
6089f64916dSGerd Hoffmann     w = MIN(x + w, width) - x;
60991937225SPeter Lieven     h = MIN(y + h, height);
6103e230dd2SCorentin Chary 
611b4c85ddcSPeter Lieven     for (; y < h; y++) {
612bea60dd7SPeter Lieven         bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
61391937225SPeter Lieven                    DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
614b4c85ddcSPeter Lieven     }
6153e230dd2SCorentin Chary }
6163e230dd2SCorentin Chary 
617bea60dd7SPeter Lieven static void vnc_dpy_update(DisplayChangeListener *dcl,
618bea60dd7SPeter Lieven                            int x, int y, int w, int h)
619bea60dd7SPeter Lieven {
620bea60dd7SPeter Lieven     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
621bea60dd7SPeter Lieven     struct VncSurface *s = &vd->guest;
622bea60dd7SPeter Lieven 
623f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
624bea60dd7SPeter Lieven }
625bea60dd7SPeter Lieven 
6263e230dd2SCorentin Chary void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
6273e230dd2SCorentin Chary                             int32_t encoding)
6283e230dd2SCorentin Chary {
6293e230dd2SCorentin Chary     vnc_write_u16(vs, x);
6303e230dd2SCorentin Chary     vnc_write_u16(vs, y);
6313e230dd2SCorentin Chary     vnc_write_u16(vs, w);
6323e230dd2SCorentin Chary     vnc_write_u16(vs, h);
6333e230dd2SCorentin Chary 
6343e230dd2SCorentin Chary     vnc_write_s32(vs, encoding);
6353e230dd2SCorentin Chary }
6363e230dd2SCorentin Chary 
63732ed2680STim Hardeck 
6383e230dd2SCorentin Chary static void vnc_desktop_resize(VncState *vs)
6393e230dd2SCorentin Chary {
64004d2529dSDaniel P. Berrange     if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
6413e230dd2SCorentin Chary         return;
6423e230dd2SCorentin Chary     }
643bea60dd7SPeter Lieven     if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
644bea60dd7SPeter Lieven         vs->client_height == pixman_image_get_height(vs->vd->server)) {
6453e230dd2SCorentin Chary         return;
6463e230dd2SCorentin Chary     }
647bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
648bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
649bd023f95SCorentin Chary     vnc_lock_output(vs);
6503e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
6513e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
6523e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
6533e230dd2SCorentin Chary     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
6543e230dd2SCorentin Chary                            VNC_ENCODING_DESKTOPRESIZE);
655bd023f95SCorentin Chary     vnc_unlock_output(vs);
6563e230dd2SCorentin Chary     vnc_flush(vs);
6573e230dd2SCorentin Chary }
6583e230dd2SCorentin Chary 
659bd023f95SCorentin Chary static void vnc_abort_display_jobs(VncDisplay *vd)
660bd023f95SCorentin Chary {
661bd023f95SCorentin Chary     VncState *vs;
662bd023f95SCorentin Chary 
663bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
664bd023f95SCorentin Chary         vnc_lock_output(vs);
665bd023f95SCorentin Chary         vs->abort = true;
666bd023f95SCorentin Chary         vnc_unlock_output(vs);
667bd023f95SCorentin Chary     }
668bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
669bd023f95SCorentin Chary         vnc_jobs_join(vs);
670bd023f95SCorentin Chary     }
671bd023f95SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
672bd023f95SCorentin Chary         vnc_lock_output(vs);
673bd023f95SCorentin Chary         vs->abort = false;
674bd023f95SCorentin Chary         vnc_unlock_output(vs);
675bd023f95SCorentin Chary     }
676bd023f95SCorentin Chary }
677bd023f95SCorentin Chary 
6789f64916dSGerd Hoffmann int vnc_server_fb_stride(VncDisplay *vd)
6799f64916dSGerd Hoffmann {
6809f64916dSGerd Hoffmann     return pixman_image_get_stride(vd->server);
6819f64916dSGerd Hoffmann }
6829f64916dSGerd Hoffmann 
6839f64916dSGerd Hoffmann void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
6849f64916dSGerd Hoffmann {
6859f64916dSGerd Hoffmann     uint8_t *ptr;
6869f64916dSGerd Hoffmann 
6879f64916dSGerd Hoffmann     ptr  = (uint8_t *)pixman_image_get_data(vd->server);
6889f64916dSGerd Hoffmann     ptr += y * vnc_server_fb_stride(vd);
6899f64916dSGerd Hoffmann     ptr += x * VNC_SERVER_FB_BYTES;
6909f64916dSGerd Hoffmann     return ptr;
6919f64916dSGerd Hoffmann }
6929f64916dSGerd Hoffmann 
693453f842bSGerd Hoffmann static void vnc_update_server_surface(VncDisplay *vd)
694453f842bSGerd Hoffmann {
695*b69a553bSDaniel P. Berrange     int width, height;
696*b69a553bSDaniel P. Berrange 
697453f842bSGerd Hoffmann     qemu_pixman_image_unref(vd->server);
698453f842bSGerd Hoffmann     vd->server = NULL;
699453f842bSGerd Hoffmann 
700c7628bffSGerd Hoffmann     if (QTAILQ_EMPTY(&vd->clients)) {
701c7628bffSGerd Hoffmann         return;
702c7628bffSGerd Hoffmann     }
703c7628bffSGerd Hoffmann 
704*b69a553bSDaniel P. Berrange     width = vnc_width(vd);
705*b69a553bSDaniel P. Berrange     height = vnc_height(vd);
706453f842bSGerd Hoffmann     vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
707*b69a553bSDaniel P. Berrange                                           width, height,
708453f842bSGerd Hoffmann                                           NULL, 0);
709*b69a553bSDaniel P. Berrange 
710*b69a553bSDaniel P. Berrange     memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
711*b69a553bSDaniel P. Berrange     vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
712*b69a553bSDaniel P. Berrange                        width, height);
713453f842bSGerd Hoffmann }
714453f842bSGerd Hoffmann 
715c12aeb86SGerd Hoffmann static void vnc_dpy_switch(DisplayChangeListener *dcl,
716c12aeb86SGerd Hoffmann                            DisplaySurface *surface)
7173e230dd2SCorentin Chary {
71821ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
7193e230dd2SCorentin Chary     VncState *vs;
7203e230dd2SCorentin Chary 
721bd023f95SCorentin Chary     vnc_abort_display_jobs(vd);
722453f842bSGerd Hoffmann     vd->ds = surface;
723bd023f95SCorentin Chary 
7243e230dd2SCorentin Chary     /* server surface */
725453f842bSGerd Hoffmann     vnc_update_server_surface(vd);
7263e230dd2SCorentin Chary 
7273e230dd2SCorentin Chary     /* guest surface */
7289f64916dSGerd Hoffmann     qemu_pixman_image_unref(vd->guest.fb);
729d39fa6d8SGerd Hoffmann     vd->guest.fb = pixman_image_ref(surface->image);
730d39fa6d8SGerd Hoffmann     vd->guest.format = surface->format;
7313e230dd2SCorentin Chary 
7323e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
7333e230dd2SCorentin Chary         vnc_colordepth(vs);
7343e230dd2SCorentin Chary         vnc_desktop_resize(vs);
7353e230dd2SCorentin Chary         if (vs->vd->cursor) {
7363e230dd2SCorentin Chary             vnc_cursor_define(vs);
7373e230dd2SCorentin Chary         }
738bea60dd7SPeter Lieven         memset(vs->dirty, 0x00, sizeof(vs->dirty));
739f7b3d68cSGerd Hoffmann         vnc_set_area_dirty(vs->dirty, vd, 0, 0,
740*b69a553bSDaniel P. Berrange                            vnc_width(vd),
741*b69a553bSDaniel P. Berrange                            vnc_height(vd));
7423e230dd2SCorentin Chary     }
7433e230dd2SCorentin Chary }
7443e230dd2SCorentin Chary 
7453e230dd2SCorentin Chary /* fastest code */
7469f64916dSGerd Hoffmann static void vnc_write_pixels_copy(VncState *vs,
7473e230dd2SCorentin Chary                                   void *pixels, int size)
7483e230dd2SCorentin Chary {
7493e230dd2SCorentin Chary     vnc_write(vs, pixels, size);
7503e230dd2SCorentin Chary }
7513e230dd2SCorentin Chary 
7523e230dd2SCorentin Chary /* slowest but generic code. */
7533e230dd2SCorentin Chary void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
7543e230dd2SCorentin Chary {
7553e230dd2SCorentin Chary     uint8_t r, g, b;
7563e230dd2SCorentin Chary 
7579f64916dSGerd Hoffmann #if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
7589f64916dSGerd Hoffmann     r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
7599f64916dSGerd Hoffmann     g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
7609f64916dSGerd Hoffmann     b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
7619f64916dSGerd Hoffmann #else
7629f64916dSGerd Hoffmann # error need some bits here if you change VNC_SERVER_FB_FORMAT
7639f64916dSGerd Hoffmann #endif
7649f64916dSGerd Hoffmann     v = (r << vs->client_pf.rshift) |
7659f64916dSGerd Hoffmann         (g << vs->client_pf.gshift) |
7669f64916dSGerd Hoffmann         (b << vs->client_pf.bshift);
7679f64916dSGerd Hoffmann     switch (vs->client_pf.bytes_per_pixel) {
7683e230dd2SCorentin Chary     case 1:
7693e230dd2SCorentin Chary         buf[0] = v;
7703e230dd2SCorentin Chary         break;
7713e230dd2SCorentin Chary     case 2:
7729f64916dSGerd Hoffmann         if (vs->client_be) {
7733e230dd2SCorentin Chary             buf[0] = v >> 8;
7743e230dd2SCorentin Chary             buf[1] = v;
7753e230dd2SCorentin Chary         } else {
7763e230dd2SCorentin Chary             buf[1] = v >> 8;
7773e230dd2SCorentin Chary             buf[0] = v;
7783e230dd2SCorentin Chary         }
7793e230dd2SCorentin Chary         break;
7803e230dd2SCorentin Chary     default:
7813e230dd2SCorentin Chary     case 4:
7829f64916dSGerd Hoffmann         if (vs->client_be) {
7833e230dd2SCorentin Chary             buf[0] = v >> 24;
7843e230dd2SCorentin Chary             buf[1] = v >> 16;
7853e230dd2SCorentin Chary             buf[2] = v >> 8;
7863e230dd2SCorentin Chary             buf[3] = v;
7873e230dd2SCorentin Chary         } else {
7883e230dd2SCorentin Chary             buf[3] = v >> 24;
7893e230dd2SCorentin Chary             buf[2] = v >> 16;
7903e230dd2SCorentin Chary             buf[1] = v >> 8;
7913e230dd2SCorentin Chary             buf[0] = v;
7923e230dd2SCorentin Chary         }
7933e230dd2SCorentin Chary         break;
7943e230dd2SCorentin Chary     }
7953e230dd2SCorentin Chary }
7963e230dd2SCorentin Chary 
7979f64916dSGerd Hoffmann static void vnc_write_pixels_generic(VncState *vs,
7983e230dd2SCorentin Chary                                      void *pixels1, int size)
7993e230dd2SCorentin Chary {
8003e230dd2SCorentin Chary     uint8_t buf[4];
8013e230dd2SCorentin Chary 
8029f64916dSGerd Hoffmann     if (VNC_SERVER_FB_BYTES == 4) {
8033e230dd2SCorentin Chary         uint32_t *pixels = pixels1;
8043e230dd2SCorentin Chary         int n, i;
8053e230dd2SCorentin Chary         n = size >> 2;
8063e230dd2SCorentin Chary         for (i = 0; i < n; i++) {
8073e230dd2SCorentin Chary             vnc_convert_pixel(vs, buf, pixels[i]);
8089f64916dSGerd Hoffmann             vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
8093e230dd2SCorentin Chary         }
8103e230dd2SCorentin Chary     }
8113e230dd2SCorentin Chary }
8123e230dd2SCorentin Chary 
8133e230dd2SCorentin Chary int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8143e230dd2SCorentin Chary {
8153e230dd2SCorentin Chary     int i;
8163e230dd2SCorentin Chary     uint8_t *row;
8173e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
8183e230dd2SCorentin Chary 
8199f64916dSGerd Hoffmann     row = vnc_server_fb_ptr(vd, x, y);
8203e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
8219f64916dSGerd Hoffmann         vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
8229f64916dSGerd Hoffmann         row += vnc_server_fb_stride(vd);
8233e230dd2SCorentin Chary     }
8243e230dd2SCorentin Chary     return 1;
8253e230dd2SCorentin Chary }
8263e230dd2SCorentin Chary 
827bd023f95SCorentin Chary int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
8283e230dd2SCorentin Chary {
8293e230dd2SCorentin Chary     int n = 0;
830de3f7de7SPeter Lieven     bool encode_raw = false;
831de3f7de7SPeter Lieven     size_t saved_offs = vs->output.offset;
8323e230dd2SCorentin Chary 
8333e230dd2SCorentin Chary     switch(vs->vnc_encoding) {
8343e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
8353e230dd2SCorentin Chary             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
8363e230dd2SCorentin Chary             break;
8373e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
8383e230dd2SCorentin Chary             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
8393e230dd2SCorentin Chary             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
8403e230dd2SCorentin Chary             break;
8413e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
8423e230dd2SCorentin Chary             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
8433e230dd2SCorentin Chary             break;
844efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
845efe556adSCorentin Chary             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
846efe556adSCorentin Chary             break;
847148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
848148954faSCorentin Chary             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
849148954faSCorentin Chary             break;
850148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
851148954faSCorentin Chary             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
852148954faSCorentin Chary             break;
8533e230dd2SCorentin Chary         default:
854de3f7de7SPeter Lieven             encode_raw = true;
8553e230dd2SCorentin Chary             break;
8563e230dd2SCorentin Chary     }
857de3f7de7SPeter Lieven 
858de3f7de7SPeter Lieven     /* If the client has the same pixel format as our internal buffer and
859de3f7de7SPeter Lieven      * a RAW encoding would need less space fall back to RAW encoding to
860de3f7de7SPeter Lieven      * save bandwidth and processing power in the client. */
861de3f7de7SPeter Lieven     if (!encode_raw && vs->write_pixels == vnc_write_pixels_copy &&
862de3f7de7SPeter Lieven         12 + h * w * VNC_SERVER_FB_BYTES <= (vs->output.offset - saved_offs)) {
863de3f7de7SPeter Lieven         vs->output.offset = saved_offs;
864de3f7de7SPeter Lieven         encode_raw = true;
865de3f7de7SPeter Lieven     }
866de3f7de7SPeter Lieven 
867de3f7de7SPeter Lieven     if (encode_raw) {
868de3f7de7SPeter Lieven         vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
869de3f7de7SPeter Lieven         n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
870de3f7de7SPeter Lieven     }
871de3f7de7SPeter Lieven 
8723e230dd2SCorentin Chary     return n;
8733e230dd2SCorentin Chary }
8743e230dd2SCorentin Chary 
8753e230dd2SCorentin Chary static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
8763e230dd2SCorentin Chary {
8773e230dd2SCorentin Chary     /* send bitblit op to the vnc client */
878bd023f95SCorentin Chary     vnc_lock_output(vs);
8793e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
8803e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
8813e230dd2SCorentin Chary     vnc_write_u16(vs, 1); /* number of rects */
8823e230dd2SCorentin Chary     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
8833e230dd2SCorentin Chary     vnc_write_u16(vs, src_x);
8843e230dd2SCorentin Chary     vnc_write_u16(vs, src_y);
885bd023f95SCorentin Chary     vnc_unlock_output(vs);
8863e230dd2SCorentin Chary     vnc_flush(vs);
8873e230dd2SCorentin Chary }
8883e230dd2SCorentin Chary 
8897c20b4a3SGerd Hoffmann static void vnc_dpy_copy(DisplayChangeListener *dcl,
8907c20b4a3SGerd Hoffmann                          int src_x, int src_y,
8917c20b4a3SGerd Hoffmann                          int dst_x, int dst_y, int w, int h)
8923e230dd2SCorentin Chary {
89321ef45d7SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
8943e230dd2SCorentin Chary     VncState *vs, *vn;
8953e230dd2SCorentin Chary     uint8_t *src_row;
8963e230dd2SCorentin Chary     uint8_t *dst_row;
8979f64916dSGerd Hoffmann     int i, x, y, pitch, inc, w_lim, s;
8983e230dd2SCorentin Chary     int cmp_bytes;
8993e230dd2SCorentin Chary 
9007fe4a41cSGerd Hoffmann     if (!vd->server) {
9017fe4a41cSGerd Hoffmann         /* no client connected */
9027fe4a41cSGerd Hoffmann         return;
9037fe4a41cSGerd Hoffmann     }
9047fe4a41cSGerd Hoffmann 
9053e230dd2SCorentin Chary     vnc_refresh_server_surface(vd);
9063e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
9073e230dd2SCorentin Chary         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
9083e230dd2SCorentin Chary             vs->force_update = 1;
90938ee14f4SGerd Hoffmann             vnc_update_client(vs, 1, true);
9103e230dd2SCorentin Chary             /* vs might be free()ed here */
9113e230dd2SCorentin Chary         }
9123e230dd2SCorentin Chary     }
9133e230dd2SCorentin Chary 
9143e230dd2SCorentin Chary     /* do bitblit op on the local surface too */
9159f64916dSGerd Hoffmann     pitch = vnc_server_fb_stride(vd);
9169f64916dSGerd Hoffmann     src_row = vnc_server_fb_ptr(vd, src_x, src_y);
9179f64916dSGerd Hoffmann     dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
9183e230dd2SCorentin Chary     y = dst_y;
9193e230dd2SCorentin Chary     inc = 1;
9203e230dd2SCorentin Chary     if (dst_y > src_y) {
9213e230dd2SCorentin Chary         /* copy backwards */
9223e230dd2SCorentin Chary         src_row += pitch * (h-1);
9233e230dd2SCorentin Chary         dst_row += pitch * (h-1);
9243e230dd2SCorentin Chary         pitch = -pitch;
9253e230dd2SCorentin Chary         y = dst_y + h - 1;
9263e230dd2SCorentin Chary         inc = -1;
9273e230dd2SCorentin Chary     }
928b4c85ddcSPeter Lieven     w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
929b4c85ddcSPeter Lieven     if (w_lim < 0) {
9303e230dd2SCorentin Chary         w_lim = w;
931b4c85ddcSPeter Lieven     } else {
932b4c85ddcSPeter Lieven         w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
933b4c85ddcSPeter Lieven     }
9343e230dd2SCorentin Chary     for (i = 0; i < h; i++) {
9353e230dd2SCorentin Chary         for (x = 0; x <= w_lim;
9363e230dd2SCorentin Chary                 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
9373e230dd2SCorentin Chary             if (x == w_lim) {
9383e230dd2SCorentin Chary                 if ((s = w - w_lim) == 0)
9393e230dd2SCorentin Chary                     break;
9403e230dd2SCorentin Chary             } else if (!x) {
941b4c85ddcSPeter Lieven                 s = (VNC_DIRTY_PIXELS_PER_BIT -
942b4c85ddcSPeter Lieven                     (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
9433e230dd2SCorentin Chary                 s = MIN(s, w_lim);
9443e230dd2SCorentin Chary             } else {
945b4c85ddcSPeter Lieven                 s = VNC_DIRTY_PIXELS_PER_BIT;
9463e230dd2SCorentin Chary             }
9479f64916dSGerd Hoffmann             cmp_bytes = s * VNC_SERVER_FB_BYTES;
9483e230dd2SCorentin Chary             if (memcmp(src_row, dst_row, cmp_bytes) == 0)
9493e230dd2SCorentin Chary                 continue;
9503e230dd2SCorentin Chary             memmove(dst_row, src_row, cmp_bytes);
9513e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
9523e230dd2SCorentin Chary                 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
953b4c85ddcSPeter Lieven                     set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
954b4c85ddcSPeter Lieven                             vs->dirty[y]);
9553e230dd2SCorentin Chary                 }
9563e230dd2SCorentin Chary             }
9573e230dd2SCorentin Chary         }
9589f64916dSGerd Hoffmann         src_row += pitch - w * VNC_SERVER_FB_BYTES;
9599f64916dSGerd Hoffmann         dst_row += pitch - w * VNC_SERVER_FB_BYTES;
9603e230dd2SCorentin Chary         y += inc;
9613e230dd2SCorentin Chary     }
9623e230dd2SCorentin Chary 
9633e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
9643e230dd2SCorentin Chary         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
9653e230dd2SCorentin Chary             vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
9663e230dd2SCorentin Chary         }
9673e230dd2SCorentin Chary     }
9683e230dd2SCorentin Chary }
9693e230dd2SCorentin Chary 
9707c20b4a3SGerd Hoffmann static void vnc_mouse_set(DisplayChangeListener *dcl,
9717c20b4a3SGerd Hoffmann                           int x, int y, int visible)
9723e230dd2SCorentin Chary {
9733e230dd2SCorentin Chary     /* can we ask the client(s) to move the pointer ??? */
9743e230dd2SCorentin Chary }
9753e230dd2SCorentin Chary 
9763e230dd2SCorentin Chary static int vnc_cursor_define(VncState *vs)
9773e230dd2SCorentin Chary {
9783e230dd2SCorentin Chary     QEMUCursor *c = vs->vd->cursor;
9793e230dd2SCorentin Chary     int isize;
9803e230dd2SCorentin Chary 
9813e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
982d01f9595SCorentin Chary         vnc_lock_output(vs);
9833e230dd2SCorentin Chary         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
9843e230dd2SCorentin Chary         vnc_write_u8(vs,  0);  /*  padding     */
9853e230dd2SCorentin Chary         vnc_write_u16(vs, 1);  /*  # of rects  */
9863e230dd2SCorentin Chary         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
9873e230dd2SCorentin Chary                                VNC_ENCODING_RICH_CURSOR);
9889f64916dSGerd Hoffmann         isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
9899f64916dSGerd Hoffmann         vnc_write_pixels_generic(vs, c->data, isize);
9903e230dd2SCorentin Chary         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
991d01f9595SCorentin Chary         vnc_unlock_output(vs);
9923e230dd2SCorentin Chary         return 0;
9933e230dd2SCorentin Chary     }
9943e230dd2SCorentin Chary     return -1;
9953e230dd2SCorentin Chary }
9963e230dd2SCorentin Chary 
9977c20b4a3SGerd Hoffmann static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
9987c20b4a3SGerd Hoffmann                                   QEMUCursor *c)
9993e230dd2SCorentin Chary {
1000d616ccc5SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
10013e230dd2SCorentin Chary     VncState *vs;
10023e230dd2SCorentin Chary 
10033e230dd2SCorentin Chary     cursor_put(vd->cursor);
10047267c094SAnthony Liguori     g_free(vd->cursor_mask);
10053e230dd2SCorentin Chary 
10063e230dd2SCorentin Chary     vd->cursor = c;
10073e230dd2SCorentin Chary     cursor_get(vd->cursor);
10083e230dd2SCorentin Chary     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
10097267c094SAnthony Liguori     vd->cursor_mask = g_malloc0(vd->cursor_msize);
10103e230dd2SCorentin Chary     cursor_get_mono_mask(c, 0, vd->cursor_mask);
10113e230dd2SCorentin Chary 
10123e230dd2SCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
10133e230dd2SCorentin Chary         vnc_cursor_define(vs);
10143e230dd2SCorentin Chary     }
10153e230dd2SCorentin Chary }
10163e230dd2SCorentin Chary 
10174769a881SChih-Min Chao static int find_and_clear_dirty_height(VncState *vs,
10186c71a539SCorentin Chary                                        int y, int last_x, int x, int height)
10193e230dd2SCorentin Chary {
10203e230dd2SCorentin Chary     int h;
10213e230dd2SCorentin Chary 
10226c71a539SCorentin Chary     for (h = 1; h < (height - y); h++) {
1023bc2429b9SCorentin Chary         if (!test_bit(last_x, vs->dirty[y + h])) {
10243e230dd2SCorentin Chary             break;
1025bc2429b9SCorentin Chary         }
1026863d7c91SPeter Lieven         bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
10273e230dd2SCorentin Chary     }
10283e230dd2SCorentin Chary 
10293e230dd2SCorentin Chary     return h;
10303e230dd2SCorentin Chary }
10313e230dd2SCorentin Chary 
103238ee14f4SGerd Hoffmann static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
10333e230dd2SCorentin Chary {
10345a8be0f7SGerd Hoffmann     if (vs->disconnecting) {
10355a8be0f7SGerd Hoffmann         vnc_disconnect_finish(vs);
10365a8be0f7SGerd Hoffmann         return 0;
10375a8be0f7SGerd Hoffmann     }
10385a8be0f7SGerd Hoffmann 
103963658280SGerd Hoffmann     vs->has_dirty += has_dirty;
10405a693efdSGonglei     if (vs->need_update && !vs->disconnecting) {
10413e230dd2SCorentin Chary         VncDisplay *vd = vs->vd;
1042bd023f95SCorentin Chary         VncJob *job;
10433e230dd2SCorentin Chary         int y;
10442f487a3dSPeter Lieven         int height, width;
1045bd023f95SCorentin Chary         int n = 0;
1046bd023f95SCorentin Chary 
10473e230dd2SCorentin Chary         if (vs->output.offset && !vs->audio_cap && !vs->force_update)
10483e230dd2SCorentin Chary             /* kernel send buffers are full -> drop frames to throttle */
10493e230dd2SCorentin Chary             return 0;
10503e230dd2SCorentin Chary 
105163658280SGerd Hoffmann         if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)
10523e230dd2SCorentin Chary             return 0;
10533e230dd2SCorentin Chary 
10543e230dd2SCorentin Chary         /*
10553e230dd2SCorentin Chary          * Send screen updates to the vnc client using the server
10563e230dd2SCorentin Chary          * surface and server dirty map.  guest surface updates
10573e230dd2SCorentin Chary          * happening in parallel don't disturb us, the next pass will
10583e230dd2SCorentin Chary          * send them to the client.
10593e230dd2SCorentin Chary          */
1060bd023f95SCorentin Chary         job = vnc_job_new(vs);
10613e230dd2SCorentin Chary 
1062bea60dd7SPeter Lieven         height = pixman_image_get_height(vd->server);
1063bea60dd7SPeter Lieven         width = pixman_image_get_width(vd->server);
10643e230dd2SCorentin Chary 
106512b316d4SPeter Lieven         y = 0;
106612b316d4SPeter Lieven         for (;;) {
106712b316d4SPeter Lieven             int x, h;
106812b316d4SPeter Lieven             unsigned long x2;
106912b316d4SPeter Lieven             unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
107012b316d4SPeter Lieven                                                  height * VNC_DIRTY_BPL(vs),
107112b316d4SPeter Lieven                                                  y * VNC_DIRTY_BPL(vs));
107212b316d4SPeter Lieven             if (offset == height * VNC_DIRTY_BPL(vs)) {
107312b316d4SPeter Lieven                 /* no more dirty bits */
107412b316d4SPeter Lieven                 break;
10753e230dd2SCorentin Chary             }
107612b316d4SPeter Lieven             y = offset / VNC_DIRTY_BPL(vs);
107712b316d4SPeter Lieven             x = offset % VNC_DIRTY_BPL(vs);
107812b316d4SPeter Lieven             x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
107912b316d4SPeter Lieven                                     VNC_DIRTY_BPL(vs), x);
108012b316d4SPeter Lieven             bitmap_clear(vs->dirty[y], x, x2 - x);
108112b316d4SPeter Lieven             h = find_and_clear_dirty_height(vs, y, x, x2, height);
10822f487a3dSPeter Lieven             x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
10832f487a3dSPeter Lieven             if (x2 > x) {
108412b316d4SPeter Lieven                 n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
108512b316d4SPeter Lieven                                       (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
10863e230dd2SCorentin Chary             }
10870e7d6f60SPeter Lieven             if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
10880e7d6f60SPeter Lieven                 y += h;
10890e7d6f60SPeter Lieven                 if (y == height) {
10900e7d6f60SPeter Lieven                     break;
10910e7d6f60SPeter Lieven                 }
10920e7d6f60SPeter Lieven             }
10932f487a3dSPeter Lieven         }
1094bd023f95SCorentin Chary 
1095bd023f95SCorentin Chary         vnc_job_push(job);
1096eb214ff8SGerd Hoffmann         if (sync) {
1097eb214ff8SGerd Hoffmann             vnc_jobs_join(vs);
1098eb214ff8SGerd Hoffmann         }
10993e230dd2SCorentin Chary         vs->force_update = 0;
110063658280SGerd Hoffmann         vs->has_dirty = 0;
1101bd023f95SCorentin Chary         return n;
11023e230dd2SCorentin Chary     }
11033e230dd2SCorentin Chary 
110404d2529dSDaniel P. Berrange     if (vs->disconnecting) {
11053e230dd2SCorentin Chary         vnc_disconnect_finish(vs);
110638ee14f4SGerd Hoffmann     } else if (sync) {
110738ee14f4SGerd Hoffmann         vnc_jobs_join(vs);
110838ee14f4SGerd Hoffmann     }
11093e230dd2SCorentin Chary 
11103e230dd2SCorentin Chary     return 0;
11113e230dd2SCorentin Chary }
11123e230dd2SCorentin Chary 
11133e230dd2SCorentin Chary /* audio */
11143e230dd2SCorentin Chary static void audio_capture_notify(void *opaque, audcnotification_e cmd)
11153e230dd2SCorentin Chary {
11163e230dd2SCorentin Chary     VncState *vs = opaque;
11173e230dd2SCorentin Chary 
11183e230dd2SCorentin Chary     switch (cmd) {
11193e230dd2SCorentin Chary     case AUD_CNOTIFY_DISABLE:
1120bd023f95SCorentin Chary         vnc_lock_output(vs);
11213e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11223e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11233e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1124bd023f95SCorentin Chary         vnc_unlock_output(vs);
11253e230dd2SCorentin Chary         vnc_flush(vs);
11263e230dd2SCorentin Chary         break;
11273e230dd2SCorentin Chary 
11283e230dd2SCorentin Chary     case AUD_CNOTIFY_ENABLE:
1129bd023f95SCorentin Chary         vnc_lock_output(vs);
11303e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11313e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11323e230dd2SCorentin Chary         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1133bd023f95SCorentin Chary         vnc_unlock_output(vs);
11343e230dd2SCorentin Chary         vnc_flush(vs);
11353e230dd2SCorentin Chary         break;
11363e230dd2SCorentin Chary     }
11373e230dd2SCorentin Chary }
11383e230dd2SCorentin Chary 
11393e230dd2SCorentin Chary static void audio_capture_destroy(void *opaque)
11403e230dd2SCorentin Chary {
11413e230dd2SCorentin Chary }
11423e230dd2SCorentin Chary 
11433e230dd2SCorentin Chary static void audio_capture(void *opaque, void *buf, int size)
11443e230dd2SCorentin Chary {
11453e230dd2SCorentin Chary     VncState *vs = opaque;
11463e230dd2SCorentin Chary 
1147bd023f95SCorentin Chary     vnc_lock_output(vs);
11483e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
11493e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
11503e230dd2SCorentin Chary     vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
11513e230dd2SCorentin Chary     vnc_write_u32(vs, size);
11523e230dd2SCorentin Chary     vnc_write(vs, buf, size);
1153bd023f95SCorentin Chary     vnc_unlock_output(vs);
11543e230dd2SCorentin Chary     vnc_flush(vs);
11553e230dd2SCorentin Chary }
11563e230dd2SCorentin Chary 
11573e230dd2SCorentin Chary static void audio_add(VncState *vs)
11583e230dd2SCorentin Chary {
11593e230dd2SCorentin Chary     struct audio_capture_ops ops;
11603e230dd2SCorentin Chary 
11613e230dd2SCorentin Chary     if (vs->audio_cap) {
1162027a79c3SCole Robinson         error_report("audio already running");
11633e230dd2SCorentin Chary         return;
11643e230dd2SCorentin Chary     }
11653e230dd2SCorentin Chary 
11663e230dd2SCorentin Chary     ops.notify = audio_capture_notify;
11673e230dd2SCorentin Chary     ops.destroy = audio_capture_destroy;
11683e230dd2SCorentin Chary     ops.capture = audio_capture;
11693e230dd2SCorentin Chary 
11703e230dd2SCorentin Chary     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
11713e230dd2SCorentin Chary     if (!vs->audio_cap) {
1172027a79c3SCole Robinson         error_report("Failed to add audio capture");
11733e230dd2SCorentin Chary     }
11743e230dd2SCorentin Chary }
11753e230dd2SCorentin Chary 
11763e230dd2SCorentin Chary static void audio_del(VncState *vs)
11773e230dd2SCorentin Chary {
11783e230dd2SCorentin Chary     if (vs->audio_cap) {
11793e230dd2SCorentin Chary         AUD_del_capture(vs->audio_cap, vs);
11803e230dd2SCorentin Chary         vs->audio_cap = NULL;
11813e230dd2SCorentin Chary     }
11823e230dd2SCorentin Chary }
11833e230dd2SCorentin Chary 
11843e230dd2SCorentin Chary static void vnc_disconnect_start(VncState *vs)
11853e230dd2SCorentin Chary {
118604d2529dSDaniel P. Berrange     if (vs->disconnecting) {
11873e230dd2SCorentin Chary         return;
118804d2529dSDaniel P. Berrange     }
11898cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
119004d2529dSDaniel P. Berrange     if (vs->ioc_tag) {
119104d2529dSDaniel P. Berrange         g_source_remove(vs->ioc_tag);
119204d2529dSDaniel P. Berrange     }
119304d2529dSDaniel P. Berrange     qio_channel_close(vs->ioc, NULL);
119404d2529dSDaniel P. Berrange     vs->disconnecting = TRUE;
11953e230dd2SCorentin Chary }
11963e230dd2SCorentin Chary 
11977536ee4bSTim Hardeck void vnc_disconnect_finish(VncState *vs)
11983e230dd2SCorentin Chary {
11997d964c9dSCorentin Chary     int i;
12007d964c9dSCorentin Chary 
1201bd023f95SCorentin Chary     vnc_jobs_join(vs); /* Wait encoding jobs */
1202bd023f95SCorentin Chary 
1203bd023f95SCorentin Chary     vnc_lock_output(vs);
1204fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
12053e230dd2SCorentin Chary 
12063e230dd2SCorentin Chary     buffer_free(&vs->input);
12073e230dd2SCorentin Chary     buffer_free(&vs->output);
12083e230dd2SCorentin Chary 
1209fb6ba0d5SWenchao Xia     qapi_free_VncClientInfo(vs->info);
12103e230dd2SCorentin Chary 
12113e230dd2SCorentin Chary     vnc_zlib_clear(vs);
12123e230dd2SCorentin Chary     vnc_tight_clear(vs);
1213148954faSCorentin Chary     vnc_zrle_clear(vs);
12143e230dd2SCorentin Chary 
12153e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
12163e230dd2SCorentin Chary     vnc_sasl_client_cleanup(vs);
12173e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
12183e230dd2SCorentin Chary     audio_del(vs);
12197bc9318bSGerd Hoffmann     vnc_release_modifiers(vs);
12203e230dd2SCorentin Chary 
12216fd8e79aSTim Hardeck     if (vs->initialized) {
12223e230dd2SCorentin Chary         QTAILQ_REMOVE(&vs->vd->clients, vs, next);
12236fd8e79aSTim Hardeck         qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1224c7628bffSGerd Hoffmann         if (QTAILQ_EMPTY(&vs->vd->clients)) {
1225c7628bffSGerd Hoffmann             /* last client gone */
1226c7628bffSGerd Hoffmann             vnc_update_server_surface(vs->vd);
1227c7628bffSGerd Hoffmann         }
12286fd8e79aSTim Hardeck     }
12293e230dd2SCorentin Chary 
12303e230dd2SCorentin Chary     if (vs->vd->lock_key_sync)
12313e230dd2SCorentin Chary         qemu_remove_led_event_handler(vs->led);
1232bd023f95SCorentin Chary     vnc_unlock_output(vs);
1233bd023f95SCorentin Chary 
1234bd023f95SCorentin Chary     qemu_mutex_destroy(&vs->output_mutex);
12356fd8e79aSTim Hardeck     if (vs->bh != NULL) {
1236175b2a6eSCorentin Chary         qemu_bh_delete(vs->bh);
12376fd8e79aSTim Hardeck     }
1238175b2a6eSCorentin Chary     buffer_free(&vs->jobs_buffer);
1239175b2a6eSCorentin Chary 
12407d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
12417267c094SAnthony Liguori         g_free(vs->lossy_rect[i]);
12427d964c9dSCorentin Chary     }
12437267c094SAnthony Liguori     g_free(vs->lossy_rect);
124404d2529dSDaniel P. Berrange 
124504d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->ioc));
124604d2529dSDaniel P. Berrange     vs->ioc = NULL;
124704d2529dSDaniel P. Berrange     object_unref(OBJECT(vs->sioc));
124804d2529dSDaniel P. Berrange     vs->sioc = NULL;
12497267c094SAnthony Liguori     g_free(vs);
12503e230dd2SCorentin Chary }
12513e230dd2SCorentin Chary 
125204d2529dSDaniel P. Berrange ssize_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
12533e230dd2SCorentin Chary {
125404d2529dSDaniel P. Berrange     if (ret <= 0) {
125504d2529dSDaniel P. Berrange         if (ret == 0) {
125604d2529dSDaniel P. Berrange             VNC_DEBUG("Closing down client sock: EOF\n");
125704d2529dSDaniel P. Berrange         } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
125804d2529dSDaniel P. Berrange             VNC_DEBUG("Closing down client sock: ret %d (%s)\n",
125904d2529dSDaniel P. Berrange                       ret, errp ? error_get_pretty(*errp) : "Unknown");
12603e230dd2SCorentin Chary         }
12613e230dd2SCorentin Chary 
12623e230dd2SCorentin Chary         vnc_disconnect_start(vs);
126304d2529dSDaniel P. Berrange         if (errp) {
126404d2529dSDaniel P. Berrange             error_free(*errp);
126504d2529dSDaniel P. Berrange             *errp = NULL;
126604d2529dSDaniel P. Berrange         }
12673e230dd2SCorentin Chary         return 0;
12683e230dd2SCorentin Chary     }
12693e230dd2SCorentin Chary     return ret;
12703e230dd2SCorentin Chary }
12713e230dd2SCorentin Chary 
12723e230dd2SCorentin Chary 
12733e230dd2SCorentin Chary void vnc_client_error(VncState *vs)
12743e230dd2SCorentin Chary {
12753e230dd2SCorentin Chary     VNC_DEBUG("Closing down client sock: protocol error\n");
12763e230dd2SCorentin Chary     vnc_disconnect_start(vs);
12773e230dd2SCorentin Chary }
12783e230dd2SCorentin Chary 
12793e305e4aSDaniel P. Berrange 
12803e230dd2SCorentin Chary /*
12813e230dd2SCorentin Chary  * Called to write a chunk of data to the client socket. The data may
12823e230dd2SCorentin Chary  * be the raw data, or may have already been encoded by SASL.
12833e230dd2SCorentin Chary  * The data will be written either straight onto the socket, or
12843e230dd2SCorentin Chary  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
12853e230dd2SCorentin Chary  *
12863e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
12873e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
12883e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
12893e230dd2SCorentin Chary  * is active
12903e230dd2SCorentin Chary  *
12913e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
12923e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
12933e230dd2SCorentin Chary  * -1 on error, and disconnects the client socket.
12943e230dd2SCorentin Chary  */
1295fdd1ab6aSDaniel P. Berrange ssize_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
12963e230dd2SCorentin Chary {
129704d2529dSDaniel P. Berrange     Error *err = NULL;
1298fdd1ab6aSDaniel P. Berrange     ssize_t ret;
129904d2529dSDaniel P. Berrange     ret = qio_channel_write(
130004d2529dSDaniel P. Berrange         vs->ioc, (const char *)data, datalen, &err);
13013e230dd2SCorentin Chary     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
130204d2529dSDaniel P. Berrange     return vnc_client_io_error(vs, ret, &err);
13033e230dd2SCorentin Chary }
13043e230dd2SCorentin Chary 
13053e230dd2SCorentin Chary 
13063e230dd2SCorentin Chary /*
13073e230dd2SCorentin Chary  * Called to write buffered data to the client socket, when not
13083e230dd2SCorentin Chary  * using any SASL SSF encryption layers. Will write as much data
13093e230dd2SCorentin Chary  * as possible without blocking. If all buffered data is written,
13103e230dd2SCorentin Chary  * will switch the FD poll() handler back to read monitoring.
13113e230dd2SCorentin Chary  *
13123e230dd2SCorentin Chary  * Returns the number of bytes written, which may be less than
13133e230dd2SCorentin Chary  * the buffered output data if the socket would block. Returns
13143e230dd2SCorentin Chary  * -1 on error, and disconnects the client socket.
13153e230dd2SCorentin Chary  */
1316fdd1ab6aSDaniel P. Berrange static ssize_t vnc_client_write_plain(VncState *vs)
13173e230dd2SCorentin Chary {
1318fdd1ab6aSDaniel P. Berrange     ssize_t ret;
13193e230dd2SCorentin Chary 
13203e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13213e230dd2SCorentin Chary     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
13223e230dd2SCorentin Chary               vs->output.buffer, vs->output.capacity, vs->output.offset,
13233e230dd2SCorentin Chary               vs->sasl.waitWriteSSF);
13243e230dd2SCorentin Chary 
13253e230dd2SCorentin Chary     if (vs->sasl.conn &&
13263e230dd2SCorentin Chary         vs->sasl.runSSF &&
13273e230dd2SCorentin Chary         vs->sasl.waitWriteSSF) {
13283e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
13293e230dd2SCorentin Chary         if (ret)
13303e230dd2SCorentin Chary             vs->sasl.waitWriteSSF -= ret;
13313e230dd2SCorentin Chary     } else
13323e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13333e230dd2SCorentin Chary         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
13343e230dd2SCorentin Chary     if (!ret)
13353e230dd2SCorentin Chary         return 0;
13363e230dd2SCorentin Chary 
133732ed2680STim Hardeck     buffer_advance(&vs->output, ret);
13383e230dd2SCorentin Chary 
13393e230dd2SCorentin Chary     if (vs->output.offset == 0) {
134004d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
134104d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
134204d2529dSDaniel P. Berrange         }
134304d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
134404d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
13453e230dd2SCorentin Chary     }
13463e230dd2SCorentin Chary 
13473e230dd2SCorentin Chary     return ret;
13483e230dd2SCorentin Chary }
13493e230dd2SCorentin Chary 
13503e230dd2SCorentin Chary 
13513e230dd2SCorentin Chary /*
13523e230dd2SCorentin Chary  * First function called whenever there is data to be written to
13533e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
13543e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring encryption calls)
13553e230dd2SCorentin Chary  */
135604d2529dSDaniel P. Berrange static void vnc_client_write_locked(VncState *vs)
13573e230dd2SCorentin Chary {
13583e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
13593e230dd2SCorentin Chary     if (vs->sasl.conn &&
13603e230dd2SCorentin Chary         vs->sasl.runSSF &&
13613e230dd2SCorentin Chary         !vs->sasl.waitWriteSSF) {
13623e230dd2SCorentin Chary         vnc_client_write_sasl(vs);
13633e230dd2SCorentin Chary     } else
13643e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
13657536ee4bSTim Hardeck     {
13663e230dd2SCorentin Chary         vnc_client_write_plain(vs);
13673e230dd2SCorentin Chary     }
13687536ee4bSTim Hardeck }
13693e230dd2SCorentin Chary 
137004d2529dSDaniel P. Berrange static void vnc_client_write(VncState *vs)
1371bd023f95SCorentin Chary {
1372bd023f95SCorentin Chary 
1373bd023f95SCorentin Chary     vnc_lock_output(vs);
1374d5f04223SDaniel P. Berrange     if (vs->output.offset) {
137504d2529dSDaniel P. Berrange         vnc_client_write_locked(vs);
137604d2529dSDaniel P. Berrange     } else if (vs->ioc != NULL) {
137704d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
137804d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
137904d2529dSDaniel P. Berrange         }
138004d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
138104d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1382bd023f95SCorentin Chary     }
1383bd023f95SCorentin Chary     vnc_unlock_output(vs);
1384bd023f95SCorentin Chary }
1385bd023f95SCorentin Chary 
13863e230dd2SCorentin Chary void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
13873e230dd2SCorentin Chary {
13883e230dd2SCorentin Chary     vs->read_handler = func;
13893e230dd2SCorentin Chary     vs->read_handler_expect = expecting;
13903e230dd2SCorentin Chary }
13913e230dd2SCorentin Chary 
13923e230dd2SCorentin Chary 
13933e230dd2SCorentin Chary /*
13943e230dd2SCorentin Chary  * Called to read a chunk of data from the client socket. The data may
13953e230dd2SCorentin Chary  * be the raw data, or may need to be further decoded by SASL.
13963e230dd2SCorentin Chary  * The data will be read either straight from to the socket, or
13973e230dd2SCorentin Chary  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
13983e230dd2SCorentin Chary  *
13993e230dd2SCorentin Chary  * NB, it is theoretically possible to have 2 layers of encryption,
14003e230dd2SCorentin Chary  * both SASL, and this TLS layer. It is highly unlikely in practice
14013e230dd2SCorentin Chary  * though, since SASL encryption will typically be a no-op if TLS
14023e230dd2SCorentin Chary  * is active
14033e230dd2SCorentin Chary  *
14043e230dd2SCorentin Chary  * Returns the number of bytes read, which may be less than
14053e230dd2SCorentin Chary  * the requested 'datalen' if the socket would block. Returns
14063e230dd2SCorentin Chary  * -1 on error, and disconnects the client socket.
14073e230dd2SCorentin Chary  */
1408fdd1ab6aSDaniel P. Berrange ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
14093e230dd2SCorentin Chary {
1410fdd1ab6aSDaniel P. Berrange     ssize_t ret;
141104d2529dSDaniel P. Berrange     Error *err = NULL;
141204d2529dSDaniel P. Berrange     ret = qio_channel_read(
141304d2529dSDaniel P. Berrange         vs->ioc, (char *)data, datalen, &err);
14143e230dd2SCorentin Chary     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
141504d2529dSDaniel P. Berrange     return vnc_client_io_error(vs, ret, &err);
14163e230dd2SCorentin Chary }
14173e230dd2SCorentin Chary 
14183e230dd2SCorentin Chary 
14193e230dd2SCorentin Chary /*
14203e230dd2SCorentin Chary  * Called to read data from the client socket to the input buffer,
14213e230dd2SCorentin Chary  * when not using any SASL SSF encryption layers. Will read as much
14223e230dd2SCorentin Chary  * data as possible without blocking.
14233e230dd2SCorentin Chary  *
14243e230dd2SCorentin Chary  * Returns the number of bytes read. Returns -1 on error, and
14253e230dd2SCorentin Chary  * disconnects the client socket.
14263e230dd2SCorentin Chary  */
1427fdd1ab6aSDaniel P. Berrange static ssize_t vnc_client_read_plain(VncState *vs)
14283e230dd2SCorentin Chary {
1429fdd1ab6aSDaniel P. Berrange     ssize_t ret;
14303e230dd2SCorentin Chary     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
14313e230dd2SCorentin Chary               vs->input.buffer, vs->input.capacity, vs->input.offset);
14323e230dd2SCorentin Chary     buffer_reserve(&vs->input, 4096);
14333e230dd2SCorentin Chary     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
14343e230dd2SCorentin Chary     if (!ret)
14353e230dd2SCorentin Chary         return 0;
14363e230dd2SCorentin Chary     vs->input.offset += ret;
14373e230dd2SCorentin Chary     return ret;
14383e230dd2SCorentin Chary }
14393e230dd2SCorentin Chary 
1440175b2a6eSCorentin Chary static void vnc_jobs_bh(void *opaque)
1441175b2a6eSCorentin Chary {
1442175b2a6eSCorentin Chary     VncState *vs = opaque;
1443175b2a6eSCorentin Chary 
1444175b2a6eSCorentin Chary     vnc_jobs_consume_buffer(vs);
1445175b2a6eSCorentin Chary }
14463e230dd2SCorentin Chary 
14473e230dd2SCorentin Chary /*
14483e230dd2SCorentin Chary  * First function called whenever there is more data to be read from
14493e230dd2SCorentin Chary  * the client socket. Will delegate actual work according to whether
14503e230dd2SCorentin Chary  * SASL SSF layers are enabled (thus requiring decryption calls)
1451ea697449SDaniel P. Berrange  * Returns 0 on success, -1 if client disconnected
14523e230dd2SCorentin Chary  */
1453ea697449SDaniel P. Berrange static int vnc_client_read(VncState *vs)
14543e230dd2SCorentin Chary {
1455fdd1ab6aSDaniel P. Berrange     ssize_t ret;
14563e230dd2SCorentin Chary 
14573e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
14583e230dd2SCorentin Chary     if (vs->sasl.conn && vs->sasl.runSSF)
14593e230dd2SCorentin Chary         ret = vnc_client_read_sasl(vs);
14603e230dd2SCorentin Chary     else
14613e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
14623e230dd2SCorentin Chary         ret = vnc_client_read_plain(vs);
14633e230dd2SCorentin Chary     if (!ret) {
146404d2529dSDaniel P. Berrange         if (vs->disconnecting) {
14653e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1466ea697449SDaniel P. Berrange             return -1;
146704d2529dSDaniel P. Berrange         }
1468ea697449SDaniel P. Berrange         return 0;
14693e230dd2SCorentin Chary     }
14703e230dd2SCorentin Chary 
14713e230dd2SCorentin Chary     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
14723e230dd2SCorentin Chary         size_t len = vs->read_handler_expect;
14733e230dd2SCorentin Chary         int ret;
14743e230dd2SCorentin Chary 
14753e230dd2SCorentin Chary         ret = vs->read_handler(vs, vs->input.buffer, len);
147604d2529dSDaniel P. Berrange         if (vs->disconnecting) {
14773e230dd2SCorentin Chary             vnc_disconnect_finish(vs);
1478ea697449SDaniel P. Berrange             return -1;
14793e230dd2SCorentin Chary         }
14803e230dd2SCorentin Chary 
14813e230dd2SCorentin Chary         if (!ret) {
148232ed2680STim Hardeck             buffer_advance(&vs->input, len);
14833e230dd2SCorentin Chary         } else {
14843e230dd2SCorentin Chary             vs->read_handler_expect = ret;
14853e230dd2SCorentin Chary         }
14863e230dd2SCorentin Chary     }
1487ea697449SDaniel P. Berrange     return 0;
14883e230dd2SCorentin Chary }
14893e230dd2SCorentin Chary 
149004d2529dSDaniel P. Berrange gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
149104d2529dSDaniel P. Berrange                        GIOCondition condition, void *opaque)
149204d2529dSDaniel P. Berrange {
149304d2529dSDaniel P. Berrange     VncState *vs = opaque;
149404d2529dSDaniel P. Berrange     if (condition & G_IO_IN) {
1495ea697449SDaniel P. Berrange         if (vnc_client_read(vs) < 0) {
1496ea697449SDaniel P. Berrange             return TRUE;
1497ea697449SDaniel P. Berrange         }
149804d2529dSDaniel P. Berrange     }
149904d2529dSDaniel P. Berrange     if (condition & G_IO_OUT) {
150004d2529dSDaniel P. Berrange         vnc_client_write(vs);
150104d2529dSDaniel P. Berrange     }
150204d2529dSDaniel P. Berrange     return TRUE;
150304d2529dSDaniel P. Berrange }
150404d2529dSDaniel P. Berrange 
150504d2529dSDaniel P. Berrange 
15063e230dd2SCorentin Chary void vnc_write(VncState *vs, const void *data, size_t len)
15073e230dd2SCorentin Chary {
15083e230dd2SCorentin Chary     buffer_reserve(&vs->output, len);
15093e230dd2SCorentin Chary 
151004d2529dSDaniel P. Berrange     if (vs->ioc != NULL && buffer_empty(&vs->output)) {
151104d2529dSDaniel P. Berrange         if (vs->ioc_tag) {
151204d2529dSDaniel P. Berrange             g_source_remove(vs->ioc_tag);
151304d2529dSDaniel P. Berrange         }
151404d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
151504d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
15163e230dd2SCorentin Chary     }
15173e230dd2SCorentin Chary 
15183e230dd2SCorentin Chary     buffer_append(&vs->output, data, len);
15193e230dd2SCorentin Chary }
15203e230dd2SCorentin Chary 
15213e230dd2SCorentin Chary void vnc_write_s32(VncState *vs, int32_t value)
15223e230dd2SCorentin Chary {
15233e230dd2SCorentin Chary     vnc_write_u32(vs, *(uint32_t *)&value);
15243e230dd2SCorentin Chary }
15253e230dd2SCorentin Chary 
15263e230dd2SCorentin Chary void vnc_write_u32(VncState *vs, uint32_t value)
15273e230dd2SCorentin Chary {
15283e230dd2SCorentin Chary     uint8_t buf[4];
15293e230dd2SCorentin Chary 
15303e230dd2SCorentin Chary     buf[0] = (value >> 24) & 0xFF;
15313e230dd2SCorentin Chary     buf[1] = (value >> 16) & 0xFF;
15323e230dd2SCorentin Chary     buf[2] = (value >>  8) & 0xFF;
15333e230dd2SCorentin Chary     buf[3] = value & 0xFF;
15343e230dd2SCorentin Chary 
15353e230dd2SCorentin Chary     vnc_write(vs, buf, 4);
15363e230dd2SCorentin Chary }
15373e230dd2SCorentin Chary 
15383e230dd2SCorentin Chary void vnc_write_u16(VncState *vs, uint16_t value)
15393e230dd2SCorentin Chary {
15403e230dd2SCorentin Chary     uint8_t buf[2];
15413e230dd2SCorentin Chary 
15423e230dd2SCorentin Chary     buf[0] = (value >> 8) & 0xFF;
15433e230dd2SCorentin Chary     buf[1] = value & 0xFF;
15443e230dd2SCorentin Chary 
15453e230dd2SCorentin Chary     vnc_write(vs, buf, 2);
15463e230dd2SCorentin Chary }
15473e230dd2SCorentin Chary 
15483e230dd2SCorentin Chary void vnc_write_u8(VncState *vs, uint8_t value)
15493e230dd2SCorentin Chary {
15503e230dd2SCorentin Chary     vnc_write(vs, (char *)&value, 1);
15513e230dd2SCorentin Chary }
15523e230dd2SCorentin Chary 
15533e230dd2SCorentin Chary void vnc_flush(VncState *vs)
15543e230dd2SCorentin Chary {
1555bd023f95SCorentin Chary     vnc_lock_output(vs);
1556d5f04223SDaniel P. Berrange     if (vs->ioc != NULL && vs->output.offset) {
1557bd023f95SCorentin Chary         vnc_client_write_locked(vs);
1558bd023f95SCorentin Chary     }
1559bd023f95SCorentin Chary     vnc_unlock_output(vs);
15603e230dd2SCorentin Chary }
15613e230dd2SCorentin Chary 
156271a8cdecSBlue Swirl static uint8_t read_u8(uint8_t *data, size_t offset)
15633e230dd2SCorentin Chary {
15643e230dd2SCorentin Chary     return data[offset];
15653e230dd2SCorentin Chary }
15663e230dd2SCorentin Chary 
156771a8cdecSBlue Swirl static uint16_t read_u16(uint8_t *data, size_t offset)
15683e230dd2SCorentin Chary {
15693e230dd2SCorentin Chary     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
15703e230dd2SCorentin Chary }
15713e230dd2SCorentin Chary 
157271a8cdecSBlue Swirl static int32_t read_s32(uint8_t *data, size_t offset)
15733e230dd2SCorentin Chary {
15743e230dd2SCorentin Chary     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
15753e230dd2SCorentin Chary                      (data[offset + 2] << 8) | data[offset + 3]);
15763e230dd2SCorentin Chary }
15773e230dd2SCorentin Chary 
15783e230dd2SCorentin Chary uint32_t read_u32(uint8_t *data, size_t offset)
15793e230dd2SCorentin Chary {
15803e230dd2SCorentin Chary     return ((data[offset] << 24) | (data[offset + 1] << 16) |
15813e230dd2SCorentin Chary             (data[offset + 2] << 8) | data[offset + 3]);
15823e230dd2SCorentin Chary }
15833e230dd2SCorentin Chary 
15843e230dd2SCorentin Chary static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
15853e230dd2SCorentin Chary {
15863e230dd2SCorentin Chary }
15873e230dd2SCorentin Chary 
15889e8dd451SJan Kiszka static void check_pointer_type_change(Notifier *notifier, void *data)
15893e230dd2SCorentin Chary {
15903e230dd2SCorentin Chary     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
159114768ebaSGerd Hoffmann     int absolute = qemu_input_is_absolute();
15923e230dd2SCorentin Chary 
15933e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1594bd023f95SCorentin Chary         vnc_lock_output(vs);
15953e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
15963e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
15973e230dd2SCorentin Chary         vnc_write_u16(vs, 1);
15983e230dd2SCorentin Chary         vnc_framebuffer_update(vs, absolute, 0,
1599bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
1600bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
16013e230dd2SCorentin Chary                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1602bd023f95SCorentin Chary         vnc_unlock_output(vs);
16033e230dd2SCorentin Chary         vnc_flush(vs);
16043e230dd2SCorentin Chary     }
16053e230dd2SCorentin Chary     vs->absolute = absolute;
16063e230dd2SCorentin Chary }
16073e230dd2SCorentin Chary 
16083e230dd2SCorentin Chary static void pointer_event(VncState *vs, int button_mask, int x, int y)
16093e230dd2SCorentin Chary {
16107fb1cf16SEric Blake     static uint32_t bmap[INPUT_BUTTON__MAX] = {
161114768ebaSGerd Hoffmann         [INPUT_BUTTON_LEFT]       = 0x01,
161214768ebaSGerd Hoffmann         [INPUT_BUTTON_MIDDLE]     = 0x02,
161314768ebaSGerd Hoffmann         [INPUT_BUTTON_RIGHT]      = 0x04,
1614f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1615f22d0af0SGerd Hoffmann         [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
161614768ebaSGerd Hoffmann     };
161714768ebaSGerd Hoffmann     QemuConsole *con = vs->vd->dcl.con;
1618bea60dd7SPeter Lieven     int width = pixman_image_get_width(vs->vd->server);
1619bea60dd7SPeter Lieven     int height = pixman_image_get_height(vs->vd->server);
16203e230dd2SCorentin Chary 
162114768ebaSGerd Hoffmann     if (vs->last_bmask != button_mask) {
162214768ebaSGerd Hoffmann         qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
162314768ebaSGerd Hoffmann         vs->last_bmask = button_mask;
162414768ebaSGerd Hoffmann     }
16253e230dd2SCorentin Chary 
16263e230dd2SCorentin Chary     if (vs->absolute) {
162714768ebaSGerd Hoffmann         qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
162814768ebaSGerd Hoffmann         qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
16293e230dd2SCorentin Chary     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
163014768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
163114768ebaSGerd Hoffmann         qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
16323e230dd2SCorentin Chary     } else {
163314768ebaSGerd Hoffmann         if (vs->last_x != -1) {
163414768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
163514768ebaSGerd Hoffmann             qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
163614768ebaSGerd Hoffmann         }
16373e230dd2SCorentin Chary         vs->last_x = x;
16383e230dd2SCorentin Chary         vs->last_y = y;
16393e230dd2SCorentin Chary     }
164014768ebaSGerd Hoffmann     qemu_input_event_sync();
16413e230dd2SCorentin Chary }
16423e230dd2SCorentin Chary 
16433e230dd2SCorentin Chary static void reset_keys(VncState *vs)
16443e230dd2SCorentin Chary {
16453e230dd2SCorentin Chary     int i;
16463e230dd2SCorentin Chary     for(i = 0; i < 256; i++) {
16473e230dd2SCorentin Chary         if (vs->modifiers_state[i]) {
16488d447d10SGerd Hoffmann             qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
1649c5ce8333SGerd Hoffmann             qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
16503e230dd2SCorentin Chary             vs->modifiers_state[i] = 0;
16513e230dd2SCorentin Chary         }
16523e230dd2SCorentin Chary     }
16533e230dd2SCorentin Chary }
16543e230dd2SCorentin Chary 
16553e230dd2SCorentin Chary static void press_key(VncState *vs, int keysym)
16563e230dd2SCorentin Chary {
16573e230dd2SCorentin Chary     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
16588d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
1659c5ce8333SGerd Hoffmann     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
16608d447d10SGerd Hoffmann     qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1661c5ce8333SGerd Hoffmann     qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
16623e230dd2SCorentin Chary }
16633e230dd2SCorentin Chary 
1664ab99e5c1SLei Li static int current_led_state(VncState *vs)
1665ab99e5c1SLei Li {
1666ab99e5c1SLei Li     int ledstate = 0;
1667ab99e5c1SLei Li 
1668ab99e5c1SLei Li     if (vs->modifiers_state[0x46]) {
1669ab99e5c1SLei Li         ledstate |= QEMU_SCROLL_LOCK_LED;
1670ab99e5c1SLei Li     }
1671ab99e5c1SLei Li     if (vs->modifiers_state[0x45]) {
1672ab99e5c1SLei Li         ledstate |= QEMU_NUM_LOCK_LED;
1673ab99e5c1SLei Li     }
1674ab99e5c1SLei Li     if (vs->modifiers_state[0x3a]) {
1675ab99e5c1SLei Li         ledstate |= QEMU_CAPS_LOCK_LED;
1676ab99e5c1SLei Li     }
1677ab99e5c1SLei Li 
1678ab99e5c1SLei Li     return ledstate;
1679ab99e5c1SLei Li }
1680ab99e5c1SLei Li 
1681ab99e5c1SLei Li static void vnc_led_state_change(VncState *vs)
1682ab99e5c1SLei Li {
1683ab99e5c1SLei Li     int ledstate = 0;
1684ab99e5c1SLei Li 
1685ab99e5c1SLei Li     if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1686ab99e5c1SLei Li         return;
1687ab99e5c1SLei Li     }
1688ab99e5c1SLei Li 
1689ab99e5c1SLei Li     ledstate = current_led_state(vs);
1690ab99e5c1SLei Li     vnc_lock_output(vs);
1691ab99e5c1SLei Li     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1692ab99e5c1SLei Li     vnc_write_u8(vs, 0);
1693ab99e5c1SLei Li     vnc_write_u16(vs, 1);
1694ab99e5c1SLei Li     vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1695ab99e5c1SLei Li     vnc_write_u8(vs, ledstate);
1696ab99e5c1SLei Li     vnc_unlock_output(vs);
1697ab99e5c1SLei Li     vnc_flush(vs);
1698ab99e5c1SLei Li }
1699ab99e5c1SLei Li 
17003e230dd2SCorentin Chary static void kbd_leds(void *opaque, int ledstate)
17013e230dd2SCorentin Chary {
17023e230dd2SCorentin Chary     VncState *vs = opaque;
170396f3d174SLei Li     int caps, num, scr;
17041483adcfSLei Li     bool has_changed = (ledstate != current_led_state(vs));
17053e230dd2SCorentin Chary 
170640066175SGerd Hoffmann     trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
170740066175SGerd Hoffmann                              (ledstate & QEMU_NUM_LOCK_LED),
170840066175SGerd Hoffmann                              (ledstate & QEMU_SCROLL_LOCK_LED));
170940066175SGerd Hoffmann 
17103e230dd2SCorentin Chary     caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
17113e230dd2SCorentin Chary     num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
171296f3d174SLei Li     scr  = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
17133e230dd2SCorentin Chary 
17143e230dd2SCorentin Chary     if (vs->modifiers_state[0x3a] != caps) {
17153e230dd2SCorentin Chary         vs->modifiers_state[0x3a] = caps;
17163e230dd2SCorentin Chary     }
17173e230dd2SCorentin Chary     if (vs->modifiers_state[0x45] != num) {
17183e230dd2SCorentin Chary         vs->modifiers_state[0x45] = num;
17193e230dd2SCorentin Chary     }
172096f3d174SLei Li     if (vs->modifiers_state[0x46] != scr) {
172196f3d174SLei Li         vs->modifiers_state[0x46] = scr;
172296f3d174SLei Li     }
1723ab99e5c1SLei Li 
1724ab99e5c1SLei Li     /* Sending the current led state message to the client */
17251483adcfSLei Li     if (has_changed) {
1726ab99e5c1SLei Li         vnc_led_state_change(vs);
1727ab99e5c1SLei Li     }
17283e230dd2SCorentin Chary }
17293e230dd2SCorentin Chary 
17303e230dd2SCorentin Chary static void do_key_event(VncState *vs, int down, int keycode, int sym)
17313e230dd2SCorentin Chary {
17323e230dd2SCorentin Chary     /* QEMU console switch */
17333e230dd2SCorentin Chary     switch(keycode) {
17343e230dd2SCorentin Chary     case 0x2a:                          /* Left Shift */
17353e230dd2SCorentin Chary     case 0x36:                          /* Right Shift */
17363e230dd2SCorentin Chary     case 0x1d:                          /* Left CTRL */
17373e230dd2SCorentin Chary     case 0x9d:                          /* Right CTRL */
17383e230dd2SCorentin Chary     case 0x38:                          /* Left ALT */
17393e230dd2SCorentin Chary     case 0xb8:                          /* Right ALT */
17403e230dd2SCorentin Chary         if (down)
17413e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 1;
17423e230dd2SCorentin Chary         else
17433e230dd2SCorentin Chary             vs->modifiers_state[keycode] = 0;
17443e230dd2SCorentin Chary         break;
17453e230dd2SCorentin Chary     case 0x02 ... 0x0a: /* '1' to '9' keys */
17461d0d59feSGerd Hoffmann         if (vs->vd->dcl.con == NULL &&
17471d0d59feSGerd Hoffmann             down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
17483e230dd2SCorentin Chary             /* Reset the modifiers sent to the current console */
17493e230dd2SCorentin Chary             reset_keys(vs);
17503e230dd2SCorentin Chary             console_select(keycode - 0x02);
17513e230dd2SCorentin Chary             return;
17523e230dd2SCorentin Chary         }
17533e230dd2SCorentin Chary         break;
17543e230dd2SCorentin Chary     case 0x3a:                        /* CapsLock */
17553e230dd2SCorentin Chary     case 0x45:                        /* NumLock */
17563e230dd2SCorentin Chary         if (down)
17573e230dd2SCorentin Chary             vs->modifiers_state[keycode] ^= 1;
17583e230dd2SCorentin Chary         break;
17593e230dd2SCorentin Chary     }
17603e230dd2SCorentin Chary 
1761e7b2aaccSLei Li     /* Turn off the lock state sync logic if the client support the led
1762e7b2aaccSLei Li        state extension.
1763e7b2aaccSLei Li     */
17649892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1765e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
17663e230dd2SCorentin Chary         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
17673e230dd2SCorentin Chary         /* If the numlock state needs to change then simulate an additional
17683e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
17693e230dd2SCorentin Chary            toggles numlock away from the VNC window.
17703e230dd2SCorentin Chary         */
17713e230dd2SCorentin Chary         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
17723e230dd2SCorentin Chary             if (!vs->modifiers_state[0x45]) {
177340066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(true);
17743e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 1;
17753e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
17763e230dd2SCorentin Chary             }
17773e230dd2SCorentin Chary         } else {
17783e230dd2SCorentin Chary             if (vs->modifiers_state[0x45]) {
177940066175SGerd Hoffmann                 trace_vnc_key_sync_numlock(false);
17803e230dd2SCorentin Chary                 vs->modifiers_state[0x45] = 0;
17813e230dd2SCorentin Chary                 press_key(vs, 0xff7f);
17823e230dd2SCorentin Chary             }
17833e230dd2SCorentin Chary         }
17843e230dd2SCorentin Chary     }
17853e230dd2SCorentin Chary 
17869892088bSGerd Hoffmann     if (down && vs->vd->lock_key_sync &&
1787e7b2aaccSLei Li         !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
17883e230dd2SCorentin Chary         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
17893e230dd2SCorentin Chary         /* If the capslock state needs to change then simulate an additional
17903e230dd2SCorentin Chary            keypress before sending this one.  This will happen if the user
17913e230dd2SCorentin Chary            toggles capslock away from the VNC window.
17923e230dd2SCorentin Chary         */
17933e230dd2SCorentin Chary         int uppercase = !!(sym >= 'A' && sym <= 'Z');
17943e230dd2SCorentin Chary         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
17953e230dd2SCorentin Chary         int capslock = !!(vs->modifiers_state[0x3a]);
17963e230dd2SCorentin Chary         if (capslock) {
17973e230dd2SCorentin Chary             if (uppercase == shift) {
179840066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(false);
17993e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 0;
18003e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18013e230dd2SCorentin Chary             }
18023e230dd2SCorentin Chary         } else {
18033e230dd2SCorentin Chary             if (uppercase != shift) {
180440066175SGerd Hoffmann                 trace_vnc_key_sync_capslock(true);
18053e230dd2SCorentin Chary                 vs->modifiers_state[0x3a] = 1;
18063e230dd2SCorentin Chary                 press_key(vs, 0xffe5);
18073e230dd2SCorentin Chary             }
18083e230dd2SCorentin Chary         }
18093e230dd2SCorentin Chary     }
18103e230dd2SCorentin Chary 
181181c0d5a6SGerd Hoffmann     if (qemu_console_is_graphic(NULL)) {
18128d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
1813c5ce8333SGerd Hoffmann         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
18143e230dd2SCorentin Chary     } else {
1815e26437c2SGerd Hoffmann         bool numlock = vs->modifiers_state[0x45];
1816e26437c2SGerd Hoffmann         bool control = (vs->modifiers_state[0x1d] ||
1817e26437c2SGerd Hoffmann                         vs->modifiers_state[0x9d]);
18183e230dd2SCorentin Chary         /* QEMU console emulation */
18193e230dd2SCorentin Chary         if (down) {
18203e230dd2SCorentin Chary             switch (keycode) {
18213e230dd2SCorentin Chary             case 0x2a:                          /* Left Shift */
18223e230dd2SCorentin Chary             case 0x36:                          /* Right Shift */
18233e230dd2SCorentin Chary             case 0x1d:                          /* Left CTRL */
18243e230dd2SCorentin Chary             case 0x9d:                          /* Right CTRL */
18253e230dd2SCorentin Chary             case 0x38:                          /* Left ALT */
18263e230dd2SCorentin Chary             case 0xb8:                          /* Right ALT */
18273e230dd2SCorentin Chary                 break;
18283e230dd2SCorentin Chary             case 0xc8:
18293e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_UP);
18303e230dd2SCorentin Chary                 break;
18313e230dd2SCorentin Chary             case 0xd0:
18323e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DOWN);
18333e230dd2SCorentin Chary                 break;
18343e230dd2SCorentin Chary             case 0xcb:
18353e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_LEFT);
18363e230dd2SCorentin Chary                 break;
18373e230dd2SCorentin Chary             case 0xcd:
18383e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_RIGHT);
18393e230dd2SCorentin Chary                 break;
18403e230dd2SCorentin Chary             case 0xd3:
18413e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_DELETE);
18423e230dd2SCorentin Chary                 break;
18433e230dd2SCorentin Chary             case 0xc7:
18443e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_HOME);
18453e230dd2SCorentin Chary                 break;
18463e230dd2SCorentin Chary             case 0xcf:
18473e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_END);
18483e230dd2SCorentin Chary                 break;
18493e230dd2SCorentin Chary             case 0xc9:
18503e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEUP);
18513e230dd2SCorentin Chary                 break;
18523e230dd2SCorentin Chary             case 0xd1:
18533e230dd2SCorentin Chary                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
18543e230dd2SCorentin Chary                 break;
18553e230dd2SCorentin Chary 
18563e230dd2SCorentin Chary             case 0x47:
18573e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
18583e230dd2SCorentin Chary                 break;
18593e230dd2SCorentin Chary             case 0x48:
18603e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
18613e230dd2SCorentin Chary                 break;
18623e230dd2SCorentin Chary             case 0x49:
18633e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
18643e230dd2SCorentin Chary                 break;
18653e230dd2SCorentin Chary             case 0x4b:
18663e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
18673e230dd2SCorentin Chary                 break;
18683e230dd2SCorentin Chary             case 0x4c:
18693e230dd2SCorentin Chary                 kbd_put_keysym('5');
18703e230dd2SCorentin Chary                 break;
18713e230dd2SCorentin Chary             case 0x4d:
18723e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
18733e230dd2SCorentin Chary                 break;
18743e230dd2SCorentin Chary             case 0x4f:
18753e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
18763e230dd2SCorentin Chary                 break;
18773e230dd2SCorentin Chary             case 0x50:
18783e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
18793e230dd2SCorentin Chary                 break;
18803e230dd2SCorentin Chary             case 0x51:
18813e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
18823e230dd2SCorentin Chary                 break;
18833e230dd2SCorentin Chary             case 0x52:
18843e230dd2SCorentin Chary                 kbd_put_keysym('0');
18853e230dd2SCorentin Chary                 break;
18863e230dd2SCorentin Chary             case 0x53:
18873e230dd2SCorentin Chary                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
18883e230dd2SCorentin Chary                 break;
18893e230dd2SCorentin Chary 
18903e230dd2SCorentin Chary             case 0xb5:
18913e230dd2SCorentin Chary                 kbd_put_keysym('/');
18923e230dd2SCorentin Chary                 break;
18933e230dd2SCorentin Chary             case 0x37:
18943e230dd2SCorentin Chary                 kbd_put_keysym('*');
18953e230dd2SCorentin Chary                 break;
18963e230dd2SCorentin Chary             case 0x4a:
18973e230dd2SCorentin Chary                 kbd_put_keysym('-');
18983e230dd2SCorentin Chary                 break;
18993e230dd2SCorentin Chary             case 0x4e:
19003e230dd2SCorentin Chary                 kbd_put_keysym('+');
19013e230dd2SCorentin Chary                 break;
19023e230dd2SCorentin Chary             case 0x9c:
19033e230dd2SCorentin Chary                 kbd_put_keysym('\n');
19043e230dd2SCorentin Chary                 break;
19053e230dd2SCorentin Chary 
19063e230dd2SCorentin Chary             default:
1907e26437c2SGerd Hoffmann                 if (control) {
1908e26437c2SGerd Hoffmann                     kbd_put_keysym(sym & 0x1f);
1909e26437c2SGerd Hoffmann                 } else {
19103e230dd2SCorentin Chary                     kbd_put_keysym(sym);
1911e26437c2SGerd Hoffmann                 }
19123e230dd2SCorentin Chary                 break;
19133e230dd2SCorentin Chary             }
19143e230dd2SCorentin Chary         }
19153e230dd2SCorentin Chary     }
19163e230dd2SCorentin Chary }
19173e230dd2SCorentin Chary 
19187bc9318bSGerd Hoffmann static void vnc_release_modifiers(VncState *vs)
19197bc9318bSGerd Hoffmann {
19207bc9318bSGerd Hoffmann     static const int keycodes[] = {
19217bc9318bSGerd Hoffmann         /* shift, control, alt keys, both left & right */
19227bc9318bSGerd Hoffmann         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
19237bc9318bSGerd Hoffmann     };
19247bc9318bSGerd Hoffmann     int i, keycode;
19257bc9318bSGerd Hoffmann 
192681c0d5a6SGerd Hoffmann     if (!qemu_console_is_graphic(NULL)) {
19277bc9318bSGerd Hoffmann         return;
19287bc9318bSGerd Hoffmann     }
19297bc9318bSGerd Hoffmann     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
19307bc9318bSGerd Hoffmann         keycode = keycodes[i];
19317bc9318bSGerd Hoffmann         if (!vs->modifiers_state[keycode]) {
19327bc9318bSGerd Hoffmann             continue;
19337bc9318bSGerd Hoffmann         }
19348d447d10SGerd Hoffmann         qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
1935c5ce8333SGerd Hoffmann         qemu_input_event_send_key_delay(vs->vd->key_delay_ms);
19367bc9318bSGerd Hoffmann     }
19377bc9318bSGerd Hoffmann }
19387bc9318bSGerd Hoffmann 
193940066175SGerd Hoffmann static const char *code2name(int keycode)
194040066175SGerd Hoffmann {
194140066175SGerd Hoffmann     return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
194240066175SGerd Hoffmann }
194340066175SGerd Hoffmann 
19443e230dd2SCorentin Chary static void key_event(VncState *vs, int down, uint32_t sym)
19453e230dd2SCorentin Chary {
19463e230dd2SCorentin Chary     int keycode;
19473e230dd2SCorentin Chary     int lsym = sym;
19483e230dd2SCorentin Chary 
194981c0d5a6SGerd Hoffmann     if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
19503e230dd2SCorentin Chary         lsym = lsym - 'A' + 'a';
19513e230dd2SCorentin Chary     }
19523e230dd2SCorentin Chary 
19533e230dd2SCorentin Chary     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
195440066175SGerd Hoffmann     trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
19553e230dd2SCorentin Chary     do_key_event(vs, down, keycode, sym);
19563e230dd2SCorentin Chary }
19573e230dd2SCorentin Chary 
19583e230dd2SCorentin Chary static void ext_key_event(VncState *vs, int down,
19593e230dd2SCorentin Chary                           uint32_t sym, uint16_t keycode)
19603e230dd2SCorentin Chary {
19613e230dd2SCorentin Chary     /* if the user specifies a keyboard layout, always use it */
196240066175SGerd Hoffmann     if (keyboard_layout) {
19633e230dd2SCorentin Chary         key_event(vs, down, sym);
196440066175SGerd Hoffmann     } else {
196540066175SGerd Hoffmann         trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
19663e230dd2SCorentin Chary         do_key_event(vs, down, keycode, sym);
19673e230dd2SCorentin Chary     }
196840066175SGerd Hoffmann }
19693e230dd2SCorentin Chary 
19703e230dd2SCorentin Chary static void framebuffer_update_request(VncState *vs, int incremental,
1971bea60dd7SPeter Lieven                                        int x, int y, int w, int h)
19723e230dd2SCorentin Chary {
19733e230dd2SCorentin Chary     vs->need_update = 1;
1974bea60dd7SPeter Lieven 
1975bea60dd7SPeter Lieven     if (incremental) {
1976bea60dd7SPeter Lieven         return;
19773e230dd2SCorentin Chary     }
1978bea60dd7SPeter Lieven 
197907535a89SStephan Kulow     vs->force_update = 1;
1980f7b3d68cSGerd Hoffmann     vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
19813e230dd2SCorentin Chary }
19823e230dd2SCorentin Chary 
19833e230dd2SCorentin Chary static void send_ext_key_event_ack(VncState *vs)
19843e230dd2SCorentin Chary {
1985bd023f95SCorentin Chary     vnc_lock_output(vs);
19863e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
19873e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
19883e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
1989d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
1990bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
1991bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
19923e230dd2SCorentin Chary                            VNC_ENCODING_EXT_KEY_EVENT);
1993bd023f95SCorentin Chary     vnc_unlock_output(vs);
19943e230dd2SCorentin Chary     vnc_flush(vs);
19953e230dd2SCorentin Chary }
19963e230dd2SCorentin Chary 
19973e230dd2SCorentin Chary static void send_ext_audio_ack(VncState *vs)
19983e230dd2SCorentin Chary {
1999bd023f95SCorentin Chary     vnc_lock_output(vs);
20003e230dd2SCorentin Chary     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
20013e230dd2SCorentin Chary     vnc_write_u8(vs, 0);
20023e230dd2SCorentin Chary     vnc_write_u16(vs, 1);
2003d39fa6d8SGerd Hoffmann     vnc_framebuffer_update(vs, 0, 0,
2004bea60dd7SPeter Lieven                            pixman_image_get_width(vs->vd->server),
2005bea60dd7SPeter Lieven                            pixman_image_get_height(vs->vd->server),
20063e230dd2SCorentin Chary                            VNC_ENCODING_AUDIO);
2007bd023f95SCorentin Chary     vnc_unlock_output(vs);
20083e230dd2SCorentin Chary     vnc_flush(vs);
20093e230dd2SCorentin Chary }
20103e230dd2SCorentin Chary 
20113e230dd2SCorentin Chary static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
20123e230dd2SCorentin Chary {
20133e230dd2SCorentin Chary     int i;
20143e230dd2SCorentin Chary     unsigned int enc = 0;
20153e230dd2SCorentin Chary 
20163e230dd2SCorentin Chary     vs->features = 0;
20173e230dd2SCorentin Chary     vs->vnc_encoding = 0;
2018d1af0e05SCorentin Chary     vs->tight.compression = 9;
2019d1af0e05SCorentin Chary     vs->tight.quality = -1; /* Lossless by default */
20203e230dd2SCorentin Chary     vs->absolute = -1;
20213e230dd2SCorentin Chary 
20223e230dd2SCorentin Chary     /*
20233e230dd2SCorentin Chary      * Start from the end because the encodings are sent in order of preference.
2024e5bed759SDong Xu Wang      * This way the preferred encoding (first encoding defined in the array)
20253e230dd2SCorentin Chary      * will be set at the end of the loop.
20263e230dd2SCorentin Chary      */
20273e230dd2SCorentin Chary     for (i = n_encodings - 1; i >= 0; i--) {
20283e230dd2SCorentin Chary         enc = encodings[i];
20293e230dd2SCorentin Chary         switch (enc) {
20303e230dd2SCorentin Chary         case VNC_ENCODING_RAW:
20313e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20323e230dd2SCorentin Chary             break;
20333e230dd2SCorentin Chary         case VNC_ENCODING_COPYRECT:
20343e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_COPYRECT_MASK;
20353e230dd2SCorentin Chary             break;
20363e230dd2SCorentin Chary         case VNC_ENCODING_HEXTILE:
20373e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_HEXTILE_MASK;
20383e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20393e230dd2SCorentin Chary             break;
20403e230dd2SCorentin Chary         case VNC_ENCODING_TIGHT:
20413e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_MASK;
20423e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20433e230dd2SCorentin Chary             break;
2044fe3e7f2dSJoel Martin #ifdef CONFIG_VNC_PNG
2045efe556adSCorentin Chary         case VNC_ENCODING_TIGHT_PNG:
2046efe556adSCorentin Chary             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2047efe556adSCorentin Chary             vs->vnc_encoding = enc;
2048efe556adSCorentin Chary             break;
2049fe3e7f2dSJoel Martin #endif
20503e230dd2SCorentin Chary         case VNC_ENCODING_ZLIB:
20513e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_ZLIB_MASK;
20523e230dd2SCorentin Chary             vs->vnc_encoding = enc;
20533e230dd2SCorentin Chary             break;
2054148954faSCorentin Chary         case VNC_ENCODING_ZRLE:
2055148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZRLE_MASK;
2056148954faSCorentin Chary             vs->vnc_encoding = enc;
2057148954faSCorentin Chary             break;
2058148954faSCorentin Chary         case VNC_ENCODING_ZYWRLE:
2059148954faSCorentin Chary             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2060148954faSCorentin Chary             vs->vnc_encoding = enc;
2061148954faSCorentin Chary             break;
20623e230dd2SCorentin Chary         case VNC_ENCODING_DESKTOPRESIZE:
20633e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RESIZE_MASK;
20643e230dd2SCorentin Chary             break;
20653e230dd2SCorentin Chary         case VNC_ENCODING_POINTER_TYPE_CHANGE:
20663e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
20673e230dd2SCorentin Chary             break;
20683e230dd2SCorentin Chary         case VNC_ENCODING_RICH_CURSOR:
20693e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
207091ec41dcSFrediano Ziglio             if (vs->vd->cursor) {
207191ec41dcSFrediano Ziglio                 vnc_cursor_define(vs);
207291ec41dcSFrediano Ziglio             }
20733e230dd2SCorentin Chary             break;
20743e230dd2SCorentin Chary         case VNC_ENCODING_EXT_KEY_EVENT:
20753e230dd2SCorentin Chary             send_ext_key_event_ack(vs);
20763e230dd2SCorentin Chary             break;
20773e230dd2SCorentin Chary         case VNC_ENCODING_AUDIO:
20783e230dd2SCorentin Chary             send_ext_audio_ack(vs);
20793e230dd2SCorentin Chary             break;
20803e230dd2SCorentin Chary         case VNC_ENCODING_WMVi:
20813e230dd2SCorentin Chary             vs->features |= VNC_FEATURE_WMVI_MASK;
20823e230dd2SCorentin Chary             break;
2083ab99e5c1SLei Li         case VNC_ENCODING_LED_STATE:
2084ab99e5c1SLei Li             vs->features |= VNC_FEATURE_LED_STATE_MASK;
2085ab99e5c1SLei Li             break;
20863e230dd2SCorentin Chary         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2087d1af0e05SCorentin Chary             vs->tight.compression = (enc & 0x0F);
20883e230dd2SCorentin Chary             break;
20893e230dd2SCorentin Chary         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2090b31f519eSCorentin Chary             if (vs->vd->lossy) {
2091d1af0e05SCorentin Chary                 vs->tight.quality = (enc & 0x0F);
2092b31f519eSCorentin Chary             }
20933e230dd2SCorentin Chary             break;
20943e230dd2SCorentin Chary         default:
20953e230dd2SCorentin Chary             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
20963e230dd2SCorentin Chary             break;
20973e230dd2SCorentin Chary         }
20983e230dd2SCorentin Chary     }
20993e230dd2SCorentin Chary     vnc_desktop_resize(vs);
21009e8dd451SJan Kiszka     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2101ab99e5c1SLei Li     vnc_led_state_change(vs);
21023e230dd2SCorentin Chary }
21033e230dd2SCorentin Chary 
21043e230dd2SCorentin Chary static void set_pixel_conversion(VncState *vs)
21053e230dd2SCorentin Chary {
21069f64916dSGerd Hoffmann     pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
21079f64916dSGerd Hoffmann 
21089f64916dSGerd Hoffmann     if (fmt == VNC_SERVER_FB_FORMAT) {
21093e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_copy;
21103e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 0);
21113e230dd2SCorentin Chary     } else {
21123e230dd2SCorentin Chary         vs->write_pixels = vnc_write_pixels_generic;
21133e230dd2SCorentin Chary         vnc_hextile_set_pixel_conversion(vs, 1);
21143e230dd2SCorentin Chary     }
21153e230dd2SCorentin Chary }
21163e230dd2SCorentin Chary 
21170c426e45SAlexander Graf static void send_color_map(VncState *vs)
21180c426e45SAlexander Graf {
21190c426e45SAlexander Graf     int i;
21200c426e45SAlexander Graf 
21210c426e45SAlexander Graf     vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
21220c426e45SAlexander Graf     vnc_write_u8(vs,  0);    /* padding     */
21230c426e45SAlexander Graf     vnc_write_u16(vs, 0);    /* first color */
21240c426e45SAlexander Graf     vnc_write_u16(vs, 256);  /* # of colors */
21250c426e45SAlexander Graf 
21260c426e45SAlexander Graf     for (i = 0; i < 256; i++) {
21270c426e45SAlexander Graf         PixelFormat *pf = &vs->client_pf;
21280c426e45SAlexander Graf 
21290c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
21300c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
21310c426e45SAlexander Graf         vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
21320c426e45SAlexander Graf     }
21330c426e45SAlexander Graf }
21340c426e45SAlexander Graf 
2135ec9fb41aSGerd Hoffmann static void set_pixel_format(VncState *vs, int bits_per_pixel,
21363e230dd2SCorentin Chary                              int big_endian_flag, int true_color_flag,
21373e230dd2SCorentin Chary                              int red_max, int green_max, int blue_max,
21383e230dd2SCorentin Chary                              int red_shift, int green_shift, int blue_shift)
21393e230dd2SCorentin Chary {
21403e230dd2SCorentin Chary     if (!true_color_flag) {
21410c426e45SAlexander Graf         /* Expose a reasonable default 256 color map */
21420c426e45SAlexander Graf         bits_per_pixel = 8;
21430c426e45SAlexander Graf         red_max = 7;
21440c426e45SAlexander Graf         green_max = 7;
21450c426e45SAlexander Graf         blue_max = 3;
21460c426e45SAlexander Graf         red_shift = 0;
21470c426e45SAlexander Graf         green_shift = 3;
21480c426e45SAlexander Graf         blue_shift = 6;
21493e230dd2SCorentin Chary     }
21503e230dd2SCorentin Chary 
2151e6908bfeSPetr Matousek     switch (bits_per_pixel) {
2152e6908bfeSPetr Matousek     case 8:
2153e6908bfeSPetr Matousek     case 16:
2154e6908bfeSPetr Matousek     case 32:
2155e6908bfeSPetr Matousek         break;
2156e6908bfeSPetr Matousek     default:
2157e6908bfeSPetr Matousek         vnc_client_error(vs);
2158e6908bfeSPetr Matousek         return;
2159e6908bfeSPetr Matousek     }
2160e6908bfeSPetr Matousek 
21614c65fed8SPrasad J Pandit     vs->client_pf.rmax = red_max ? red_max : 0xFF;
21629f64916dSGerd Hoffmann     vs->client_pf.rbits = hweight_long(red_max);
21639f64916dSGerd Hoffmann     vs->client_pf.rshift = red_shift;
21649f64916dSGerd Hoffmann     vs->client_pf.rmask = red_max << red_shift;
21654c65fed8SPrasad J Pandit     vs->client_pf.gmax = green_max ? green_max : 0xFF;
21669f64916dSGerd Hoffmann     vs->client_pf.gbits = hweight_long(green_max);
21679f64916dSGerd Hoffmann     vs->client_pf.gshift = green_shift;
21689f64916dSGerd Hoffmann     vs->client_pf.gmask = green_max << green_shift;
21694c65fed8SPrasad J Pandit     vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
21709f64916dSGerd Hoffmann     vs->client_pf.bbits = hweight_long(blue_max);
21719f64916dSGerd Hoffmann     vs->client_pf.bshift = blue_shift;
21729f64916dSGerd Hoffmann     vs->client_pf.bmask = blue_max << blue_shift;
21739f64916dSGerd Hoffmann     vs->client_pf.bits_per_pixel = bits_per_pixel;
21749f64916dSGerd Hoffmann     vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
21759f64916dSGerd Hoffmann     vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
21769f64916dSGerd Hoffmann     vs->client_be = big_endian_flag;
21773e230dd2SCorentin Chary 
21780c426e45SAlexander Graf     if (!true_color_flag) {
21790c426e45SAlexander Graf         send_color_map(vs);
21800c426e45SAlexander Graf     }
21810c426e45SAlexander Graf 
21823e230dd2SCorentin Chary     set_pixel_conversion(vs);
21833e230dd2SCorentin Chary 
21841d0d59feSGerd Hoffmann     graphic_hw_invalidate(vs->vd->dcl.con);
21851d0d59feSGerd Hoffmann     graphic_hw_update(vs->vd->dcl.con);
21863e230dd2SCorentin Chary }
21873e230dd2SCorentin Chary 
21883e230dd2SCorentin Chary static void pixel_format_message (VncState *vs) {
21893e230dd2SCorentin Chary     char pad[3] = { 0, 0, 0 };
21903e230dd2SCorentin Chary 
21919f64916dSGerd Hoffmann     vs->client_pf = qemu_default_pixelformat(32);
21929f64916dSGerd Hoffmann 
21939f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
21949f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.depth); /* depth */
21953e230dd2SCorentin Chary 
21963e230dd2SCorentin Chary #ifdef HOST_WORDS_BIGENDIAN
21973e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* big-endian-flag */
21983e230dd2SCorentin Chary #else
21993e230dd2SCorentin Chary     vnc_write_u8(vs, 0);             /* big-endian-flag */
22003e230dd2SCorentin Chary #endif
22013e230dd2SCorentin Chary     vnc_write_u8(vs, 1);             /* true-color-flag */
22029f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
22039f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
22049f64916dSGerd Hoffmann     vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
22059f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
22069f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
22079f64916dSGerd Hoffmann     vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
22089f64916dSGerd Hoffmann     vnc_write(vs, pad, 3);           /* padding */
22093e230dd2SCorentin Chary 
22103e230dd2SCorentin Chary     vnc_hextile_set_pixel_conversion(vs, 0);
22113e230dd2SCorentin Chary     vs->write_pixels = vnc_write_pixels_copy;
22123e230dd2SCorentin Chary }
22133e230dd2SCorentin Chary 
22143e230dd2SCorentin Chary static void vnc_colordepth(VncState *vs)
22153e230dd2SCorentin Chary {
22163e230dd2SCorentin Chary     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
22173e230dd2SCorentin Chary         /* Sending a WMVi message to notify the client*/
2218bd023f95SCorentin Chary         vnc_lock_output(vs);
22193e230dd2SCorentin Chary         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
22203e230dd2SCorentin Chary         vnc_write_u8(vs, 0);
22213e230dd2SCorentin Chary         vnc_write_u16(vs, 1); /* number of rects */
2222d39fa6d8SGerd Hoffmann         vnc_framebuffer_update(vs, 0, 0,
2223bea60dd7SPeter Lieven                                pixman_image_get_width(vs->vd->server),
2224bea60dd7SPeter Lieven                                pixman_image_get_height(vs->vd->server),
2225d39fa6d8SGerd Hoffmann                                VNC_ENCODING_WMVi);
22263e230dd2SCorentin Chary         pixel_format_message(vs);
2227bd023f95SCorentin Chary         vnc_unlock_output(vs);
22283e230dd2SCorentin Chary         vnc_flush(vs);
22293e230dd2SCorentin Chary     } else {
22303e230dd2SCorentin Chary         set_pixel_conversion(vs);
22313e230dd2SCorentin Chary     }
22323e230dd2SCorentin Chary }
22333e230dd2SCorentin Chary 
22343e230dd2SCorentin Chary static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
22353e230dd2SCorentin Chary {
22363e230dd2SCorentin Chary     int i;
22373e230dd2SCorentin Chary     uint16_t limit;
22383e230dd2SCorentin Chary     VncDisplay *vd = vs->vd;
22393e230dd2SCorentin Chary 
22403e230dd2SCorentin Chary     if (data[0] > 3) {
22410f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
22423e230dd2SCorentin Chary     }
22433e230dd2SCorentin Chary 
22443e230dd2SCorentin Chary     switch (data[0]) {
22453e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
22463e230dd2SCorentin Chary         if (len == 1)
22473e230dd2SCorentin Chary             return 20;
22483e230dd2SCorentin Chary 
2249ec9fb41aSGerd Hoffmann         set_pixel_format(vs, read_u8(data, 4),
22503e230dd2SCorentin Chary                          read_u8(data, 6), read_u8(data, 7),
22513e230dd2SCorentin Chary                          read_u16(data, 8), read_u16(data, 10),
22523e230dd2SCorentin Chary                          read_u16(data, 12), read_u8(data, 14),
22533e230dd2SCorentin Chary                          read_u8(data, 15), read_u8(data, 16));
22543e230dd2SCorentin Chary         break;
22553e230dd2SCorentin Chary     case VNC_MSG_CLIENT_SET_ENCODINGS:
22563e230dd2SCorentin Chary         if (len == 1)
22573e230dd2SCorentin Chary             return 4;
22583e230dd2SCorentin Chary 
22593e230dd2SCorentin Chary         if (len == 4) {
22603e230dd2SCorentin Chary             limit = read_u16(data, 2);
22613e230dd2SCorentin Chary             if (limit > 0)
22623e230dd2SCorentin Chary                 return 4 + (limit * 4);
22633e230dd2SCorentin Chary         } else
22643e230dd2SCorentin Chary             limit = read_u16(data, 2);
22653e230dd2SCorentin Chary 
22663e230dd2SCorentin Chary         for (i = 0; i < limit; i++) {
22673e230dd2SCorentin Chary             int32_t val = read_s32(data, 4 + (i * 4));
22683e230dd2SCorentin Chary             memcpy(data + 4 + (i * 4), &val, sizeof(val));
22693e230dd2SCorentin Chary         }
22703e230dd2SCorentin Chary 
22713e230dd2SCorentin Chary         set_encodings(vs, (int32_t *)(data + 4), limit);
22723e230dd2SCorentin Chary         break;
22733e230dd2SCorentin Chary     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
22743e230dd2SCorentin Chary         if (len == 1)
22753e230dd2SCorentin Chary             return 10;
22763e230dd2SCorentin Chary 
22773e230dd2SCorentin Chary         framebuffer_update_request(vs,
22783e230dd2SCorentin Chary                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
22793e230dd2SCorentin Chary                                    read_u16(data, 6), read_u16(data, 8));
22803e230dd2SCorentin Chary         break;
22813e230dd2SCorentin Chary     case VNC_MSG_CLIENT_KEY_EVENT:
22823e230dd2SCorentin Chary         if (len == 1)
22833e230dd2SCorentin Chary             return 8;
22843e230dd2SCorentin Chary 
22853e230dd2SCorentin Chary         key_event(vs, read_u8(data, 1), read_u32(data, 4));
22863e230dd2SCorentin Chary         break;
22873e230dd2SCorentin Chary     case VNC_MSG_CLIENT_POINTER_EVENT:
22883e230dd2SCorentin Chary         if (len == 1)
22893e230dd2SCorentin Chary             return 6;
22903e230dd2SCorentin Chary 
22913e230dd2SCorentin Chary         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
22923e230dd2SCorentin Chary         break;
22933e230dd2SCorentin Chary     case VNC_MSG_CLIENT_CUT_TEXT:
2294f9a70e79SPeter Lieven         if (len == 1) {
22953e230dd2SCorentin Chary             return 8;
2296f9a70e79SPeter Lieven         }
22973e230dd2SCorentin Chary         if (len == 8) {
22983e230dd2SCorentin Chary             uint32_t dlen = read_u32(data, 4);
2299f9a70e79SPeter Lieven             if (dlen > (1 << 20)) {
2300f9a70e79SPeter Lieven                 error_report("vnc: client_cut_text msg payload has %u bytes"
2301f9a70e79SPeter Lieven                              " which exceeds our limit of 1MB.", dlen);
2302f9a70e79SPeter Lieven                 vnc_client_error(vs);
2303f9a70e79SPeter Lieven                 break;
2304f9a70e79SPeter Lieven             }
2305f9a70e79SPeter Lieven             if (dlen > 0) {
23063e230dd2SCorentin Chary                 return 8 + dlen;
23073e230dd2SCorentin Chary             }
2308f9a70e79SPeter Lieven         }
23093e230dd2SCorentin Chary 
23103e230dd2SCorentin Chary         client_cut_text(vs, read_u32(data, 4), data + 8);
23113e230dd2SCorentin Chary         break;
23123e230dd2SCorentin Chary     case VNC_MSG_CLIENT_QEMU:
23133e230dd2SCorentin Chary         if (len == 1)
23143e230dd2SCorentin Chary             return 2;
23153e230dd2SCorentin Chary 
23163e230dd2SCorentin Chary         switch (read_u8(data, 1)) {
23173e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
23183e230dd2SCorentin Chary             if (len == 2)
23193e230dd2SCorentin Chary                 return 12;
23203e230dd2SCorentin Chary 
23213e230dd2SCorentin Chary             ext_key_event(vs, read_u16(data, 2),
23223e230dd2SCorentin Chary                           read_u32(data, 4), read_u32(data, 8));
23233e230dd2SCorentin Chary             break;
23243e230dd2SCorentin Chary         case VNC_MSG_CLIENT_QEMU_AUDIO:
23253e230dd2SCorentin Chary             if (len == 2)
23263e230dd2SCorentin Chary                 return 4;
23273e230dd2SCorentin Chary 
23283e230dd2SCorentin Chary             switch (read_u16 (data, 2)) {
23293e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
23303e230dd2SCorentin Chary                 audio_add(vs);
23313e230dd2SCorentin Chary                 break;
23323e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
23333e230dd2SCorentin Chary                 audio_del(vs);
23343e230dd2SCorentin Chary                 break;
23353e230dd2SCorentin Chary             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
23363e230dd2SCorentin Chary                 if (len == 4)
23373e230dd2SCorentin Chary                     return 10;
23383e230dd2SCorentin Chary                 switch (read_u8(data, 4)) {
23393e230dd2SCorentin Chary                 case 0: vs->as.fmt = AUD_FMT_U8; break;
23403e230dd2SCorentin Chary                 case 1: vs->as.fmt = AUD_FMT_S8; break;
23413e230dd2SCorentin Chary                 case 2: vs->as.fmt = AUD_FMT_U16; break;
23423e230dd2SCorentin Chary                 case 3: vs->as.fmt = AUD_FMT_S16; break;
23433e230dd2SCorentin Chary                 case 4: vs->as.fmt = AUD_FMT_U32; break;
23443e230dd2SCorentin Chary                 case 5: vs->as.fmt = AUD_FMT_S32; break;
23453e230dd2SCorentin Chary                 default:
2346153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
23473e230dd2SCorentin Chary                     vnc_client_error(vs);
23483e230dd2SCorentin Chary                     break;
23493e230dd2SCorentin Chary                 }
23503e230dd2SCorentin Chary                 vs->as.nchannels = read_u8(data, 5);
23513e230dd2SCorentin Chary                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2352153130cdSDaniel P. Berrange                     VNC_DEBUG("Invalid audio channel coount %d\n",
23533e230dd2SCorentin Chary                               read_u8(data, 5));
23543e230dd2SCorentin Chary                     vnc_client_error(vs);
23553e230dd2SCorentin Chary                     break;
23563e230dd2SCorentin Chary                 }
23573e230dd2SCorentin Chary                 vs->as.freq = read_u32(data, 6);
23583e230dd2SCorentin Chary                 break;
23593e230dd2SCorentin Chary             default:
2360153130cdSDaniel P. Berrange                 VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
23613e230dd2SCorentin Chary                 vnc_client_error(vs);
23623e230dd2SCorentin Chary                 break;
23633e230dd2SCorentin Chary             }
23643e230dd2SCorentin Chary             break;
23653e230dd2SCorentin Chary 
23663e230dd2SCorentin Chary         default:
2367153130cdSDaniel P. Berrange             VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
23683e230dd2SCorentin Chary             vnc_client_error(vs);
23693e230dd2SCorentin Chary             break;
23703e230dd2SCorentin Chary         }
23713e230dd2SCorentin Chary         break;
23723e230dd2SCorentin Chary     default:
2373153130cdSDaniel P. Berrange         VNC_DEBUG("Msg: %d\n", data[0]);
23743e230dd2SCorentin Chary         vnc_client_error(vs);
23753e230dd2SCorentin Chary         break;
23763e230dd2SCorentin Chary     }
23773e230dd2SCorentin Chary 
23783e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
23793e230dd2SCorentin Chary     return 0;
23803e230dd2SCorentin Chary }
23813e230dd2SCorentin Chary 
23823e230dd2SCorentin Chary static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
23833e230dd2SCorentin Chary {
23843e230dd2SCorentin Chary     char buf[1024];
23858cf36489SGerd Hoffmann     VncShareMode mode;
23863e230dd2SCorentin Chary     int size;
23873e230dd2SCorentin Chary 
23888cf36489SGerd Hoffmann     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
23898cf36489SGerd Hoffmann     switch (vs->vd->share_policy) {
23908cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_IGNORE:
23918cf36489SGerd Hoffmann         /*
23928cf36489SGerd Hoffmann          * Ignore the shared flag.  Nothing to do here.
23938cf36489SGerd Hoffmann          *
23948cf36489SGerd Hoffmann          * Doesn't conform to the rfb spec but is traditional qemu
23958cf36489SGerd Hoffmann          * behavior, thus left here as option for compatibility
23968cf36489SGerd Hoffmann          * reasons.
23978cf36489SGerd Hoffmann          */
23988cf36489SGerd Hoffmann         break;
23998cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
24008cf36489SGerd Hoffmann         /*
24018cf36489SGerd Hoffmann          * Policy: Allow clients ask for exclusive access.
24028cf36489SGerd Hoffmann          *
24038cf36489SGerd Hoffmann          * Implementation: When a client asks for exclusive access,
24048cf36489SGerd Hoffmann          * disconnect all others. Shared connects are allowed as long
24058cf36489SGerd Hoffmann          * as no exclusive connection exists.
24068cf36489SGerd Hoffmann          *
24078cf36489SGerd Hoffmann          * This is how the rfb spec suggests to handle the shared flag.
24088cf36489SGerd Hoffmann          */
24098cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24108cf36489SGerd Hoffmann             VncState *client;
24118cf36489SGerd Hoffmann             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
24128cf36489SGerd Hoffmann                 if (vs == client) {
24138cf36489SGerd Hoffmann                     continue;
24148cf36489SGerd Hoffmann                 }
24158cf36489SGerd Hoffmann                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
24168cf36489SGerd Hoffmann                     client->share_mode != VNC_SHARE_MODE_SHARED) {
24178cf36489SGerd Hoffmann                     continue;
24188cf36489SGerd Hoffmann                 }
24198cf36489SGerd Hoffmann                 vnc_disconnect_start(client);
24208cf36489SGerd Hoffmann             }
24218cf36489SGerd Hoffmann         }
24228cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_SHARED) {
24238cf36489SGerd Hoffmann             if (vs->vd->num_exclusive > 0) {
24248cf36489SGerd Hoffmann                 vnc_disconnect_start(vs);
24258cf36489SGerd Hoffmann                 return 0;
24268cf36489SGerd Hoffmann             }
24278cf36489SGerd Hoffmann         }
24288cf36489SGerd Hoffmann         break;
24298cf36489SGerd Hoffmann     case VNC_SHARE_POLICY_FORCE_SHARED:
24308cf36489SGerd Hoffmann         /*
24318cf36489SGerd Hoffmann          * Policy: Shared connects only.
24328cf36489SGerd Hoffmann          * Implementation: Disallow clients asking for exclusive access.
24338cf36489SGerd Hoffmann          *
24348cf36489SGerd Hoffmann          * Useful for shared desktop sessions where you don't want
24358cf36489SGerd Hoffmann          * someone forgetting to say -shared when running the vnc
24368cf36489SGerd Hoffmann          * client disconnect everybody else.
24378cf36489SGerd Hoffmann          */
24388cf36489SGerd Hoffmann         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
24398cf36489SGerd Hoffmann             vnc_disconnect_start(vs);
24408cf36489SGerd Hoffmann             return 0;
24418cf36489SGerd Hoffmann         }
24428cf36489SGerd Hoffmann         break;
24438cf36489SGerd Hoffmann     }
24448cf36489SGerd Hoffmann     vnc_set_share_mode(vs, mode);
24458cf36489SGerd Hoffmann 
2446e5f34cddSGerd Hoffmann     if (vs->vd->num_shared > vs->vd->connections_limit) {
2447e5f34cddSGerd Hoffmann         vnc_disconnect_start(vs);
2448e5f34cddSGerd Hoffmann         return 0;
2449e5f34cddSGerd Hoffmann     }
2450e5f34cddSGerd Hoffmann 
2451bea60dd7SPeter Lieven     vs->client_width = pixman_image_get_width(vs->vd->server);
2452bea60dd7SPeter Lieven     vs->client_height = pixman_image_get_height(vs->vd->server);
24533e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_width);
24543e230dd2SCorentin Chary     vnc_write_u16(vs, vs->client_height);
24553e230dd2SCorentin Chary 
24563e230dd2SCorentin Chary     pixel_format_message(vs);
24573e230dd2SCorentin Chary 
24583e230dd2SCorentin Chary     if (qemu_name)
24593e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
24603e230dd2SCorentin Chary     else
24613e230dd2SCorentin Chary         size = snprintf(buf, sizeof(buf), "QEMU");
24623e230dd2SCorentin Chary 
24633e230dd2SCorentin Chary     vnc_write_u32(vs, size);
24643e230dd2SCorentin Chary     vnc_write(vs, buf, size);
24653e230dd2SCorentin Chary     vnc_flush(vs);
24663e230dd2SCorentin Chary 
24673e230dd2SCorentin Chary     vnc_client_cache_auth(vs);
2468fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
24693e230dd2SCorentin Chary 
24703e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_msg, 1);
24713e230dd2SCorentin Chary 
24723e230dd2SCorentin Chary     return 0;
24733e230dd2SCorentin Chary }
24743e230dd2SCorentin Chary 
24753e230dd2SCorentin Chary void start_client_init(VncState *vs)
24763e230dd2SCorentin Chary {
24773e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_init, 1);
24783e230dd2SCorentin Chary }
24793e230dd2SCorentin Chary 
24803e230dd2SCorentin Chary static void make_challenge(VncState *vs)
24813e230dd2SCorentin Chary {
24823e230dd2SCorentin Chary     int i;
24833e230dd2SCorentin Chary 
24843e230dd2SCorentin Chary     srand(time(NULL)+getpid()+getpid()*987654+rand());
24853e230dd2SCorentin Chary 
24863e230dd2SCorentin Chary     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
24873e230dd2SCorentin Chary         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
24883e230dd2SCorentin Chary }
24893e230dd2SCorentin Chary 
24903e230dd2SCorentin Chary static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
24913e230dd2SCorentin Chary {
24923e230dd2SCorentin Chary     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2493800567a6SDaniel P. Berrange     size_t i, pwlen;
24943e230dd2SCorentin Chary     unsigned char key[8];
24953c9405a0SGerd Hoffmann     time_t now = time(NULL);
249660928458SGonglei     QCryptoCipher *cipher = NULL;
2497800567a6SDaniel P. Berrange     Error *err = NULL;
24983e230dd2SCorentin Chary 
24991cd20f8bSAnthony Liguori     if (!vs->vd->password) {
25003e230dd2SCorentin Chary         VNC_DEBUG("No password configured on server");
25016bffdf0fSGerd Hoffmann         goto reject;
25023e230dd2SCorentin Chary     }
25033c9405a0SGerd Hoffmann     if (vs->vd->expires < now) {
25043c9405a0SGerd Hoffmann         VNC_DEBUG("Password is expired");
25053c9405a0SGerd Hoffmann         goto reject;
25063c9405a0SGerd Hoffmann     }
25073e230dd2SCorentin Chary 
25083e230dd2SCorentin Chary     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
25093e230dd2SCorentin Chary 
25103e230dd2SCorentin Chary     /* Calculate the expected challenge response */
25113e230dd2SCorentin Chary     pwlen = strlen(vs->vd->password);
25123e230dd2SCorentin Chary     for (i=0; i<sizeof(key); i++)
25133e230dd2SCorentin Chary         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2514800567a6SDaniel P. Berrange 
2515800567a6SDaniel P. Berrange     cipher = qcrypto_cipher_new(
2516800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_DES_RFB,
2517800567a6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_ECB,
2518800567a6SDaniel P. Berrange         key, G_N_ELEMENTS(key),
2519800567a6SDaniel P. Berrange         &err);
2520800567a6SDaniel P. Berrange     if (!cipher) {
2521800567a6SDaniel P. Berrange         VNC_DEBUG("Cannot initialize cipher %s",
2522800567a6SDaniel P. Berrange                   error_get_pretty(err));
2523800567a6SDaniel P. Berrange         error_free(err);
2524800567a6SDaniel P. Berrange         goto reject;
2525800567a6SDaniel P. Berrange     }
2526800567a6SDaniel P. Berrange 
2527a1695137SWolfgang Bumiller     if (qcrypto_cipher_encrypt(cipher,
2528800567a6SDaniel P. Berrange                                vs->challenge,
2529800567a6SDaniel P. Berrange                                response,
2530800567a6SDaniel P. Berrange                                VNC_AUTH_CHALLENGE_SIZE,
2531800567a6SDaniel P. Berrange                                &err) < 0) {
2532800567a6SDaniel P. Berrange         VNC_DEBUG("Cannot encrypt challenge %s",
2533800567a6SDaniel P. Berrange                   error_get_pretty(err));
2534800567a6SDaniel P. Berrange         error_free(err);
2535800567a6SDaniel P. Berrange         goto reject;
2536800567a6SDaniel P. Berrange     }
25373e230dd2SCorentin Chary 
25383e230dd2SCorentin Chary     /* Compare expected vs actual challenge response */
25393e230dd2SCorentin Chary     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2540e5bed759SDong Xu Wang         VNC_DEBUG("Client challenge response did not match\n");
25416bffdf0fSGerd Hoffmann         goto reject;
25426bffdf0fSGerd Hoffmann     } else {
25436bffdf0fSGerd Hoffmann         VNC_DEBUG("Accepting VNC challenge response\n");
25446bffdf0fSGerd Hoffmann         vnc_write_u32(vs, 0); /* Accept auth */
25456bffdf0fSGerd Hoffmann         vnc_flush(vs);
25466bffdf0fSGerd Hoffmann 
25476bffdf0fSGerd Hoffmann         start_client_init(vs);
25486bffdf0fSGerd Hoffmann     }
254960928458SGonglei 
255060928458SGonglei     qcrypto_cipher_free(cipher);
25516bffdf0fSGerd Hoffmann     return 0;
25526bffdf0fSGerd Hoffmann 
25536bffdf0fSGerd Hoffmann reject:
25543e230dd2SCorentin Chary     vnc_write_u32(vs, 1); /* Reject auth */
25553e230dd2SCorentin Chary     if (vs->minor >= 8) {
25563e230dd2SCorentin Chary         static const char err[] = "Authentication failed";
25573e230dd2SCorentin Chary         vnc_write_u32(vs, sizeof(err));
25583e230dd2SCorentin Chary         vnc_write(vs, err, sizeof(err));
25593e230dd2SCorentin Chary     }
25603e230dd2SCorentin Chary     vnc_flush(vs);
25613e230dd2SCorentin Chary     vnc_client_error(vs);
256260928458SGonglei     qcrypto_cipher_free(cipher);
25633e230dd2SCorentin Chary     return 0;
25643e230dd2SCorentin Chary }
25653e230dd2SCorentin Chary 
25663e230dd2SCorentin Chary void start_auth_vnc(VncState *vs)
25673e230dd2SCorentin Chary {
25683e230dd2SCorentin Chary     make_challenge(vs);
25693e230dd2SCorentin Chary     /* Send client a 'random' challenge */
25703e230dd2SCorentin Chary     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
25713e230dd2SCorentin Chary     vnc_flush(vs);
25723e230dd2SCorentin Chary 
25733e230dd2SCorentin Chary     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
25743e230dd2SCorentin Chary }
25753e230dd2SCorentin Chary 
25763e230dd2SCorentin Chary 
25773e230dd2SCorentin Chary static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
25783e230dd2SCorentin Chary {
25793e230dd2SCorentin Chary     /* We only advertise 1 auth scheme at a time, so client
25803e230dd2SCorentin Chary      * must pick the one we sent. Verify this */
25817e7e2ebcSDaniel P. Berrange     if (data[0] != vs->auth) { /* Reject auth */
25823e230dd2SCorentin Chary        VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
25833e230dd2SCorentin Chary        vnc_write_u32(vs, 1);
25843e230dd2SCorentin Chary        if (vs->minor >= 8) {
25853e230dd2SCorentin Chary            static const char err[] = "Authentication failed";
25863e230dd2SCorentin Chary            vnc_write_u32(vs, sizeof(err));
25873e230dd2SCorentin Chary            vnc_write(vs, err, sizeof(err));
25883e230dd2SCorentin Chary        }
25893e230dd2SCorentin Chary        vnc_client_error(vs);
25903e230dd2SCorentin Chary     } else { /* Accept requested auth */
25913e230dd2SCorentin Chary        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
25927e7e2ebcSDaniel P. Berrange        switch (vs->auth) {
25933e230dd2SCorentin Chary        case VNC_AUTH_NONE:
25943e230dd2SCorentin Chary            VNC_DEBUG("Accept auth none\n");
25953e230dd2SCorentin Chary            if (vs->minor >= 8) {
25963e230dd2SCorentin Chary                vnc_write_u32(vs, 0); /* Accept auth completion */
25973e230dd2SCorentin Chary                vnc_flush(vs);
25983e230dd2SCorentin Chary            }
25993e230dd2SCorentin Chary            start_client_init(vs);
26003e230dd2SCorentin Chary            break;
26013e230dd2SCorentin Chary 
26023e230dd2SCorentin Chary        case VNC_AUTH_VNC:
26033e230dd2SCorentin Chary            VNC_DEBUG("Start VNC auth\n");
26043e230dd2SCorentin Chary            start_auth_vnc(vs);
26053e230dd2SCorentin Chary            break;
26063e230dd2SCorentin Chary 
26073e230dd2SCorentin Chary        case VNC_AUTH_VENCRYPT:
26083a93113aSDong Xu Wang            VNC_DEBUG("Accept VeNCrypt auth\n");
26093e230dd2SCorentin Chary            start_auth_vencrypt(vs);
26103e230dd2SCorentin Chary            break;
26113e230dd2SCorentin Chary 
26123e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
26133e230dd2SCorentin Chary        case VNC_AUTH_SASL:
26143e230dd2SCorentin Chary            VNC_DEBUG("Accept SASL auth\n");
26153e230dd2SCorentin Chary            start_auth_sasl(vs);
26163e230dd2SCorentin Chary            break;
26173e230dd2SCorentin Chary #endif /* CONFIG_VNC_SASL */
26183e230dd2SCorentin Chary 
26193e230dd2SCorentin Chary        default: /* Should not be possible, but just in case */
26207e7e2ebcSDaniel P. Berrange            VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
26213e230dd2SCorentin Chary            vnc_write_u8(vs, 1);
26223e230dd2SCorentin Chary            if (vs->minor >= 8) {
26233e230dd2SCorentin Chary                static const char err[] = "Authentication failed";
26243e230dd2SCorentin Chary                vnc_write_u32(vs, sizeof(err));
26253e230dd2SCorentin Chary                vnc_write(vs, err, sizeof(err));
26263e230dd2SCorentin Chary            }
26273e230dd2SCorentin Chary            vnc_client_error(vs);
26283e230dd2SCorentin Chary        }
26293e230dd2SCorentin Chary     }
26303e230dd2SCorentin Chary     return 0;
26313e230dd2SCorentin Chary }
26323e230dd2SCorentin Chary 
26333e230dd2SCorentin Chary static int protocol_version(VncState *vs, uint8_t *version, size_t len)
26343e230dd2SCorentin Chary {
26353e230dd2SCorentin Chary     char local[13];
26363e230dd2SCorentin Chary 
26373e230dd2SCorentin Chary     memcpy(local, version, 12);
26383e230dd2SCorentin Chary     local[12] = 0;
26393e230dd2SCorentin Chary 
26403e230dd2SCorentin Chary     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
26413e230dd2SCorentin Chary         VNC_DEBUG("Malformed protocol version %s\n", local);
26423e230dd2SCorentin Chary         vnc_client_error(vs);
26433e230dd2SCorentin Chary         return 0;
26443e230dd2SCorentin Chary     }
26453e230dd2SCorentin Chary     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
26463e230dd2SCorentin Chary     if (vs->major != 3 ||
26473e230dd2SCorentin Chary         (vs->minor != 3 &&
26483e230dd2SCorentin Chary          vs->minor != 4 &&
26493e230dd2SCorentin Chary          vs->minor != 5 &&
26503e230dd2SCorentin Chary          vs->minor != 7 &&
26513e230dd2SCorentin Chary          vs->minor != 8)) {
26523e230dd2SCorentin Chary         VNC_DEBUG("Unsupported client version\n");
26533e230dd2SCorentin Chary         vnc_write_u32(vs, VNC_AUTH_INVALID);
26543e230dd2SCorentin Chary         vnc_flush(vs);
26553e230dd2SCorentin Chary         vnc_client_error(vs);
26563e230dd2SCorentin Chary         return 0;
26573e230dd2SCorentin Chary     }
26583e230dd2SCorentin Chary     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
26593e230dd2SCorentin Chary      * as equivalent to v3.3 by servers
26603e230dd2SCorentin Chary      */
26613e230dd2SCorentin Chary     if (vs->minor == 4 || vs->minor == 5)
26623e230dd2SCorentin Chary         vs->minor = 3;
26633e230dd2SCorentin Chary 
26643e230dd2SCorentin Chary     if (vs->minor == 3) {
26657e7e2ebcSDaniel P. Berrange         if (vs->auth == VNC_AUTH_NONE) {
26663e230dd2SCorentin Chary             VNC_DEBUG("Tell client auth none\n");
26677e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
26683e230dd2SCorentin Chary             vnc_flush(vs);
26693e230dd2SCorentin Chary             start_client_init(vs);
26707e7e2ebcSDaniel P. Berrange        } else if (vs->auth == VNC_AUTH_VNC) {
26713e230dd2SCorentin Chary             VNC_DEBUG("Tell client VNC auth\n");
26727e7e2ebcSDaniel P. Berrange             vnc_write_u32(vs, vs->auth);
26733e230dd2SCorentin Chary             vnc_flush(vs);
26743e230dd2SCorentin Chary             start_auth_vnc(vs);
26753e230dd2SCorentin Chary        } else {
26767e7e2ebcSDaniel P. Berrange             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
26773e230dd2SCorentin Chary             vnc_write_u32(vs, VNC_AUTH_INVALID);
26783e230dd2SCorentin Chary             vnc_flush(vs);
26793e230dd2SCorentin Chary             vnc_client_error(vs);
26803e230dd2SCorentin Chary        }
26813e230dd2SCorentin Chary     } else {
26827e7e2ebcSDaniel P. Berrange         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
26833e230dd2SCorentin Chary         vnc_write_u8(vs, 1); /* num auth */
26847e7e2ebcSDaniel P. Berrange         vnc_write_u8(vs, vs->auth);
26853e230dd2SCorentin Chary         vnc_read_when(vs, protocol_client_auth, 1);
26863e230dd2SCorentin Chary         vnc_flush(vs);
26873e230dd2SCorentin Chary     }
26883e230dd2SCorentin Chary 
26893e230dd2SCorentin Chary     return 0;
26903e230dd2SCorentin Chary }
26913e230dd2SCorentin Chary 
2692999342a0SCorentin Chary static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2693999342a0SCorentin Chary {
2694999342a0SCorentin Chary     struct VncSurface *vs = &vd->guest;
2695999342a0SCorentin Chary 
2696999342a0SCorentin Chary     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2697999342a0SCorentin Chary }
2698999342a0SCorentin Chary 
26997d964c9dSCorentin Chary void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
27007d964c9dSCorentin Chary {
27017d964c9dSCorentin Chary     int i, j;
27027d964c9dSCorentin Chary 
27037d964c9dSCorentin Chary     w = (x + w) / VNC_STAT_RECT;
27047d964c9dSCorentin Chary     h = (y + h) / VNC_STAT_RECT;
27057d964c9dSCorentin Chary     x /= VNC_STAT_RECT;
27067d964c9dSCorentin Chary     y /= VNC_STAT_RECT;
27077d964c9dSCorentin Chary 
2708207f328aSCorentin Chary     for (j = y; j <= h; j++) {
2709207f328aSCorentin Chary         for (i = x; i <= w; i++) {
27107d964c9dSCorentin Chary             vs->lossy_rect[j][i] = 1;
27117d964c9dSCorentin Chary         }
27127d964c9dSCorentin Chary     }
27137d964c9dSCorentin Chary }
27147d964c9dSCorentin Chary 
27157d964c9dSCorentin Chary static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
27167d964c9dSCorentin Chary {
27177d964c9dSCorentin Chary     VncState *vs;
27187d964c9dSCorentin Chary     int sty = y / VNC_STAT_RECT;
27197d964c9dSCorentin Chary     int stx = x / VNC_STAT_RECT;
27207d964c9dSCorentin Chary     int has_dirty = 0;
27217d964c9dSCorentin Chary 
27227d964c9dSCorentin Chary     y = y / VNC_STAT_RECT * VNC_STAT_RECT;
27237d964c9dSCorentin Chary     x = x / VNC_STAT_RECT * VNC_STAT_RECT;
27247d964c9dSCorentin Chary 
27257d964c9dSCorentin Chary     QTAILQ_FOREACH(vs, &vd->clients, next) {
2726bc2429b9SCorentin Chary         int j;
27277d964c9dSCorentin Chary 
27287d964c9dSCorentin Chary         /* kernel send buffers are full -> refresh later */
27297d964c9dSCorentin Chary         if (vs->output.offset) {
27307d964c9dSCorentin Chary             continue;
27317d964c9dSCorentin Chary         }
27327d964c9dSCorentin Chary 
27337d964c9dSCorentin Chary         if (!vs->lossy_rect[sty][stx]) {
27347d964c9dSCorentin Chary             continue;
27357d964c9dSCorentin Chary         }
2736207f328aSCorentin Chary 
27377d964c9dSCorentin Chary         vs->lossy_rect[sty][stx] = 0;
27387d964c9dSCorentin Chary         for (j = 0; j < VNC_STAT_RECT; ++j) {
2739b4c85ddcSPeter Lieven             bitmap_set(vs->dirty[y + j],
2740b4c85ddcSPeter Lieven                        x / VNC_DIRTY_PIXELS_PER_BIT,
2741b4c85ddcSPeter Lieven                        VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
27427d964c9dSCorentin Chary         }
27437d964c9dSCorentin Chary         has_dirty++;
27447d964c9dSCorentin Chary     }
2745207f328aSCorentin Chary 
27467d964c9dSCorentin Chary     return has_dirty;
27477d964c9dSCorentin Chary }
27487d964c9dSCorentin Chary 
27497d964c9dSCorentin Chary static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2750999342a0SCorentin Chary {
27519f64916dSGerd Hoffmann     int width = pixman_image_get_width(vd->guest.fb);
27529f64916dSGerd Hoffmann     int height = pixman_image_get_height(vd->guest.fb);
2753999342a0SCorentin Chary     int x, y;
2754999342a0SCorentin Chary     struct timeval res;
27557d964c9dSCorentin Chary     int has_dirty = 0;
2756999342a0SCorentin Chary 
27579f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
27589f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2759999342a0SCorentin Chary             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2760999342a0SCorentin Chary 
2761999342a0SCorentin Chary             rect->updated = false;
2762999342a0SCorentin Chary         }
2763999342a0SCorentin Chary     }
2764999342a0SCorentin Chary 
2765ad620c29SBlue Swirl     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2766999342a0SCorentin Chary 
2767999342a0SCorentin Chary     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
27687d964c9dSCorentin Chary         return has_dirty;
2769999342a0SCorentin Chary     }
2770999342a0SCorentin Chary     vd->guest.last_freq_check = *tv;
2771999342a0SCorentin Chary 
27729f64916dSGerd Hoffmann     for (y = 0; y < height; y += VNC_STAT_RECT) {
27739f64916dSGerd Hoffmann         for (x = 0; x < width; x += VNC_STAT_RECT) {
2774999342a0SCorentin Chary             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2775999342a0SCorentin Chary             int count = ARRAY_SIZE(rect->times);
2776999342a0SCorentin Chary             struct timeval min, max;
2777999342a0SCorentin Chary 
2778999342a0SCorentin Chary             if (!timerisset(&rect->times[count - 1])) {
2779999342a0SCorentin Chary                 continue ;
2780999342a0SCorentin Chary             }
2781999342a0SCorentin Chary 
2782999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2783ad620c29SBlue Swirl             qemu_timersub(tv, &max, &res);
2784999342a0SCorentin Chary 
2785999342a0SCorentin Chary             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2786999342a0SCorentin Chary                 rect->freq = 0;
27877d964c9dSCorentin Chary                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2788999342a0SCorentin Chary                 memset(rect->times, 0, sizeof (rect->times));
2789999342a0SCorentin Chary                 continue ;
2790999342a0SCorentin Chary             }
2791999342a0SCorentin Chary 
2792999342a0SCorentin Chary             min = rect->times[rect->idx];
2793999342a0SCorentin Chary             max = rect->times[(rect->idx + count - 1) % count];
2794ad620c29SBlue Swirl             qemu_timersub(&max, &min, &res);
2795999342a0SCorentin Chary 
2796999342a0SCorentin Chary             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2797999342a0SCorentin Chary             rect->freq /= count;
2798999342a0SCorentin Chary             rect->freq = 1. / rect->freq;
2799999342a0SCorentin Chary         }
2800999342a0SCorentin Chary     }
28017d964c9dSCorentin Chary     return has_dirty;
2802999342a0SCorentin Chary }
2803999342a0SCorentin Chary 
2804999342a0SCorentin Chary double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2805999342a0SCorentin Chary {
2806999342a0SCorentin Chary     int i, j;
2807999342a0SCorentin Chary     double total = 0;
2808999342a0SCorentin Chary     int num = 0;
2809999342a0SCorentin Chary 
2810999342a0SCorentin Chary     x =  (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2811999342a0SCorentin Chary     y =  (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2812999342a0SCorentin Chary 
2813999342a0SCorentin Chary     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2814999342a0SCorentin Chary         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2815999342a0SCorentin Chary             total += vnc_stat_rect(vs->vd, i, j)->freq;
2816999342a0SCorentin Chary             num++;
2817999342a0SCorentin Chary         }
2818999342a0SCorentin Chary     }
2819999342a0SCorentin Chary 
2820999342a0SCorentin Chary     if (num) {
2821999342a0SCorentin Chary         return total / num;
2822999342a0SCorentin Chary     } else {
2823999342a0SCorentin Chary         return 0;
2824999342a0SCorentin Chary     }
2825999342a0SCorentin Chary }
2826999342a0SCorentin Chary 
2827999342a0SCorentin Chary static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2828999342a0SCorentin Chary {
2829999342a0SCorentin Chary     VncRectStat *rect;
2830999342a0SCorentin Chary 
2831999342a0SCorentin Chary     rect = vnc_stat_rect(vd, x, y);
2832999342a0SCorentin Chary     if (rect->updated) {
2833999342a0SCorentin Chary         return ;
2834999342a0SCorentin Chary     }
2835999342a0SCorentin Chary     rect->times[rect->idx] = *tv;
2836999342a0SCorentin Chary     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2837999342a0SCorentin Chary     rect->updated = true;
2838999342a0SCorentin Chary }
2839999342a0SCorentin Chary 
28403e230dd2SCorentin Chary static int vnc_refresh_server_surface(VncDisplay *vd)
28413e230dd2SCorentin Chary {
2842bea60dd7SPeter Lieven     int width = MIN(pixman_image_get_width(vd->guest.fb),
2843bea60dd7SPeter Lieven                     pixman_image_get_width(vd->server));
2844bea60dd7SPeter Lieven     int height = MIN(pixman_image_get_height(vd->guest.fb),
2845bea60dd7SPeter Lieven                      pixman_image_get_height(vd->server));
2846eb8934b0SGerd Hoffmann     int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
284712b316d4SPeter Lieven     uint8_t *guest_row0 = NULL, *server_row0;
28483e230dd2SCorentin Chary     VncState *vs;
28493e230dd2SCorentin Chary     int has_dirty = 0;
28509f64916dSGerd Hoffmann     pixman_image_t *tmpbuf = NULL;
28513e230dd2SCorentin Chary 
285280e0c8c3SCorentin Chary     struct timeval tv = { 0, 0 };
2853999342a0SCorentin Chary 
285480e0c8c3SCorentin Chary     if (!vd->non_adaptive) {
2855999342a0SCorentin Chary         gettimeofday(&tv, NULL);
28567d964c9dSCorentin Chary         has_dirty = vnc_update_stats(vd, &tv);
285780e0c8c3SCorentin Chary     }
2858999342a0SCorentin Chary 
28593e230dd2SCorentin Chary     /*
28603e230dd2SCorentin Chary      * Walk through the guest dirty map.
28613e230dd2SCorentin Chary      * Check and copy modified bits from guest to server surface.
28623e230dd2SCorentin Chary      * Update server dirty map.
28633e230dd2SCorentin Chary      */
2864bea60dd7SPeter Lieven     server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2865eb8934b0SGerd Hoffmann     server_stride = guest_stride = guest_ll =
2866eb8934b0SGerd Hoffmann         pixman_image_get_stride(vd->server);
2867bea60dd7SPeter Lieven     cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2868bea60dd7SPeter Lieven                     server_stride);
28699f64916dSGerd Hoffmann     if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
28709f64916dSGerd Hoffmann         int width = pixman_image_get_width(vd->server);
28719f64916dSGerd Hoffmann         tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
287212b316d4SPeter Lieven     } else {
2873eb8934b0SGerd Hoffmann         int guest_bpp =
2874eb8934b0SGerd Hoffmann             PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
287512b316d4SPeter Lieven         guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
287612b316d4SPeter Lieven         guest_stride = pixman_image_get_stride(vd->guest.fb);
2877eb8934b0SGerd Hoffmann         guest_ll = pixman_image_get_width(vd->guest.fb) * ((guest_bpp + 7) / 8);
28789f64916dSGerd Hoffmann     }
2879eb8934b0SGerd Hoffmann     line_bytes = MIN(server_stride, guest_ll);
288012b316d4SPeter Lieven 
288112b316d4SPeter Lieven     for (;;) {
28823e230dd2SCorentin Chary         int x;
288312b316d4SPeter Lieven         uint8_t *guest_ptr, *server_ptr;
288412b316d4SPeter Lieven         unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
288512b316d4SPeter Lieven                                              height * VNC_DIRTY_BPL(&vd->guest),
288612b316d4SPeter Lieven                                              y * VNC_DIRTY_BPL(&vd->guest));
288712b316d4SPeter Lieven         if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
288812b316d4SPeter Lieven             /* no more dirty bits */
288912b316d4SPeter Lieven             break;
289012b316d4SPeter Lieven         }
289112b316d4SPeter Lieven         y = offset / VNC_DIRTY_BPL(&vd->guest);
289212b316d4SPeter Lieven         x = offset % VNC_DIRTY_BPL(&vd->guest);
289312b316d4SPeter Lieven 
289412b316d4SPeter Lieven         server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
28953e230dd2SCorentin Chary 
28969f64916dSGerd Hoffmann         if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2897bc210eb1SGerd Hoffmann             qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
28989f64916dSGerd Hoffmann             guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
28999f64916dSGerd Hoffmann         } else {
290012b316d4SPeter Lieven             guest_ptr = guest_row0 + y * guest_stride;
29019f64916dSGerd Hoffmann         }
290212b316d4SPeter Lieven         guest_ptr += x * cmp_bytes;
29033e230dd2SCorentin Chary 
290412b316d4SPeter Lieven         for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
290512b316d4SPeter Lieven              x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2906bea60dd7SPeter Lieven             int _cmp_bytes = cmp_bytes;
290712b316d4SPeter Lieven             if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
29083e230dd2SCorentin Chary                 continue;
2909b4c85ddcSPeter Lieven             }
2910eb8934b0SGerd Hoffmann             if ((x + 1) * cmp_bytes > line_bytes) {
2911eb8934b0SGerd Hoffmann                 _cmp_bytes = line_bytes - x * cmp_bytes;
2912bea60dd7SPeter Lieven             }
2913eb8934b0SGerd Hoffmann             assert(_cmp_bytes >= 0);
2914bea60dd7SPeter Lieven             if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
29153e230dd2SCorentin Chary                 continue;
2916b4c85ddcSPeter Lieven             }
2917bea60dd7SPeter Lieven             memcpy(server_ptr, guest_ptr, _cmp_bytes);
291812b316d4SPeter Lieven             if (!vd->non_adaptive) {
291912b316d4SPeter Lieven                 vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
292012b316d4SPeter Lieven                                  y, &tv);
292112b316d4SPeter Lieven             }
29223e230dd2SCorentin Chary             QTAILQ_FOREACH(vs, &vd->clients, next) {
292312b316d4SPeter Lieven                 set_bit(x, vs->dirty[y]);
29243e230dd2SCorentin Chary             }
29253e230dd2SCorentin Chary             has_dirty++;
29263e230dd2SCorentin Chary         }
292712b316d4SPeter Lieven 
292812b316d4SPeter Lieven         y++;
29293e230dd2SCorentin Chary     }
29309f64916dSGerd Hoffmann     qemu_pixman_image_unref(tmpbuf);
29313e230dd2SCorentin Chary     return has_dirty;
29323e230dd2SCorentin Chary }
29333e230dd2SCorentin Chary 
29340f7b2864SGerd Hoffmann static void vnc_refresh(DisplayChangeListener *dcl)
29353e230dd2SCorentin Chary {
29360f7b2864SGerd Hoffmann     VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
29373e230dd2SCorentin Chary     VncState *vs, *vn;
29383e230dd2SCorentin Chary     int has_dirty, rects = 0;
29393e230dd2SCorentin Chary 
29409d6b2070SChenLiang     if (QTAILQ_EMPTY(&vd->clients)) {
29419d6b2070SChenLiang         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
29429d6b2070SChenLiang         return;
29439d6b2070SChenLiang     }
29449d6b2070SChenLiang 
29451d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
29463e230dd2SCorentin Chary 
2947bd023f95SCorentin Chary     if (vnc_trylock_display(vd)) {
29480f7b2864SGerd Hoffmann         update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2949bd023f95SCorentin Chary         return;
2950bd023f95SCorentin Chary     }
2951bd023f95SCorentin Chary 
29523e230dd2SCorentin Chary     has_dirty = vnc_refresh_server_surface(vd);
2953bd023f95SCorentin Chary     vnc_unlock_display(vd);
29543e230dd2SCorentin Chary 
29553e230dd2SCorentin Chary     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
295638ee14f4SGerd Hoffmann         rects += vnc_update_client(vs, has_dirty, false);
29573e230dd2SCorentin Chary         /* vs might be free()ed here */
29583e230dd2SCorentin Chary     }
2959bd023f95SCorentin Chary 
29603e230dd2SCorentin Chary     if (has_dirty && rects) {
29610f7b2864SGerd Hoffmann         vd->dcl.update_interval /= 2;
29620f7b2864SGerd Hoffmann         if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
29630f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
29640f7b2864SGerd Hoffmann         }
29653e230dd2SCorentin Chary     } else {
29660f7b2864SGerd Hoffmann         vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
29670f7b2864SGerd Hoffmann         if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
29680f7b2864SGerd Hoffmann             vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
29693e230dd2SCorentin Chary         }
29703e230dd2SCorentin Chary     }
29713e230dd2SCorentin Chary }
29723e230dd2SCorentin Chary 
297304d2529dSDaniel P. Berrange static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
29742c8cf549SMichael Tokarev                         bool skipauth, bool websocket)
29753e230dd2SCorentin Chary {
2976fedf0d35SMarkus Armbruster     VncState *vs = g_new0(VncState, 1);
29777d964c9dSCorentin Chary     int i;
29787d964c9dSCorentin Chary 
297904d2529dSDaniel P. Berrange     vs->sioc = sioc;
298004d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->sioc));
298104d2529dSDaniel P. Berrange     vs->ioc = QIO_CHANNEL(sioc);
298204d2529dSDaniel P. Berrange     object_ref(OBJECT(vs->ioc));
2983d616ccc5SGerd Hoffmann     vs->vd = vd;
29847e7e2ebcSDaniel P. Berrange 
298504d2529dSDaniel P. Berrange     buffer_init(&vs->input,          "vnc-input/%p", sioc);
298604d2529dSDaniel P. Berrange     buffer_init(&vs->output,         "vnc-output/%p", sioc);
298704d2529dSDaniel P. Berrange     buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
2988543b9580SGerd Hoffmann 
298904d2529dSDaniel P. Berrange     buffer_init(&vs->tight.tight,    "vnc-tight/%p", sioc);
299004d2529dSDaniel P. Berrange     buffer_init(&vs->tight.zlib,     "vnc-tight-zlib/%p", sioc);
299104d2529dSDaniel P. Berrange     buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);
2992543b9580SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
299304d2529dSDaniel P. Berrange     buffer_init(&vs->tight.jpeg,     "vnc-tight-jpeg/%p", sioc);
2994543b9580SGerd Hoffmann #endif
2995543b9580SGerd Hoffmann #ifdef CONFIG_VNC_PNG
299604d2529dSDaniel P. Berrange     buffer_init(&vs->tight.png,      "vnc-tight-png/%p", sioc);
2997543b9580SGerd Hoffmann #endif
299804d2529dSDaniel P. Berrange     buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
299904d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.zrle,      "vnc-zrle/%p", sioc);
300004d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.fb,        "vnc-zrle-fb/%p", sioc);
300104d2529dSDaniel P. Berrange     buffer_init(&vs->zrle.zlib,      "vnc-zrle-zlib/%p", sioc);
3002543b9580SGerd Hoffmann 
30037e7e2ebcSDaniel P. Berrange     if (skipauth) {
30047e7e2ebcSDaniel P. Berrange 	vs->auth = VNC_AUTH_NONE;
30057e7e2ebcSDaniel P. Berrange 	vs->subauth = VNC_AUTH_INVALID;
30067e7e2ebcSDaniel P. Berrange     } else {
3007f9148c8aSDaniel P. Berrange         if (websocket) {
3008f9148c8aSDaniel P. Berrange             vs->auth = vd->ws_auth;
3009f9148c8aSDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
3010f9148c8aSDaniel P. Berrange         } else {
30117e7e2ebcSDaniel P. Berrange             vs->auth = vd->auth;
30127e7e2ebcSDaniel P. Berrange             vs->subauth = vd->subauth;
30137e7e2ebcSDaniel P. Berrange         }
3014f9148c8aSDaniel P. Berrange     }
301504d2529dSDaniel P. Berrange     VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
301604d2529dSDaniel P. Berrange               sioc, websocket, vs->auth, vs->subauth);
30177e7e2ebcSDaniel P. Berrange 
30187267c094SAnthony Liguori     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
30197d964c9dSCorentin Chary     for (i = 0; i < VNC_STAT_ROWS; ++i) {
3020fedf0d35SMarkus Armbruster         vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
30217d964c9dSCorentin Chary     }
30223e230dd2SCorentin Chary 
302304d2529dSDaniel P. Berrange     VNC_DEBUG("New client on socket %p\n", vs->sioc);
30240f7b2864SGerd Hoffmann     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
302504d2529dSDaniel P. Berrange     qio_channel_set_blocking(vs->ioc, false, NULL);
30267536ee4bSTim Hardeck     if (websocket) {
30277536ee4bSTim Hardeck         vs->websocket = 1;
3028f9148c8aSDaniel P. Berrange         if (vd->ws_tls) {
302904d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
303004d2529dSDaniel P. Berrange                 vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
30313e305e4aSDaniel P. Berrange         } else {
303204d2529dSDaniel P. Berrange             vs->ioc_tag = qio_channel_add_watch(
303304d2529dSDaniel P. Berrange                 vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
30340057a0d5STim Hardeck         }
303504d2529dSDaniel P. Berrange     } else {
303604d2529dSDaniel P. Berrange         vs->ioc_tag = qio_channel_add_watch(
303704d2529dSDaniel P. Berrange             vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
30387536ee4bSTim Hardeck     }
30393e230dd2SCorentin Chary 
30403e230dd2SCorentin Chary     vnc_client_cache_addr(vs);
3041fb6ba0d5SWenchao Xia     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
30428cf36489SGerd Hoffmann     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
30433e230dd2SCorentin Chary 
30448e9b0d24SDaniel P. Berrange     if (!vs->websocket) {
30457536ee4bSTim Hardeck         vnc_init_state(vs);
30467536ee4bSTim Hardeck     }
3047e5f34cddSGerd Hoffmann 
3048e5f34cddSGerd Hoffmann     if (vd->num_connecting > vd->connections_limit) {
3049e5f34cddSGerd Hoffmann         QTAILQ_FOREACH(vs, &vd->clients, next) {
3050e5f34cddSGerd Hoffmann             if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3051e5f34cddSGerd Hoffmann                 vnc_disconnect_start(vs);
3052e5f34cddSGerd Hoffmann                 return;
3053e5f34cddSGerd Hoffmann             }
3054e5f34cddSGerd Hoffmann         }
3055e5f34cddSGerd Hoffmann     }
30567536ee4bSTim Hardeck }
30577536ee4bSTim Hardeck 
30587536ee4bSTim Hardeck void vnc_init_state(VncState *vs)
30597536ee4bSTim Hardeck {
30606fd8e79aSTim Hardeck     vs->initialized = true;
30617536ee4bSTim Hardeck     VncDisplay *vd = vs->vd;
3062c7628bffSGerd Hoffmann     bool first_client = QTAILQ_EMPTY(&vd->clients);
30637536ee4bSTim Hardeck 
30643e230dd2SCorentin Chary     vs->last_x = -1;
30653e230dd2SCorentin Chary     vs->last_y = -1;
30663e230dd2SCorentin Chary 
30673e230dd2SCorentin Chary     vs->as.freq = 44100;
30683e230dd2SCorentin Chary     vs->as.nchannels = 2;
30693e230dd2SCorentin Chary     vs->as.fmt = AUD_FMT_S16;
30703e230dd2SCorentin Chary     vs->as.endianness = 0;
30713e230dd2SCorentin Chary 
3072bd023f95SCorentin Chary     qemu_mutex_init(&vs->output_mutex);
3073175b2a6eSCorentin Chary     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3074bd023f95SCorentin Chary 
3075e5f34cddSGerd Hoffmann     QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3076c7628bffSGerd Hoffmann     if (first_client) {
3077c7628bffSGerd Hoffmann         vnc_update_server_surface(vd);
3078c7628bffSGerd Hoffmann     }
30793e230dd2SCorentin Chary 
30801d0d59feSGerd Hoffmann     graphic_hw_update(vd->dcl.con);
30813e230dd2SCorentin Chary 
30823e230dd2SCorentin Chary     vnc_write(vs, "RFB 003.008\n", 12);
30833e230dd2SCorentin Chary     vnc_flush(vs);
30843e230dd2SCorentin Chary     vnc_read_when(vs, protocol_version, 12);
30853e230dd2SCorentin Chary     reset_keys(vs);
30863e230dd2SCorentin Chary     if (vs->vd->lock_key_sync)
30873e230dd2SCorentin Chary         vs->led = qemu_add_led_event_handler(kbd_leds, vs);
30883e230dd2SCorentin Chary 
30893e230dd2SCorentin Chary     vs->mouse_mode_notifier.notify = check_pointer_type_change;
30903e230dd2SCorentin Chary     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
30913e230dd2SCorentin Chary 
30923e230dd2SCorentin Chary     /* vs might be free()ed here */
30933e230dd2SCorentin Chary }
30943e230dd2SCorentin Chary 
309504d2529dSDaniel P. Berrange static gboolean vnc_listen_io(QIOChannel *ioc,
309604d2529dSDaniel P. Berrange                               GIOCondition condition,
309704d2529dSDaniel P. Berrange                               void *opaque)
30983e230dd2SCorentin Chary {
30993e230dd2SCorentin Chary     VncDisplay *vs = opaque;
310004d2529dSDaniel P. Berrange     QIOChannelSocket *sioc = NULL;
310104d2529dSDaniel P. Berrange     Error *err = NULL;
31023e230dd2SCorentin Chary 
31033e230dd2SCorentin Chary     /* Catch-up */
31041d0d59feSGerd Hoffmann     graphic_hw_update(vs->dcl.con);
310504d2529dSDaniel P. Berrange     sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), &err);
310604d2529dSDaniel P. Berrange     if (sioc != NULL) {
310704d2529dSDaniel P. Berrange         qio_channel_set_delay(QIO_CHANNEL(sioc), false);
310804d2529dSDaniel P. Berrange         vnc_connect(vs, sioc, false,
310904d2529dSDaniel P. Berrange                     ioc != QIO_CHANNEL(vs->lsock));
311004d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
31118e9b0d24SDaniel P. Berrange     } else {
311204d2529dSDaniel P. Berrange         /* client probably closed connection before we got there */
311304d2529dSDaniel P. Berrange         error_free(err);
31147536ee4bSTim Hardeck     }
31153e230dd2SCorentin Chary 
311604d2529dSDaniel P. Berrange     return TRUE;
31177536ee4bSTim Hardeck }
31187536ee4bSTim Hardeck 
31197c20b4a3SGerd Hoffmann static const DisplayChangeListenerOps dcl_ops = {
31207c20b4a3SGerd Hoffmann     .dpy_name             = "vnc",
31210f7b2864SGerd Hoffmann     .dpy_refresh          = vnc_refresh,
31227c20b4a3SGerd Hoffmann     .dpy_gfx_copy         = vnc_dpy_copy,
31237c20b4a3SGerd Hoffmann     .dpy_gfx_update       = vnc_dpy_update,
3124c12aeb86SGerd Hoffmann     .dpy_gfx_switch       = vnc_dpy_switch,
312534da30afSBenjamin Herrenschmidt     .dpy_gfx_check_format = qemu_pixman_check_format,
31267c20b4a3SGerd Hoffmann     .dpy_mouse_set        = vnc_mouse_set,
31277c20b4a3SGerd Hoffmann     .dpy_cursor_define    = vnc_dpy_cursor_define,
31287c20b4a3SGerd Hoffmann };
31297c20b4a3SGerd Hoffmann 
313014f7143eSGerd Hoffmann void vnc_display_init(const char *id)
31313e230dd2SCorentin Chary {
31324db14629SGerd Hoffmann     VncDisplay *vs;
31334db14629SGerd Hoffmann 
31344db14629SGerd Hoffmann     if (vnc_display_find(id) != NULL) {
31354db14629SGerd Hoffmann         return;
31364db14629SGerd Hoffmann     }
31374db14629SGerd Hoffmann     vs = g_malloc0(sizeof(*vs));
31383e230dd2SCorentin Chary 
313914f7143eSGerd Hoffmann     vs->id = strdup(id);
3140d616ccc5SGerd Hoffmann     QTAILQ_INSERT_TAIL(&vnc_displays, vs, next);
31413e230dd2SCorentin Chary 
31423e230dd2SCorentin Chary     QTAILQ_INIT(&vs->clients);
31433c9405a0SGerd Hoffmann     vs->expires = TIME_MAX;
31443e230dd2SCorentin Chary 
314540066175SGerd Hoffmann     if (keyboard_layout) {
314640066175SGerd Hoffmann         trace_vnc_key_map_init(keyboard_layout);
31473e230dd2SCorentin Chary         vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
314840066175SGerd Hoffmann     } else {
31493e230dd2SCorentin Chary         vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
315040066175SGerd Hoffmann     }
31513e230dd2SCorentin Chary 
31523e230dd2SCorentin Chary     if (!vs->kbd_layout)
31533e230dd2SCorentin Chary         exit(1);
31543e230dd2SCorentin Chary 
315512e29b16SDaniel P. Berrange     vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
315612e29b16SDaniel P. Berrange     vs->connections_limit = 32;
315712e29b16SDaniel P. Berrange 
3158bd023f95SCorentin Chary     qemu_mutex_init(&vs->mutex);
3159bd023f95SCorentin Chary     vnc_start_worker_thread();
3160bd023f95SCorentin Chary 
316121ef45d7SGerd Hoffmann     vs->dcl.ops = &dcl_ops;
31625209089fSGerd Hoffmann     register_displaychangelistener(&vs->dcl);
31633e230dd2SCorentin Chary }
31643e230dd2SCorentin Chary 
31653e230dd2SCorentin Chary 
316614f7143eSGerd Hoffmann static void vnc_display_close(VncDisplay *vs)
31673e230dd2SCorentin Chary {
31683e230dd2SCorentin Chary     if (!vs)
31693e230dd2SCorentin Chary         return;
3170bf7aa45eSGerd Hoffmann     vs->enabled = false;
3171bf7aa45eSGerd Hoffmann     vs->is_unix = false;
317204d2529dSDaniel P. Berrange     if (vs->lsock != NULL) {
317304d2529dSDaniel P. Berrange         if (vs->lsock_tag) {
317404d2529dSDaniel P. Berrange             g_source_remove(vs->lsock_tag);
317504d2529dSDaniel P. Berrange         }
317604d2529dSDaniel P. Berrange         object_unref(OBJECT(vs->lsock));
317704d2529dSDaniel P. Berrange         vs->lsock = NULL;
31783e230dd2SCorentin Chary     }
3179bf7aa45eSGerd Hoffmann     vs->ws_enabled = false;
318004d2529dSDaniel P. Berrange     if (vs->lwebsock != NULL) {
318104d2529dSDaniel P. Berrange         if (vs->lwebsock_tag) {
318204d2529dSDaniel P. Berrange             g_source_remove(vs->lwebsock_tag);
318304d2529dSDaniel P. Berrange         }
318404d2529dSDaniel P. Berrange         object_unref(OBJECT(vs->lwebsock));
318504d2529dSDaniel P. Berrange         vs->lwebsock = NULL;
31867536ee4bSTim Hardeck     }
31873e230dd2SCorentin Chary     vs->auth = VNC_AUTH_INVALID;
31883e230dd2SCorentin Chary     vs->subauth = VNC_AUTH_INVALID;
31893e305e4aSDaniel P. Berrange     if (vs->tlscreds) {
31903e305e4aSDaniel P. Berrange         object_unparent(OBJECT(vs->tlscreds));
319167c4c2bdSWolfgang Bumiller         vs->tlscreds = NULL;
31923e305e4aSDaniel P. Berrange     }
31933e305e4aSDaniel P. Berrange     g_free(vs->tlsaclname);
31943e305e4aSDaniel P. Berrange     vs->tlsaclname = NULL;
31953e230dd2SCorentin Chary }
31963e230dd2SCorentin Chary 
319714f7143eSGerd Hoffmann int vnc_display_password(const char *id, const char *password)
31981cd20f8bSAnthony Liguori {
319914f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
32001cd20f8bSAnthony Liguori 
32011cd20f8bSAnthony Liguori     if (!vs) {
3202a6aa9d3eSLuiz Capitulino         return -EINVAL;
32031cd20f8bSAnthony Liguori     }
3204cf864569SGerd Hoffmann     if (vs->auth == VNC_AUTH_NONE) {
3205cf864569SGerd Hoffmann         error_printf_unless_qmp("If you want use passwords please enable "
32067ea7d36eSMarkus Armbruster                                 "password auth using '-vnc ${dpy},password'.\n");
3207cf864569SGerd Hoffmann         return -EINVAL;
32081cd20f8bSAnthony Liguori     }
32091cd20f8bSAnthony Liguori 
32107267c094SAnthony Liguori     g_free(vs->password);
32117267c094SAnthony Liguori     vs->password = g_strdup(password);
3212a6aa9d3eSLuiz Capitulino 
3213a6aa9d3eSLuiz Capitulino     return 0;
32143e230dd2SCorentin Chary }
32153e230dd2SCorentin Chary 
321614f7143eSGerd Hoffmann int vnc_display_pw_expire(const char *id, time_t expires)
32173c9405a0SGerd Hoffmann {
321814f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
32193c9405a0SGerd Hoffmann 
32201643f2b2SGerd Hoffmann     if (!vs) {
32211643f2b2SGerd Hoffmann         return -EINVAL;
32221643f2b2SGerd Hoffmann     }
32231643f2b2SGerd Hoffmann 
32243c9405a0SGerd Hoffmann     vs->expires = expires;
32253c9405a0SGerd Hoffmann     return 0;
32263c9405a0SGerd Hoffmann }
32273c9405a0SGerd Hoffmann 
322833df7bf3SPaolo Bonzini static void vnc_display_print_local_addr(VncDisplay *vs)
32293e230dd2SCorentin Chary {
323004d2529dSDaniel P. Berrange     SocketAddress *addr;
323104d2529dSDaniel P. Berrange     Error *err = NULL;
32323e230dd2SCorentin Chary 
323304d2529dSDaniel P. Berrange     addr = qio_channel_socket_get_local_address(vs->lsock, &err);
323404d2529dSDaniel P. Berrange     if (!addr) {
323533df7bf3SPaolo Bonzini         return;
323604d2529dSDaniel P. Berrange     }
323704d2529dSDaniel P. Berrange 
323804d2529dSDaniel P. Berrange     if (addr->type != SOCKET_ADDRESS_KIND_INET) {
323904d2529dSDaniel P. Berrange         qapi_free_SocketAddress(addr);
324033df7bf3SPaolo Bonzini         return;
324104d2529dSDaniel P. Berrange     }
324233df7bf3SPaolo Bonzini     error_printf_unless_qmp("VNC server running on %s:%s\n",
324333df7bf3SPaolo Bonzini                             addr->u.inet.data->host,
324432bafa8fSEric Blake                             addr->u.inet.data->port);
324504d2529dSDaniel P. Berrange     qapi_free_SocketAddress(addr);
32463e230dd2SCorentin Chary }
32473e230dd2SCorentin Chary 
32484db14629SGerd Hoffmann static QemuOptsList qemu_vnc_opts = {
32494db14629SGerd Hoffmann     .name = "vnc",
32504db14629SGerd Hoffmann     .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
32514db14629SGerd Hoffmann     .implied_opt_name = "vnc",
32524db14629SGerd Hoffmann     .desc = {
32534db14629SGerd Hoffmann         {
32544db14629SGerd Hoffmann             .name = "vnc",
32554db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32564db14629SGerd Hoffmann         },{
32574db14629SGerd Hoffmann             .name = "websocket",
32584db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32594db14629SGerd Hoffmann         },{
32603e305e4aSDaniel P. Berrange             .name = "tls-creds",
32613e305e4aSDaniel P. Berrange             .type = QEMU_OPT_STRING,
32623e305e4aSDaniel P. Berrange         },{
32633e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
32644db14629SGerd Hoffmann             .name = "x509",
32654db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32664db14629SGerd Hoffmann         },{
32674db14629SGerd Hoffmann             .name = "share",
32684db14629SGerd Hoffmann             .type = QEMU_OPT_STRING,
32694db14629SGerd Hoffmann         },{
32701d0d59feSGerd Hoffmann             .name = "display",
32711d0d59feSGerd Hoffmann             .type = QEMU_OPT_STRING,
32721d0d59feSGerd Hoffmann         },{
32731d0d59feSGerd Hoffmann             .name = "head",
32741d0d59feSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
32751d0d59feSGerd Hoffmann         },{
3276e5f34cddSGerd Hoffmann             .name = "connections",
3277e5f34cddSGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3278e5f34cddSGerd Hoffmann         },{
327988428b7aSGonglei             .name = "to",
328088428b7aSGonglei             .type = QEMU_OPT_NUMBER,
328188428b7aSGonglei         },{
328288428b7aSGonglei             .name = "ipv4",
328388428b7aSGonglei             .type = QEMU_OPT_BOOL,
328488428b7aSGonglei         },{
328588428b7aSGonglei             .name = "ipv6",
328688428b7aSGonglei             .type = QEMU_OPT_BOOL,
328788428b7aSGonglei         },{
32884db14629SGerd Hoffmann             .name = "password",
32894db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32904db14629SGerd Hoffmann         },{
32914db14629SGerd Hoffmann             .name = "reverse",
32924db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32934db14629SGerd Hoffmann         },{
32944db14629SGerd Hoffmann             .name = "lock-key-sync",
32954db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
32964db14629SGerd Hoffmann         },{
3297c5ce8333SGerd Hoffmann             .name = "key-delay-ms",
3298c5ce8333SGerd Hoffmann             .type = QEMU_OPT_NUMBER,
3299c5ce8333SGerd Hoffmann         },{
33004db14629SGerd Hoffmann             .name = "sasl",
33014db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33024db14629SGerd Hoffmann         },{
33033e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33044db14629SGerd Hoffmann             .name = "tls",
33054db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33064db14629SGerd Hoffmann         },{
33073e305e4aSDaniel P. Berrange             /* Deprecated in favour of tls-creds */
33084db14629SGerd Hoffmann             .name = "x509verify",
33098c7d0645SDaniel P. Berrange             .type = QEMU_OPT_STRING,
33104db14629SGerd Hoffmann         },{
33114db14629SGerd Hoffmann             .name = "acl",
33124db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33134db14629SGerd Hoffmann         },{
33144db14629SGerd Hoffmann             .name = "lossy",
33154db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33164db14629SGerd Hoffmann         },{
33174db14629SGerd Hoffmann             .name = "non-adaptive",
33184db14629SGerd Hoffmann             .type = QEMU_OPT_BOOL,
33194db14629SGerd Hoffmann         },
33204db14629SGerd Hoffmann         { /* end of list */ }
33214db14629SGerd Hoffmann     },
33224db14629SGerd Hoffmann };
33234db14629SGerd Hoffmann 
33240dd72e15SDaniel P. Berrange 
33253e305e4aSDaniel P. Berrange static int
33260dd72e15SDaniel P. Berrange vnc_display_setup_auth(VncDisplay *vs,
33270dd72e15SDaniel P. Berrange                        bool password,
33280dd72e15SDaniel P. Berrange                        bool sasl,
33293e305e4aSDaniel P. Berrange                        bool websocket,
33303e305e4aSDaniel P. Berrange                        Error **errp)
33310dd72e15SDaniel P. Berrange {
33320dd72e15SDaniel P. Berrange     /*
33330dd72e15SDaniel P. Berrange      * We have a choice of 3 authentication options
33340dd72e15SDaniel P. Berrange      *
33350dd72e15SDaniel P. Berrange      *   1. none
33360dd72e15SDaniel P. Berrange      *   2. vnc
33370dd72e15SDaniel P. Berrange      *   3. sasl
33380dd72e15SDaniel P. Berrange      *
33390dd72e15SDaniel P. Berrange      * The channel can be run in 2 modes
33400dd72e15SDaniel P. Berrange      *
33410dd72e15SDaniel P. Berrange      *   1. clear
33420dd72e15SDaniel P. Berrange      *   2. tls
33430dd72e15SDaniel P. Berrange      *
33440dd72e15SDaniel P. Berrange      * And TLS can use 2 types of credentials
33450dd72e15SDaniel P. Berrange      *
33460dd72e15SDaniel P. Berrange      *   1. anon
33470dd72e15SDaniel P. Berrange      *   2. x509
33480dd72e15SDaniel P. Berrange      *
33490dd72e15SDaniel P. Berrange      * We thus have 9 possible logical combinations
33500dd72e15SDaniel P. Berrange      *
33510dd72e15SDaniel P. Berrange      *   1. clear + none
33520dd72e15SDaniel P. Berrange      *   2. clear + vnc
33530dd72e15SDaniel P. Berrange      *   3. clear + sasl
33540dd72e15SDaniel P. Berrange      *   4. tls + anon + none
33550dd72e15SDaniel P. Berrange      *   5. tls + anon + vnc
33560dd72e15SDaniel P. Berrange      *   6. tls + anon + sasl
33570dd72e15SDaniel P. Berrange      *   7. tls + x509 + none
33580dd72e15SDaniel P. Berrange      *   8. tls + x509 + vnc
33590dd72e15SDaniel P. Berrange      *   9. tls + x509 + sasl
33600dd72e15SDaniel P. Berrange      *
33610dd72e15SDaniel P. Berrange      * These need to be mapped into the VNC auth schemes
33620dd72e15SDaniel P. Berrange      * in an appropriate manner. In regular VNC, all the
33630dd72e15SDaniel P. Berrange      * TLS options get mapped into VNC_AUTH_VENCRYPT
33640dd72e15SDaniel P. Berrange      * sub-auth types.
3365f9148c8aSDaniel P. Berrange      *
3366f9148c8aSDaniel P. Berrange      * In websockets, the https:// protocol already provides
3367f9148c8aSDaniel P. Berrange      * TLS support, so there is no need to make use of the
3368f9148c8aSDaniel P. Berrange      * VeNCrypt extension. Furthermore, websockets browser
3369f9148c8aSDaniel P. Berrange      * clients could not use VeNCrypt even if they wanted to,
3370f9148c8aSDaniel P. Berrange      * as they cannot control when the TLS handshake takes
3371f9148c8aSDaniel P. Berrange      * place. Thus there is no option but to rely on https://,
3372f9148c8aSDaniel P. Berrange      * meaning combinations 4->6 and 7->9 will be mapped to
3373f9148c8aSDaniel P. Berrange      * VNC auth schemes in the same way as combos 1->3.
3374f9148c8aSDaniel P. Berrange      *
3375f9148c8aSDaniel P. Berrange      * Regardless of fact that we have a different mapping to
3376f9148c8aSDaniel P. Berrange      * VNC auth mechs for plain VNC vs websockets VNC, the end
3377f9148c8aSDaniel P. Berrange      * result has the same security characteristics.
33780dd72e15SDaniel P. Berrange      */
33790dd72e15SDaniel P. Berrange     if (password) {
33803e305e4aSDaniel P. Berrange         if (vs->tlscreds) {
33810dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VENCRYPT;
3382f9148c8aSDaniel P. Berrange             if (websocket) {
3383f9148c8aSDaniel P. Berrange                 vs->ws_tls = true;
3384f9148c8aSDaniel P. Berrange             }
33853e305e4aSDaniel P. Berrange             if (object_dynamic_cast(OBJECT(vs->tlscreds),
33863e305e4aSDaniel P. Berrange                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
33870dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
33880dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
33893e305e4aSDaniel P. Berrange             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
33903e305e4aSDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
33910dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
33920dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
33933e305e4aSDaniel P. Berrange             } else {
33943e305e4aSDaniel P. Berrange                 error_setg(errp,
33953e305e4aSDaniel P. Berrange                            "Unsupported TLS cred type %s",
33963e305e4aSDaniel P. Berrange                            object_get_typename(OBJECT(vs->tlscreds)));
33973e305e4aSDaniel P. Berrange                 return -1;
33980dd72e15SDaniel P. Berrange             }
33990dd72e15SDaniel P. Berrange         } else {
34000dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with password auth\n");
34010dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VNC;
34020dd72e15SDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
34030dd72e15SDaniel P. Berrange         }
3404f9148c8aSDaniel P. Berrange         if (websocket) {
3405f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_VNC;
3406f9148c8aSDaniel P. Berrange         } else {
3407f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_INVALID;
3408f9148c8aSDaniel P. Berrange         }
34090dd72e15SDaniel P. Berrange     } else if (sasl) {
34103e305e4aSDaniel P. Berrange         if (vs->tlscreds) {
34110dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VENCRYPT;
3412f9148c8aSDaniel P. Berrange             if (websocket) {
3413f9148c8aSDaniel P. Berrange                 vs->ws_tls = true;
3414f9148c8aSDaniel P. Berrange             }
34153e305e4aSDaniel P. Berrange             if (object_dynamic_cast(OBJECT(vs->tlscreds),
34163e305e4aSDaniel P. Berrange                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
34170dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
34180dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
34193e305e4aSDaniel P. Berrange             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
34203e305e4aSDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
34210dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
34220dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
34233e305e4aSDaniel P. Berrange             } else {
34243e305e4aSDaniel P. Berrange                 error_setg(errp,
34253e305e4aSDaniel P. Berrange                            "Unsupported TLS cred type %s",
34263e305e4aSDaniel P. Berrange                            object_get_typename(OBJECT(vs->tlscreds)));
34273e305e4aSDaniel P. Berrange                 return -1;
34280dd72e15SDaniel P. Berrange             }
34290dd72e15SDaniel P. Berrange         } else {
34300dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with SASL auth\n");
34310dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_SASL;
34320dd72e15SDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
34330dd72e15SDaniel P. Berrange         }
3434f9148c8aSDaniel P. Berrange         if (websocket) {
3435f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_SASL;
3436f9148c8aSDaniel P. Berrange         } else {
3437f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_INVALID;
3438f9148c8aSDaniel P. Berrange         }
34390dd72e15SDaniel P. Berrange     } else {
34403e305e4aSDaniel P. Berrange         if (vs->tlscreds) {
34410dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_VENCRYPT;
3442f9148c8aSDaniel P. Berrange             if (websocket) {
3443f9148c8aSDaniel P. Berrange                 vs->ws_tls = true;
3444f9148c8aSDaniel P. Berrange             }
34453e305e4aSDaniel P. Berrange             if (object_dynamic_cast(OBJECT(vs->tlscreds),
34463e305e4aSDaniel P. Berrange                                     TYPE_QCRYPTO_TLS_CREDS_X509)) {
34470dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
34480dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
34493e305e4aSDaniel P. Berrange             } else if (object_dynamic_cast(OBJECT(vs->tlscreds),
34503e305e4aSDaniel P. Berrange                                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
34510dd72e15SDaniel P. Berrange                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
34520dd72e15SDaniel P. Berrange                 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
34533e305e4aSDaniel P. Berrange             } else {
34543e305e4aSDaniel P. Berrange                 error_setg(errp,
34553e305e4aSDaniel P. Berrange                            "Unsupported TLS cred type %s",
34563e305e4aSDaniel P. Berrange                            object_get_typename(OBJECT(vs->tlscreds)));
34573e305e4aSDaniel P. Berrange                 return -1;
34580dd72e15SDaniel P. Berrange             }
34590dd72e15SDaniel P. Berrange         } else {
34600dd72e15SDaniel P. Berrange             VNC_DEBUG("Initializing VNC server with no auth\n");
34610dd72e15SDaniel P. Berrange             vs->auth = VNC_AUTH_NONE;
34620dd72e15SDaniel P. Berrange             vs->subauth = VNC_AUTH_INVALID;
34630dd72e15SDaniel P. Berrange         }
3464f9148c8aSDaniel P. Berrange         if (websocket) {
3465f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_NONE;
3466f9148c8aSDaniel P. Berrange         } else {
3467f9148c8aSDaniel P. Berrange             vs->ws_auth = VNC_AUTH_INVALID;
3468f9148c8aSDaniel P. Berrange         }
34690dd72e15SDaniel P. Berrange     }
34703e305e4aSDaniel P. Berrange     return 0;
34710dd72e15SDaniel P. Berrange }
34720dd72e15SDaniel P. Berrange 
34733e305e4aSDaniel P. Berrange 
34743e305e4aSDaniel P. Berrange /*
34753e305e4aSDaniel P. Berrange  * Handle back compat with old CLI syntax by creating some
34763e305e4aSDaniel P. Berrange  * suitable QCryptoTLSCreds objects
34773e305e4aSDaniel P. Berrange  */
34783e305e4aSDaniel P. Berrange static QCryptoTLSCreds *
34793e305e4aSDaniel P. Berrange vnc_display_create_creds(bool x509,
34803e305e4aSDaniel P. Berrange                          bool x509verify,
34813e305e4aSDaniel P. Berrange                          const char *dir,
34823e305e4aSDaniel P. Berrange                          const char *id,
34833e305e4aSDaniel P. Berrange                          Error **errp)
34843e305e4aSDaniel P. Berrange {
34853e305e4aSDaniel P. Berrange     gchar *credsid = g_strdup_printf("tlsvnc%s", id);
34863e305e4aSDaniel P. Berrange     Object *parent = object_get_objects_root();
34873e305e4aSDaniel P. Berrange     Object *creds;
34883e305e4aSDaniel P. Berrange     Error *err = NULL;
34893e305e4aSDaniel P. Berrange 
34903e305e4aSDaniel P. Berrange     if (x509) {
34913e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_X509,
34923e305e4aSDaniel P. Berrange                                       parent,
34933e305e4aSDaniel P. Berrange                                       credsid,
34943e305e4aSDaniel P. Berrange                                       &err,
34953e305e4aSDaniel P. Berrange                                       "endpoint", "server",
34963e305e4aSDaniel P. Berrange                                       "dir", dir,
34973e305e4aSDaniel P. Berrange                                       "verify-peer", x509verify ? "yes" : "no",
34983e305e4aSDaniel P. Berrange                                       NULL);
34993e305e4aSDaniel P. Berrange     } else {
35003e305e4aSDaniel P. Berrange         creds = object_new_with_props(TYPE_QCRYPTO_TLS_CREDS_ANON,
35013e305e4aSDaniel P. Berrange                                       parent,
35023e305e4aSDaniel P. Berrange                                       credsid,
35033e305e4aSDaniel P. Berrange                                       &err,
35043e305e4aSDaniel P. Berrange                                       "endpoint", "server",
35053e305e4aSDaniel P. Berrange                                       NULL);
35063e305e4aSDaniel P. Berrange     }
35073e305e4aSDaniel P. Berrange 
35083e305e4aSDaniel P. Berrange     g_free(credsid);
35093e305e4aSDaniel P. Berrange 
35103e305e4aSDaniel P. Berrange     if (err) {
35113e305e4aSDaniel P. Berrange         error_propagate(errp, err);
35123e305e4aSDaniel P. Berrange         return NULL;
35133e305e4aSDaniel P. Berrange     }
35143e305e4aSDaniel P. Berrange 
35153e305e4aSDaniel P. Berrange     return QCRYPTO_TLS_CREDS(creds);
35163e305e4aSDaniel P. Berrange }
35173e305e4aSDaniel P. Berrange 
35183e305e4aSDaniel P. Berrange 
35194db14629SGerd Hoffmann void vnc_display_open(const char *id, Error **errp)
35203e230dd2SCorentin Chary {
352114f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
35224db14629SGerd Hoffmann     QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3523e0d03b8cSDaniel P. Berrange     SocketAddress *saddr = NULL, *wsaddr = NULL;
3524e2a11d9dSGonglei     const char *share, *device_id;
35251d0d59feSGerd Hoffmann     QemuConsole *con;
3526a2c72de0SGonglei     bool password = false;
3527a2c72de0SGonglei     bool reverse = false;
3528e2a11d9dSGonglei     const char *vnc;
3529e5560329SGerd Hoffmann     char *h;
35303e305e4aSDaniel P. Berrange     const char *credid;
353133df7bf3SPaolo Bonzini     int show_vnc_port = 0;
3532a2c72de0SGonglei     bool sasl = false;
3533d169f04bSDaniel P. Berrange #ifdef CONFIG_VNC_SASL
35343e230dd2SCorentin Chary     int saslErr;
35353e230dd2SCorentin Chary #endif
35363e230dd2SCorentin Chary     int acl = 0;
35373e230dd2SCorentin Chary     int lock_key_sync = 1;
3538c5ce8333SGerd Hoffmann     int key_delay_ms;
35393e230dd2SCorentin Chary 
3540d616ccc5SGerd Hoffmann     if (!vs) {
35412d55f0e8SPaolo Bonzini         error_setg(errp, "VNC display not active");
35422d55f0e8SPaolo Bonzini         return;
35432d55f0e8SPaolo Bonzini     }
354414f7143eSGerd Hoffmann     vnc_display_close(vs);
35454db14629SGerd Hoffmann 
35464db14629SGerd Hoffmann     if (!opts) {
35472d55f0e8SPaolo Bonzini         return;
35484db14629SGerd Hoffmann     }
3549e2a11d9dSGonglei     vnc = qemu_opt_get(opts, "vnc");
3550e2a11d9dSGonglei     if (!vnc || strcmp(vnc, "none") == 0) {
35514db14629SGerd Hoffmann         return;
35524db14629SGerd Hoffmann     }
3553e2a11d9dSGonglei 
3554e5560329SGerd Hoffmann     h = strrchr(vnc, ':');
3555e5560329SGerd Hoffmann     if (h) {
3556274c3b52SJán Tomko         size_t hlen = h - vnc;
3557274c3b52SJán Tomko 
3558e0d03b8cSDaniel P. Berrange         const char *websocket = qemu_opt_get(opts, "websocket");
3559e0d03b8cSDaniel P. Berrange         int to = qemu_opt_get_number(opts, "to", 0);
35603f0230e9SDaniel P. Berrange         bool has_ipv4 = qemu_opt_get(opts, "ipv4");
35613f0230e9SDaniel P. Berrange         bool has_ipv6 = qemu_opt_get(opts, "ipv6");
35623f0230e9SDaniel P. Berrange         bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
35633f0230e9SDaniel P. Berrange         bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3564e0d03b8cSDaniel P. Berrange 
3565e0d03b8cSDaniel P. Berrange         saddr = g_new0(SocketAddress, 1);
3566e0d03b8cSDaniel P. Berrange         if (websocket) {
3567e0d03b8cSDaniel P. Berrange             if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3568e0d03b8cSDaniel P. Berrange                 error_setg(errp,
3569e0d03b8cSDaniel P. Berrange                            "SHA1 hash support is required for websockets");
3570e5560329SGerd Hoffmann                 goto fail;
3571e2a11d9dSGonglei             }
3572e5560329SGerd Hoffmann 
3573e0d03b8cSDaniel P. Berrange             wsaddr = g_new0(SocketAddress, 1);
3574e0d03b8cSDaniel P. Berrange             vs->ws_enabled = true;
3575e5560329SGerd Hoffmann         }
3576e0d03b8cSDaniel P. Berrange 
3577e0d03b8cSDaniel P. Berrange         if (strncmp(vnc, "unix:", 5) == 0) {
35782d32addaSEric Blake             saddr->type = SOCKET_ADDRESS_KIND_UNIX;
357932bafa8fSEric Blake             saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
358032bafa8fSEric Blake             saddr->u.q_unix.data->path = g_strdup(vnc + 5);
3581e0d03b8cSDaniel P. Berrange 
3582e0d03b8cSDaniel P. Berrange             if (vs->ws_enabled) {
3583e0d03b8cSDaniel P. Berrange                 error_setg(errp, "UNIX sockets not supported with websock");
3584e0d03b8cSDaniel P. Berrange                 goto fail;
3585e5560329SGerd Hoffmann             }
3586e0d03b8cSDaniel P. Berrange         } else {
3587e0d03b8cSDaniel P. Berrange             unsigned long long baseport;
35880399293eSEric Blake             InetSocketAddress *inet;
35892d32addaSEric Blake             saddr->type = SOCKET_ADDRESS_KIND_INET;
359032bafa8fSEric Blake             inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
3591e0d03b8cSDaniel P. Berrange             if (vnc[0] == '[' && vnc[hlen - 1] == ']') {
35920399293eSEric Blake                 inet->host = g_strndup(vnc + 1, hlen - 2);
3593e0d03b8cSDaniel P. Berrange             } else {
35940399293eSEric Blake                 inet->host = g_strndup(vnc, hlen);
3595e0d03b8cSDaniel P. Berrange             }
3596e0d03b8cSDaniel P. Berrange             if (parse_uint_full(h + 1, &baseport, 10) < 0) {
3597e0d03b8cSDaniel P. Berrange                 error_setg(errp, "can't convert to a number: %s", h + 1);
3598e0d03b8cSDaniel P. Berrange                 goto fail;
3599e0d03b8cSDaniel P. Berrange             }
3600e0d03b8cSDaniel P. Berrange             if (baseport > 65535 ||
3601e0d03b8cSDaniel P. Berrange                 baseport + 5900 > 65535) {
3602e0d03b8cSDaniel P. Berrange                 error_setg(errp, "port %s out of range", h + 1);
3603e0d03b8cSDaniel P. Berrange                 goto fail;
3604e0d03b8cSDaniel P. Berrange             }
36050399293eSEric Blake             inet->port = g_strdup_printf(
3606e0d03b8cSDaniel P. Berrange                 "%d", (int)baseport + 5900);
3607e0d03b8cSDaniel P. Berrange 
3608e0d03b8cSDaniel P. Berrange             if (to) {
36090399293eSEric Blake                 inet->has_to = true;
36100399293eSEric Blake                 inet->to = to + 5900;
361133df7bf3SPaolo Bonzini                 show_vnc_port = 1;
3612e0d03b8cSDaniel P. Berrange             }
36130399293eSEric Blake             inet->ipv4 = ipv4;
36140399293eSEric Blake             inet->has_ipv4 = has_ipv4;
36150399293eSEric Blake             inet->ipv6 = ipv6;
36160399293eSEric Blake             inet->has_ipv6 = has_ipv6;
3617e0d03b8cSDaniel P. Berrange 
3618e0d03b8cSDaniel P. Berrange             if (vs->ws_enabled) {
36192d32addaSEric Blake                 wsaddr->type = SOCKET_ADDRESS_KIND_INET;
362032bafa8fSEric Blake                 inet = wsaddr->u.inet.data = g_new0(InetSocketAddress, 1);
362132bafa8fSEric Blake                 inet->host = g_strdup(saddr->u.inet.data->host);
36220399293eSEric Blake                 inet->port = g_strdup(websocket);
3623e0d03b8cSDaniel P. Berrange 
3624e0d03b8cSDaniel P. Berrange                 if (to) {
36250399293eSEric Blake                     inet->has_to = true;
36260399293eSEric Blake                     inet->to = to;
3627e0d03b8cSDaniel P. Berrange                 }
36280399293eSEric Blake                 inet->ipv4 = ipv4;
36290399293eSEric Blake                 inet->has_ipv4 = has_ipv4;
36300399293eSEric Blake                 inet->ipv6 = ipv6;
36310399293eSEric Blake                 inet->has_ipv6 = has_ipv6;
3632e0d03b8cSDaniel P. Berrange             }
3633e0d03b8cSDaniel P. Berrange         }
3634e0d03b8cSDaniel P. Berrange     } else {
3635e0d03b8cSDaniel P. Berrange         error_setg(errp, "no vnc port specified");
3636e0d03b8cSDaniel P. Berrange         goto fail;
3637e5560329SGerd Hoffmann     }
36383e230dd2SCorentin Chary 
36394db14629SGerd Hoffmann     password = qemu_opt_get_bool(opts, "password", false);
3640800567a6SDaniel P. Berrange     if (password) {
3641800567a6SDaniel P. Berrange         if (fips_get_state()) {
36422d55f0e8SPaolo Bonzini             error_setg(errp,
36430f66998fSPaul Moore                        "VNC password auth disabled due to FIPS mode, "
36440f66998fSPaul Moore                        "consider using the VeNCrypt or SASL authentication "
36452d55f0e8SPaolo Bonzini                        "methods as an alternative");
36461ce52c78SPaolo Bonzini             goto fail;
36470f66998fSPaul Moore         }
3648800567a6SDaniel P. Berrange         if (!qcrypto_cipher_supports(
3649800567a6SDaniel P. Berrange                 QCRYPTO_CIPHER_ALG_DES_RFB)) {
3650800567a6SDaniel P. Berrange             error_setg(errp,
3651800567a6SDaniel P. Berrange                        "Cipher backend does not support DES RFB algorithm");
3652800567a6SDaniel P. Berrange             goto fail;
3653800567a6SDaniel P. Berrange         }
3654800567a6SDaniel P. Berrange     }
36554db14629SGerd Hoffmann 
36564db14629SGerd Hoffmann     reverse = qemu_opt_get_bool(opts, "reverse", false);
36574db14629SGerd Hoffmann     lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3658c5ce8333SGerd Hoffmann     key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 1);
36594db14629SGerd Hoffmann     sasl = qemu_opt_get_bool(opts, "sasl", false);
3660d169f04bSDaniel P. Berrange #ifndef CONFIG_VNC_SASL
3661d169f04bSDaniel P. Berrange     if (sasl) {
3662d169f04bSDaniel P. Berrange         error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3663d169f04bSDaniel P. Berrange         goto fail;
3664d169f04bSDaniel P. Berrange     }
3665d169f04bSDaniel P. Berrange #endif /* CONFIG_VNC_SASL */
36663e305e4aSDaniel P. Berrange     credid = qemu_opt_get(opts, "tls-creds");
36673e305e4aSDaniel P. Berrange     if (credid) {
36683e305e4aSDaniel P. Berrange         Object *creds;
36693e305e4aSDaniel P. Berrange         if (qemu_opt_get(opts, "tls") ||
36703e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509") ||
36713e305e4aSDaniel P. Berrange             qemu_opt_get(opts, "x509verify")) {
36723e305e4aSDaniel P. Berrange             error_setg(errp,
3673c62e90afSWolfgang Bumiller                        "'tls-creds' parameter is mutually exclusive with "
36743e305e4aSDaniel P. Berrange                        "'tls', 'x509' and 'x509verify' parameters");
36753e305e4aSDaniel P. Berrange             goto fail;
36763e305e4aSDaniel P. Berrange         }
36773e305e4aSDaniel P. Berrange 
36783e305e4aSDaniel P. Berrange         creds = object_resolve_path_component(
36793e305e4aSDaniel P. Berrange             object_get_objects_root(), credid);
36803e305e4aSDaniel P. Berrange         if (!creds) {
36813e305e4aSDaniel P. Berrange             error_setg(errp, "No TLS credentials with id '%s'",
36823e305e4aSDaniel P. Berrange                        credid);
36833e305e4aSDaniel P. Berrange             goto fail;
36843e305e4aSDaniel P. Berrange         }
36853e305e4aSDaniel P. Berrange         vs->tlscreds = (QCryptoTLSCreds *)
36863e305e4aSDaniel P. Berrange             object_dynamic_cast(creds,
36873e305e4aSDaniel P. Berrange                                 TYPE_QCRYPTO_TLS_CREDS);
36883e305e4aSDaniel P. Berrange         if (!vs->tlscreds) {
36893e305e4aSDaniel P. Berrange             error_setg(errp, "Object with id '%s' is not TLS credentials",
36903e305e4aSDaniel P. Berrange                        credid);
36913e305e4aSDaniel P. Berrange             goto fail;
36923e305e4aSDaniel P. Berrange         }
36933e305e4aSDaniel P. Berrange         object_ref(OBJECT(vs->tlscreds));
36943e305e4aSDaniel P. Berrange 
36953e305e4aSDaniel P. Berrange         if (vs->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
36963e305e4aSDaniel P. Berrange             error_setg(errp,
36973e305e4aSDaniel P. Berrange                        "Expecting TLS credentials with a server endpoint");
36983e305e4aSDaniel P. Berrange             goto fail;
36993e305e4aSDaniel P. Berrange         }
37003e305e4aSDaniel P. Berrange     } else {
37013e305e4aSDaniel P. Berrange         const char *path;
37023e305e4aSDaniel P. Berrange         bool tls = false, x509 = false, x509verify = false;
37034db14629SGerd Hoffmann         tls  = qemu_opt_get_bool(opts, "tls", false);
37043e305e4aSDaniel P. Berrange         if (tls) {
37054db14629SGerd Hoffmann             path = qemu_opt_get(opts, "x509");
37063e305e4aSDaniel P. Berrange 
37074db14629SGerd Hoffmann             if (path) {
3708a2c72de0SGonglei                 x509 = true;
37093e305e4aSDaniel P. Berrange             } else {
37103e305e4aSDaniel P. Berrange                 path = qemu_opt_get(opts, "x509verify");
37113e305e4aSDaniel P. Berrange                 if (path) {
37123e305e4aSDaniel P. Berrange                     x509 = true;
37133e305e4aSDaniel P. Berrange                     x509verify = true;
37143e305e4aSDaniel P. Berrange                 }
37153e305e4aSDaniel P. Berrange             }
37163e305e4aSDaniel P. Berrange             vs->tlscreds = vnc_display_create_creds(x509,
37173e305e4aSDaniel P. Berrange                                                     x509verify,
37183e305e4aSDaniel P. Berrange                                                     path,
37193e305e4aSDaniel P. Berrange                                                     vs->id,
37203e305e4aSDaniel P. Berrange                                                     errp);
37213e305e4aSDaniel P. Berrange             if (!vs->tlscreds) {
37221ce52c78SPaolo Bonzini                 goto fail;
37233e230dd2SCorentin Chary             }
37243e230dd2SCorentin Chary         }
3725d169f04bSDaniel P. Berrange     }
37264db14629SGerd Hoffmann     acl = qemu_opt_get_bool(opts, "acl", false);
37274db14629SGerd Hoffmann 
37284db14629SGerd Hoffmann     share = qemu_opt_get(opts, "share");
37294db14629SGerd Hoffmann     if (share) {
37304db14629SGerd Hoffmann         if (strcmp(share, "ignore") == 0) {
37318cf36489SGerd Hoffmann             vs->share_policy = VNC_SHARE_POLICY_IGNORE;
37324db14629SGerd Hoffmann         } else if (strcmp(share, "allow-exclusive") == 0) {
37338cf36489SGerd Hoffmann             vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
37344db14629SGerd Hoffmann         } else if (strcmp(share, "force-shared") == 0) {
37358cf36489SGerd Hoffmann             vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
37368cf36489SGerd Hoffmann         } else {
37372d55f0e8SPaolo Bonzini             error_setg(errp, "unknown vnc share= option");
37381ce52c78SPaolo Bonzini             goto fail;
37398cf36489SGerd Hoffmann         }
37404db14629SGerd Hoffmann     } else {
37414db14629SGerd Hoffmann         vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
37423e230dd2SCorentin Chary     }
3743e5f34cddSGerd Hoffmann     vs->connections_limit = qemu_opt_get_number(opts, "connections", 32);
37443e230dd2SCorentin Chary 
37454db14629SGerd Hoffmann #ifdef CONFIG_VNC_JPEG
37464db14629SGerd Hoffmann     vs->lossy = qemu_opt_get_bool(opts, "lossy", false);
37474db14629SGerd Hoffmann #endif
37484db14629SGerd Hoffmann     vs->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3749e22492d3SPeter Lieven     /* adaptive updates are only used with tight encoding and
3750e22492d3SPeter Lieven      * if lossy updates are enabled so we can disable all the
3751e22492d3SPeter Lieven      * calculations otherwise */
3752e22492d3SPeter Lieven     if (!vs->lossy) {
3753e22492d3SPeter Lieven         vs->non_adaptive = true;
3754e22492d3SPeter Lieven     }
3755e22492d3SPeter Lieven 
37563e305e4aSDaniel P. Berrange     if (acl) {
3757c8496408SGerd Hoffmann         if (strcmp(vs->id, "default") == 0) {
37583e305e4aSDaniel P. Berrange             vs->tlsaclname = g_strdup("vnc.x509dname");
3759c8496408SGerd Hoffmann         } else {
37603e305e4aSDaniel P. Berrange             vs->tlsaclname = g_strdup_printf("vnc.%s.x509dname", vs->id);
3761c8496408SGerd Hoffmann         }
37623e305e4aSDaniel P. Berrange         qemu_acl_init(vs->tlsaclname);
37633e230dd2SCorentin Chary     }
37643e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
37653e230dd2SCorentin Chary     if (acl && sasl) {
3766c8496408SGerd Hoffmann         char *aclname;
3767c8496408SGerd Hoffmann 
3768c8496408SGerd Hoffmann         if (strcmp(vs->id, "default") == 0) {
3769c8496408SGerd Hoffmann             aclname = g_strdup("vnc.username");
3770c8496408SGerd Hoffmann         } else {
3771c8496408SGerd Hoffmann             aclname = g_strdup_printf("vnc.%s.username", vs->id);
3772c8496408SGerd Hoffmann         }
3773c8496408SGerd Hoffmann         vs->sasl.acl = qemu_acl_init(aclname);
3774c8496408SGerd Hoffmann         g_free(aclname);
37753e230dd2SCorentin Chary     }
37763e230dd2SCorentin Chary #endif
37773e230dd2SCorentin Chary 
3778e0d03b8cSDaniel P. Berrange     if (vnc_display_setup_auth(vs, password, sasl, vs->ws_enabled, errp) < 0) {
37793e305e4aSDaniel P. Berrange         goto fail;
37803e305e4aSDaniel P. Berrange     }
37813e230dd2SCorentin Chary 
37823e230dd2SCorentin Chary #ifdef CONFIG_VNC_SASL
37833e230dd2SCorentin Chary     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
37842d55f0e8SPaolo Bonzini         error_setg(errp, "Failed to initialize SASL auth: %s",
37853e230dd2SCorentin Chary                    sasl_errstring(saslErr, NULL, NULL));
37861ce52c78SPaolo Bonzini         goto fail;
37873e230dd2SCorentin Chary     }
37883e230dd2SCorentin Chary #endif
37893e230dd2SCorentin Chary     vs->lock_key_sync = lock_key_sync;
3790c5ce8333SGerd Hoffmann     vs->key_delay_ms = key_delay_ms;
37913e230dd2SCorentin Chary 
37921d0d59feSGerd Hoffmann     device_id = qemu_opt_get(opts, "display");
37931d0d59feSGerd Hoffmann     if (device_id) {
37941d0d59feSGerd Hoffmann         int head = qemu_opt_get_number(opts, "head", 0);
3795f2c1d54cSGerd Hoffmann         Error *err = NULL;
37961d0d59feSGerd Hoffmann 
3797f2c1d54cSGerd Hoffmann         con = qemu_console_lookup_by_device_name(device_id, head, &err);
3798f2c1d54cSGerd Hoffmann         if (err) {
3799f2c1d54cSGerd Hoffmann             error_propagate(errp, err);
38001d0d59feSGerd Hoffmann             goto fail;
38011d0d59feSGerd Hoffmann         }
38021d0d59feSGerd Hoffmann     } else {
38031d0d59feSGerd Hoffmann         con = NULL;
38041d0d59feSGerd Hoffmann     }
38051d0d59feSGerd Hoffmann 
38061d0d59feSGerd Hoffmann     if (con != vs->dcl.con) {
38071d0d59feSGerd Hoffmann         unregister_displaychangelistener(&vs->dcl);
38081d0d59feSGerd Hoffmann         vs->dcl.con = con;
38091d0d59feSGerd Hoffmann         register_displaychangelistener(&vs->dcl);
38101d0d59feSGerd Hoffmann     }
38111d0d59feSGerd Hoffmann 
38123e230dd2SCorentin Chary     if (reverse) {
38133e230dd2SCorentin Chary         /* connect to viewer */
381404d2529dSDaniel P. Berrange         QIOChannelSocket *sioc = NULL;
381504d2529dSDaniel P. Berrange         vs->lsock = NULL;
381604d2529dSDaniel P. Berrange         vs->lwebsock = NULL;
3817e0d03b8cSDaniel P. Berrange         if (vs->ws_enabled) {
3818e0d03b8cSDaniel P. Berrange             error_setg(errp, "Cannot use websockets in reverse mode");
3819e0d03b8cSDaniel P. Berrange             goto fail;
38203e230dd2SCorentin Chary         }
382104d2529dSDaniel P. Berrange         vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
382204d2529dSDaniel P. Berrange         sioc = qio_channel_socket_new();
382304d2529dSDaniel P. Berrange         if (qio_channel_socket_connect_sync(sioc, saddr, errp) < 0) {
3824007fcd3eSPaolo Bonzini             goto fail;
3825007fcd3eSPaolo Bonzini         }
382604d2529dSDaniel P. Berrange         vnc_connect(vs, sioc, false, false);
382704d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
38283e230dd2SCorentin Chary     } else {
382904d2529dSDaniel P. Berrange         vs->lsock = qio_channel_socket_new();
383004d2529dSDaniel P. Berrange         if (qio_channel_socket_listen_sync(vs->lsock, saddr, errp) < 0) {
38313d00ac1aSCole Robinson             goto fail;
38323d00ac1aSCole Robinson         }
38332d32addaSEric Blake         vs->is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
383404d2529dSDaniel P. Berrange         vs->enabled = true;
383504d2529dSDaniel P. Berrange 
3836bf7aa45eSGerd Hoffmann         if (vs->ws_enabled) {
383704d2529dSDaniel P. Berrange             vs->lwebsock = qio_channel_socket_new();
383804d2529dSDaniel P. Berrange             if (qio_channel_socket_listen_sync(vs->lwebsock,
383904d2529dSDaniel P. Berrange                                                wsaddr, errp) < 0) {
384004d2529dSDaniel P. Berrange                 object_unref(OBJECT(vs->lsock));
384104d2529dSDaniel P. Berrange                 vs->lsock = NULL;
38427536ee4bSTim Hardeck                 goto fail;
38437536ee4bSTim Hardeck             }
38447536ee4bSTim Hardeck         }
384504d2529dSDaniel P. Berrange 
384604d2529dSDaniel P. Berrange         vs->lsock_tag = qio_channel_add_watch(
384704d2529dSDaniel P. Berrange             QIO_CHANNEL(vs->lsock),
384804d2529dSDaniel P. Berrange             G_IO_IN, vnc_listen_io, vs, NULL);
3849bf7aa45eSGerd Hoffmann         if (vs->ws_enabled) {
385004d2529dSDaniel P. Berrange             vs->lwebsock_tag = qio_channel_add_watch(
385104d2529dSDaniel P. Berrange                 QIO_CHANNEL(vs->lwebsock),
385204d2529dSDaniel P. Berrange                 G_IO_IN, vnc_listen_io, vs, NULL);
38537536ee4bSTim Hardeck         }
38543e230dd2SCorentin Chary     }
3855e0d03b8cSDaniel P. Berrange 
385633df7bf3SPaolo Bonzini     if (show_vnc_port) {
385733df7bf3SPaolo Bonzini         vnc_display_print_local_addr(vs);
385833df7bf3SPaolo Bonzini     }
385933df7bf3SPaolo Bonzini 
3860e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(saddr);
3861e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(wsaddr);
38622d55f0e8SPaolo Bonzini     return;
38631ce52c78SPaolo Bonzini 
38641ce52c78SPaolo Bonzini fail:
3865e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(saddr);
3866e0d03b8cSDaniel P. Berrange     qapi_free_SocketAddress(wsaddr);
3867bf7aa45eSGerd Hoffmann     vs->enabled = false;
3868bf7aa45eSGerd Hoffmann     vs->ws_enabled = false;
38693e230dd2SCorentin Chary }
387013661089SDaniel P. Berrange 
387114f7143eSGerd Hoffmann void vnc_display_add_client(const char *id, int csock, bool skipauth)
387213661089SDaniel P. Berrange {
387314f7143eSGerd Hoffmann     VncDisplay *vs = vnc_display_find(id);
387404d2529dSDaniel P. Berrange     QIOChannelSocket *sioc;
387513661089SDaniel P. Berrange 
3876d616ccc5SGerd Hoffmann     if (!vs) {
3877d616ccc5SGerd Hoffmann         return;
3878d616ccc5SGerd Hoffmann     }
387904d2529dSDaniel P. Berrange 
388004d2529dSDaniel P. Berrange     sioc = qio_channel_socket_new_fd(csock, NULL);
388104d2529dSDaniel P. Berrange     if (sioc) {
388204d2529dSDaniel P. Berrange         vnc_connect(vs, sioc, skipauth, false);
388304d2529dSDaniel P. Berrange         object_unref(OBJECT(sioc));
388404d2529dSDaniel P. Berrange     }
388513661089SDaniel P. Berrange }
38864db14629SGerd Hoffmann 
38879634f4e3SGerd Hoffmann static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
38882779672fSGonglei {
38892779672fSGonglei     int i = 2;
38902779672fSGonglei     char *id;
38912779672fSGonglei 
38922779672fSGonglei     id = g_strdup("default");
38932779672fSGonglei     while (qemu_opts_find(olist, id)) {
38942779672fSGonglei         g_free(id);
38952779672fSGonglei         id = g_strdup_printf("vnc%d", i++);
38962779672fSGonglei     }
38972779672fSGonglei     qemu_opts_set_id(opts, id);
38982779672fSGonglei }
38992779672fSGonglei 
390070b94331SMarkus Armbruster QemuOpts *vnc_parse(const char *str, Error **errp)
39014db14629SGerd Hoffmann {
39024db14629SGerd Hoffmann     QemuOptsList *olist = qemu_find_opts("vnc");
390370b94331SMarkus Armbruster     QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
390481607cbfSGonglei     const char *id;
39054db14629SGerd Hoffmann 
390681607cbfSGonglei     if (!opts) {
390781607cbfSGonglei         return NULL;
390881607cbfSGonglei     }
390981607cbfSGonglei 
391081607cbfSGonglei     id = qemu_opts_id(opts);
39114db14629SGerd Hoffmann     if (!id) {
39124db14629SGerd Hoffmann         /* auto-assign id if not present */
39132779672fSGonglei         vnc_auto_assign_id(olist, opts);
39149634f4e3SGerd Hoffmann     }
39159634f4e3SGerd Hoffmann     return opts;
39164db14629SGerd Hoffmann }
39174db14629SGerd Hoffmann 
391828d0de7aSMarkus Armbruster int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
39199634f4e3SGerd Hoffmann {
39209634f4e3SGerd Hoffmann     Error *local_err = NULL;
39219634f4e3SGerd Hoffmann     char *id = (char *)qemu_opts_id(opts);
39229634f4e3SGerd Hoffmann 
39239634f4e3SGerd Hoffmann     assert(id);
39244db14629SGerd Hoffmann     vnc_display_init(id);
39254db14629SGerd Hoffmann     vnc_display_open(id, &local_err);
39264db14629SGerd Hoffmann     if (local_err != NULL) {
3927c29b77f9SMarkus Armbruster         error_reportf_err(local_err, "Failed to start VNC server: ");
39284db14629SGerd Hoffmann         exit(1);
39294db14629SGerd Hoffmann     }
39304db14629SGerd Hoffmann     return 0;
39314db14629SGerd Hoffmann }
39324db14629SGerd Hoffmann 
39334db14629SGerd Hoffmann static void vnc_register_config(void)
39344db14629SGerd Hoffmann {
39354db14629SGerd Hoffmann     qemu_add_opts(&qemu_vnc_opts);
39364db14629SGerd Hoffmann }
393734294e2fSEduardo Habkost opts_init(vnc_register_config);
3938