qemu/ui/vnc.c
<<
>>
Prefs
   1/*
   2 * QEMU VNC display driver
   3 *
   4 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
   5 * Copyright (C) 2006 Fabrice Bellard
   6 * Copyright (C) 2009 Red Hat, Inc
   7 *
   8 * Permission is hereby granted, free of charge, to any person obtaining a copy
   9 * of this software and associated documentation files (the "Software"), to deal
  10 * in the Software without restriction, including without limitation the rights
  11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12 * copies of the Software, and to permit persons to whom the Software is
  13 * furnished to do so, subject to the following conditions:
  14 *
  15 * The above copyright notice and this permission notice shall be included in
  16 * all copies or substantial portions of the Software.
  17 *
  18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24 * THE SOFTWARE.
  25 */
  26
  27#include "qemu/osdep.h"
  28#include "vnc.h"
  29#include "vnc-jobs.h"
  30#include "trace.h"
  31#include "hw/qdev-core.h"
  32#include "sysemu/sysemu.h"
  33#include "qemu/error-report.h"
  34#include "qemu/main-loop.h"
  35#include "qemu/module.h"
  36#include "qemu/option.h"
  37#include "qemu/sockets.h"
  38#include "qemu/timer.h"
  39#include "authz/list.h"
  40#include "qemu/config-file.h"
  41#include "qapi/qapi-emit-events.h"
  42#include "qapi/qapi-events-ui.h"
  43#include "qapi/error.h"
  44#include "qapi/qapi-commands-ui.h"
  45#include "ui/input.h"
  46#include "crypto/hash.h"
  47#include "crypto/tlscredsanon.h"
  48#include "crypto/tlscredsx509.h"
  49#include "crypto/random.h"
  50#include "qom/object_interfaces.h"
  51#include "qemu/cutils.h"
  52#include "io/dns-resolver.h"
  53
  54#define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
  55#define VNC_REFRESH_INTERVAL_INC  50
  56#define VNC_REFRESH_INTERVAL_MAX  GUI_REFRESH_INTERVAL_IDLE
  57static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
  58static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
  59
  60#include "vnc_keysym.h"
  61#include "crypto/cipher.h"
  62
  63static QTAILQ_HEAD(, VncDisplay) vnc_displays =
  64    QTAILQ_HEAD_INITIALIZER(vnc_displays);
  65
  66static int vnc_cursor_define(VncState *vs);
  67static void vnc_update_throttle_offset(VncState *vs);
  68
  69static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
  70{
  71#ifdef _VNC_DEBUG
  72    static const char *mn[] = {
  73        [0]                           = "undefined",
  74        [VNC_SHARE_MODE_CONNECTING]   = "connecting",
  75        [VNC_SHARE_MODE_SHARED]       = "shared",
  76        [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
  77        [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
  78    };
  79    fprintf(stderr, "%s/%p: %s -> %s\n", __func__,
  80            vs->ioc, mn[vs->share_mode], mn[mode]);
  81#endif
  82
  83    switch (vs->share_mode) {
  84    case VNC_SHARE_MODE_CONNECTING:
  85        vs->vd->num_connecting--;
  86        break;
  87    case VNC_SHARE_MODE_SHARED:
  88        vs->vd->num_shared--;
  89        break;
  90    case VNC_SHARE_MODE_EXCLUSIVE:
  91        vs->vd->num_exclusive--;
  92        break;
  93    default:
  94        break;
  95    }
  96
  97    vs->share_mode = mode;
  98
  99    switch (vs->share_mode) {
 100    case VNC_SHARE_MODE_CONNECTING:
 101        vs->vd->num_connecting++;
 102        break;
 103    case VNC_SHARE_MODE_SHARED:
 104        vs->vd->num_shared++;
 105        break;
 106    case VNC_SHARE_MODE_EXCLUSIVE:
 107        vs->vd->num_exclusive++;
 108        break;
 109    default:
 110        break;
 111    }
 112}
 113
 114
 115static void vnc_init_basic_info(SocketAddress *addr,
 116                                VncBasicInfo *info,
 117                                Error **errp)
 118{
 119    switch (addr->type) {
 120    case SOCKET_ADDRESS_TYPE_INET:
 121        info->host = g_strdup(addr->u.inet.host);
 122        info->service = g_strdup(addr->u.inet.port);
 123        if (addr->u.inet.ipv6) {
 124            info->family = NETWORK_ADDRESS_FAMILY_IPV6;
 125        } else {
 126            info->family = NETWORK_ADDRESS_FAMILY_IPV4;
 127        }
 128        break;
 129
 130    case SOCKET_ADDRESS_TYPE_UNIX:
 131        info->host = g_strdup("");
 132        info->service = g_strdup(addr->u.q_unix.path);
 133        info->family = NETWORK_ADDRESS_FAMILY_UNIX;
 134        break;
 135
 136    case SOCKET_ADDRESS_TYPE_VSOCK:
 137    case SOCKET_ADDRESS_TYPE_FD:
 138        error_setg(errp, "Unsupported socket address type %s",
 139                   SocketAddressType_str(addr->type));
 140        break;
 141    default:
 142        abort();
 143    }
 144
 145    return;
 146}
 147
 148static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
 149                                                 VncBasicInfo *info,
 150                                                 Error **errp)
 151{
 152    SocketAddress *addr = NULL;
 153
 154    if (!ioc) {
 155        error_setg(errp, "No listener socket available");
 156        return;
 157    }
 158
 159    addr = qio_channel_socket_get_local_address(ioc, errp);
 160    if (!addr) {
 161        return;
 162    }
 163
 164    vnc_init_basic_info(addr, info, errp);
 165    qapi_free_SocketAddress(addr);
 166}
 167
 168static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
 169                                                 VncBasicInfo *info,
 170                                                 Error **errp)
 171{
 172    SocketAddress *addr = NULL;
 173
 174    addr = qio_channel_socket_get_remote_address(ioc, errp);
 175    if (!addr) {
 176        return;
 177    }
 178
 179    vnc_init_basic_info(addr, info, errp);
 180    qapi_free_SocketAddress(addr);
 181}
 182
 183static const char *vnc_auth_name(VncDisplay *vd) {
 184    switch (vd->auth) {
 185    case VNC_AUTH_INVALID:
 186        return "invalid";
 187    case VNC_AUTH_NONE:
 188        return "none";
 189    case VNC_AUTH_VNC:
 190        return "vnc";
 191    case VNC_AUTH_RA2:
 192        return "ra2";
 193    case VNC_AUTH_RA2NE:
 194        return "ra2ne";
 195    case VNC_AUTH_TIGHT:
 196        return "tight";
 197    case VNC_AUTH_ULTRA:
 198        return "ultra";
 199    case VNC_AUTH_TLS:
 200        return "tls";
 201    case VNC_AUTH_VENCRYPT:
 202        switch (vd->subauth) {
 203        case VNC_AUTH_VENCRYPT_PLAIN:
 204            return "vencrypt+plain";
 205        case VNC_AUTH_VENCRYPT_TLSNONE:
 206            return "vencrypt+tls+none";
 207        case VNC_AUTH_VENCRYPT_TLSVNC:
 208            return "vencrypt+tls+vnc";
 209        case VNC_AUTH_VENCRYPT_TLSPLAIN:
 210            return "vencrypt+tls+plain";
 211        case VNC_AUTH_VENCRYPT_X509NONE:
 212            return "vencrypt+x509+none";
 213        case VNC_AUTH_VENCRYPT_X509VNC:
 214            return "vencrypt+x509+vnc";
 215        case VNC_AUTH_VENCRYPT_X509PLAIN:
 216            return "vencrypt+x509+plain";
 217        case VNC_AUTH_VENCRYPT_TLSSASL:
 218            return "vencrypt+tls+sasl";
 219        case VNC_AUTH_VENCRYPT_X509SASL:
 220            return "vencrypt+x509+sasl";
 221        default:
 222            return "vencrypt";
 223        }
 224    case VNC_AUTH_SASL:
 225        return "sasl";
 226    }
 227    return "unknown";
 228}
 229
 230static VncServerInfo *vnc_server_info_get(VncDisplay *vd)
 231{
 232    VncServerInfo *info;
 233    Error *err = NULL;
 234
 235    if (!vd->listener || !vd->listener->nsioc) {
 236        return NULL;
 237    }
 238
 239    info = g_malloc0(sizeof(*info));
 240    vnc_init_basic_info_from_server_addr(vd->listener->sioc[0],
 241                                         qapi_VncServerInfo_base(info), &err);
 242    info->has_auth = true;
 243    info->auth = g_strdup(vnc_auth_name(vd));
 244    if (err) {
 245        qapi_free_VncServerInfo(info);
 246        info = NULL;
 247        error_free(err);
 248    }
 249    return info;
 250}
 251
 252static void vnc_client_cache_auth(VncState *client)
 253{
 254    if (!client->info) {
 255        return;
 256    }
 257
 258    if (client->tls) {
 259        client->info->x509_dname =
 260            qcrypto_tls_session_get_peer_name(client->tls);
 261        client->info->has_x509_dname =
 262            client->info->x509_dname != NULL;
 263    }
 264#ifdef CONFIG_VNC_SASL
 265    if (client->sasl.conn &&
 266        client->sasl.username) {
 267        client->info->has_sasl_username = true;
 268        client->info->sasl_username = g_strdup(client->sasl.username);
 269    }
 270#endif
 271}
 272
 273static void vnc_client_cache_addr(VncState *client)
 274{
 275    Error *err = NULL;
 276
 277    client->info = g_malloc0(sizeof(*client->info));
 278    vnc_init_basic_info_from_remote_addr(client->sioc,
 279                                         qapi_VncClientInfo_base(client->info),
 280                                         &err);
 281    client->info->websocket = client->websocket;
 282    if (err) {
 283        qapi_free_VncClientInfo(client->info);
 284        client->info = NULL;
 285        error_free(err);
 286    }
 287}
 288
 289static void vnc_qmp_event(VncState *vs, QAPIEvent event)
 290{
 291    VncServerInfo *si;
 292
 293    if (!vs->info) {
 294        return;
 295    }
 296
 297    si = vnc_server_info_get(vs->vd);
 298    if (!si) {
 299        return;
 300    }
 301
 302    switch (event) {
 303    case QAPI_EVENT_VNC_CONNECTED:
 304        qapi_event_send_vnc_connected(si, qapi_VncClientInfo_base(vs->info));
 305        break;
 306    case QAPI_EVENT_VNC_INITIALIZED:
 307        qapi_event_send_vnc_initialized(si, vs->info);
 308        break;
 309    case QAPI_EVENT_VNC_DISCONNECTED:
 310        qapi_event_send_vnc_disconnected(si, vs->info);
 311        break;
 312    default:
 313        break;
 314    }
 315
 316    qapi_free_VncServerInfo(si);
 317}
 318
 319static VncClientInfo *qmp_query_vnc_client(const VncState *client)
 320{
 321    VncClientInfo *info;
 322    Error *err = NULL;
 323
 324    info = g_malloc0(sizeof(*info));
 325
 326    vnc_init_basic_info_from_remote_addr(client->sioc,
 327                                         qapi_VncClientInfo_base(info),
 328                                         &err);
 329    if (err) {
 330        error_free(err);
 331        qapi_free_VncClientInfo(info);
 332        return NULL;
 333    }
 334
 335    info->websocket = client->websocket;
 336
 337    if (client->tls) {
 338        info->x509_dname = qcrypto_tls_session_get_peer_name(client->tls);
 339        info->has_x509_dname = info->x509_dname != NULL;
 340    }
 341#ifdef CONFIG_VNC_SASL
 342    if (client->sasl.conn && client->sasl.username) {
 343        info->has_sasl_username = true;
 344        info->sasl_username = g_strdup(client->sasl.username);
 345    }
 346#endif
 347
 348    return info;
 349}
 350
 351static VncDisplay *vnc_display_find(const char *id)
 352{
 353    VncDisplay *vd;
 354
 355    if (id == NULL) {
 356        return QTAILQ_FIRST(&vnc_displays);
 357    }
 358    QTAILQ_FOREACH(vd, &vnc_displays, next) {
 359        if (strcmp(id, vd->id) == 0) {
 360            return vd;
 361        }
 362    }
 363    return NULL;
 364}
 365
 366static VncClientInfoList *qmp_query_client_list(VncDisplay *vd)
 367{
 368    VncClientInfoList *cinfo, *prev = NULL;
 369    VncState *client;
 370
 371    QTAILQ_FOREACH(client, &vd->clients, next) {
 372        cinfo = g_new0(VncClientInfoList, 1);
 373        cinfo->value = qmp_query_vnc_client(client);
 374        cinfo->next = prev;
 375        prev = cinfo;
 376    }
 377    return prev;
 378}
 379
 380VncInfo *qmp_query_vnc(Error **errp)
 381{
 382    VncInfo *info = g_malloc0(sizeof(*info));
 383    VncDisplay *vd = vnc_display_find(NULL);
 384    SocketAddress *addr = NULL;
 385
 386    if (vd == NULL || !vd->listener || !vd->listener->nsioc) {
 387        info->enabled = false;
 388    } else {
 389        info->enabled = true;
 390
 391        /* for compatibility with the original command */
 392        info->has_clients = true;
 393        info->clients = qmp_query_client_list(vd);
 394
 395        addr = qio_channel_socket_get_local_address(vd->listener->sioc[0],
 396                                                    errp);
 397        if (!addr) {
 398            goto out_error;
 399        }
 400
 401        switch (addr->type) {
 402        case SOCKET_ADDRESS_TYPE_INET:
 403            info->host = g_strdup(addr->u.inet.host);
 404            info->service = g_strdup(addr->u.inet.port);
 405            if (addr->u.inet.ipv6) {
 406                info->family = NETWORK_ADDRESS_FAMILY_IPV6;
 407            } else {
 408                info->family = NETWORK_ADDRESS_FAMILY_IPV4;
 409            }
 410            break;
 411
 412        case SOCKET_ADDRESS_TYPE_UNIX:
 413            info->host = g_strdup("");
 414            info->service = g_strdup(addr->u.q_unix.path);
 415            info->family = NETWORK_ADDRESS_FAMILY_UNIX;
 416            break;
 417
 418        case SOCKET_ADDRESS_TYPE_VSOCK:
 419        case SOCKET_ADDRESS_TYPE_FD:
 420            error_setg(errp, "Unsupported socket address type %s",
 421                       SocketAddressType_str(addr->type));
 422            goto out_error;
 423        default:
 424            abort();
 425        }
 426
 427        info->has_host = true;
 428        info->has_service = true;
 429        info->has_family = true;
 430
 431        info->has_auth = true;
 432        info->auth = g_strdup(vnc_auth_name(vd));
 433    }
 434
 435    qapi_free_SocketAddress(addr);
 436    return info;
 437
 438out_error:
 439    qapi_free_SocketAddress(addr);
 440    qapi_free_VncInfo(info);
 441    return NULL;
 442}
 443
 444
 445static void qmp_query_auth(int auth, int subauth,
 446                           VncPrimaryAuth *qmp_auth,
 447                           VncVencryptSubAuth *qmp_vencrypt,
 448                           bool *qmp_has_vencrypt);
 449
 450static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,
 451                                                  bool websocket,
 452                                                  int auth,
 453                                                  int subauth,
 454                                                  VncServerInfo2List *prev)
 455{
 456    VncServerInfo2List *list;
 457    VncServerInfo2 *info;
 458    Error *err = NULL;
 459    SocketAddress *addr;
 460
 461    addr = qio_channel_socket_get_local_address(ioc, &err);
 462    if (!addr) {
 463        error_free(err);
 464        return prev;
 465    }
 466
 467    info = g_new0(VncServerInfo2, 1);
 468    vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);
 469    qapi_free_SocketAddress(addr);
 470    if (err) {
 471        qapi_free_VncServerInfo2(info);
 472        error_free(err);
 473        return prev;
 474    }
 475    info->websocket = websocket;
 476
 477    qmp_query_auth(auth, subauth, &info->auth,
 478                   &info->vencrypt, &info->has_vencrypt);
 479
 480    list = g_new0(VncServerInfo2List, 1);
 481    list->value = info;
 482    list->next = prev;
 483    return list;
 484}
 485
 486static void qmp_query_auth(int auth, int subauth,
 487                           VncPrimaryAuth *qmp_auth,
 488                           VncVencryptSubAuth *qmp_vencrypt,
 489                           bool *qmp_has_vencrypt)
 490{
 491    switch (auth) {
 492    case VNC_AUTH_VNC:
 493        *qmp_auth = VNC_PRIMARY_AUTH_VNC;
 494        break;
 495    case VNC_AUTH_RA2:
 496        *qmp_auth = VNC_PRIMARY_AUTH_RA2;
 497        break;
 498    case VNC_AUTH_RA2NE:
 499        *qmp_auth = VNC_PRIMARY_AUTH_RA2NE;
 500        break;
 501    case VNC_AUTH_TIGHT:
 502        *qmp_auth = VNC_PRIMARY_AUTH_TIGHT;
 503        break;
 504    case VNC_AUTH_ULTRA:
 505        *qmp_auth = VNC_PRIMARY_AUTH_ULTRA;
 506        break;
 507    case VNC_AUTH_TLS:
 508        *qmp_auth = VNC_PRIMARY_AUTH_TLS;
 509        break;
 510    case VNC_AUTH_VENCRYPT:
 511        *qmp_auth = VNC_PRIMARY_AUTH_VENCRYPT;
 512        *qmp_has_vencrypt = true;
 513        switch (subauth) {
 514        case VNC_AUTH_VENCRYPT_PLAIN:
 515            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;
 516            break;
 517        case VNC_AUTH_VENCRYPT_TLSNONE:
 518            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;
 519            break;
 520        case VNC_AUTH_VENCRYPT_TLSVNC:
 521            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;
 522            break;
 523        case VNC_AUTH_VENCRYPT_TLSPLAIN:
 524            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;
 525            break;
 526        case VNC_AUTH_VENCRYPT_X509NONE:
 527            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;
 528            break;
 529        case VNC_AUTH_VENCRYPT_X509VNC:
 530            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;
 531            break;
 532        case VNC_AUTH_VENCRYPT_X509PLAIN:
 533            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;
 534            break;
 535        case VNC_AUTH_VENCRYPT_TLSSASL:
 536            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;
 537            break;
 538        case VNC_AUTH_VENCRYPT_X509SASL:
 539            *qmp_vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;
 540            break;
 541        default:
 542            *qmp_has_vencrypt = false;
 543            break;
 544        }
 545        break;
 546    case VNC_AUTH_SASL:
 547        *qmp_auth = VNC_PRIMARY_AUTH_SASL;
 548        break;
 549    case VNC_AUTH_NONE:
 550    default:
 551        *qmp_auth = VNC_PRIMARY_AUTH_NONE;
 552        break;
 553    }
 554}
 555
 556VncInfo2List *qmp_query_vnc_servers(Error **errp)
 557{
 558    VncInfo2List *item, *prev = NULL;
 559    VncInfo2 *info;
 560    VncDisplay *vd;
 561    DeviceState *dev;
 562    size_t i;
 563
 564    QTAILQ_FOREACH(vd, &vnc_displays, next) {
 565        info = g_new0(VncInfo2, 1);
 566        info->id = g_strdup(vd->id);
 567        info->clients = qmp_query_client_list(vd);
 568        qmp_query_auth(vd->auth, vd->subauth, &info->auth,
 569                       &info->vencrypt, &info->has_vencrypt);
 570        if (vd->dcl.con) {
 571            dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),
 572                                                  "device", NULL));
 573            info->has_display = true;
 574            info->display = g_strdup(dev->id);
 575        }
 576        for (i = 0; vd->listener != NULL && i < vd->listener->nsioc; i++) {
 577            info->server = qmp_query_server_entry(
 578                vd->listener->sioc[i], false, vd->auth, vd->subauth,
 579                info->server);
 580        }
 581        for (i = 0; vd->wslistener != NULL && i < vd->wslistener->nsioc; i++) {
 582            info->server = qmp_query_server_entry(
 583                vd->wslistener->sioc[i], true, vd->ws_auth,
 584                vd->ws_subauth, info->server);
 585        }
 586
 587        item = g_new0(VncInfo2List, 1);
 588        item->value = info;
 589        item->next = prev;
 590        prev = item;
 591    }
 592    return prev;
 593}
 594
 595/* TODO
 596   1) Get the queue working for IO.
 597   2) there is some weirdness when using the -S option (the screen is grey
 598      and not totally invalidated
 599   3) resolutions > 1024
 600*/
 601
 602static int vnc_update_client(VncState *vs, int has_dirty);
 603static void vnc_disconnect_start(VncState *vs);
 604
 605static void vnc_colordepth(VncState *vs);
 606static void framebuffer_update_request(VncState *vs, int incremental,
 607                                       int x_position, int y_position,
 608                                       int w, int h);
 609static void vnc_refresh(DisplayChangeListener *dcl);
 610static int vnc_refresh_server_surface(VncDisplay *vd);
 611
 612static int vnc_width(VncDisplay *vd)
 613{
 614    return MIN(VNC_MAX_WIDTH, ROUND_UP(surface_width(vd->ds),
 615                                       VNC_DIRTY_PIXELS_PER_BIT));
 616}
 617
 618static int vnc_height(VncDisplay *vd)
 619{
 620    return MIN(VNC_MAX_HEIGHT, surface_height(vd->ds));
 621}
 622
 623static void vnc_set_area_dirty(DECLARE_BITMAP(dirty[VNC_MAX_HEIGHT],
 624                               VNC_MAX_WIDTH / VNC_DIRTY_PIXELS_PER_BIT),
 625                               VncDisplay *vd,
 626                               int x, int y, int w, int h)
 627{
 628    int width = vnc_width(vd);
 629    int height = vnc_height(vd);
 630
 631    /* this is needed this to ensure we updated all affected
 632     * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
 633    w += (x % VNC_DIRTY_PIXELS_PER_BIT);
 634    x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
 635
 636    x = MIN(x, width);
 637    y = MIN(y, height);
 638    w = MIN(x + w, width) - x;
 639    h = MIN(y + h, height);
 640
 641    for (; y < h; y++) {
 642        bitmap_set(dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
 643                   DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
 644    }
 645}
 646
 647static void vnc_dpy_update(DisplayChangeListener *dcl,
 648                           int x, int y, int w, int h)
 649{
 650    VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
 651    struct VncSurface *s = &vd->guest;
 652
 653    vnc_set_area_dirty(s->dirty, vd, x, y, w, h);
 654}
 655
 656void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
 657                            int32_t encoding)
 658{
 659    vnc_write_u16(vs, x);
 660    vnc_write_u16(vs, y);
 661    vnc_write_u16(vs, w);
 662    vnc_write_u16(vs, h);
 663
 664    vnc_write_s32(vs, encoding);
 665}
 666
 667
 668static void vnc_desktop_resize(VncState *vs)
 669{
 670    if (vs->ioc == NULL || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
 671        return;
 672    }
 673    if (vs->client_width == pixman_image_get_width(vs->vd->server) &&
 674        vs->client_height == pixman_image_get_height(vs->vd->server)) {
 675        return;
 676    }
 677
 678    assert(pixman_image_get_width(vs->vd->server) < 65536 &&
 679           pixman_image_get_width(vs->vd->server) >= 0);
 680    assert(pixman_image_get_height(vs->vd->server) < 65536 &&
 681           pixman_image_get_height(vs->vd->server) >= 0);
 682    vs->client_width = pixman_image_get_width(vs->vd->server);
 683    vs->client_height = pixman_image_get_height(vs->vd->server);
 684    vnc_lock_output(vs);
 685    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
 686    vnc_write_u8(vs, 0);
 687    vnc_write_u16(vs, 1); /* number of rects */
 688    vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
 689                           VNC_ENCODING_DESKTOPRESIZE);
 690    vnc_unlock_output(vs);
 691    vnc_flush(vs);
 692}
 693
 694static void vnc_abort_display_jobs(VncDisplay *vd)
 695{
 696    VncState *vs;
 697
 698    QTAILQ_FOREACH(vs, &vd->clients, next) {
 699        vnc_lock_output(vs);
 700        vs->abort = true;
 701        vnc_unlock_output(vs);
 702    }
 703    QTAILQ_FOREACH(vs, &vd->clients, next) {
 704        vnc_jobs_join(vs);
 705    }
 706    QTAILQ_FOREACH(vs, &vd->clients, next) {
 707        vnc_lock_output(vs);
 708        if (vs->update == VNC_STATE_UPDATE_NONE &&
 709            vs->job_update != VNC_STATE_UPDATE_NONE) {
 710            /* job aborted before completion */
 711            vs->update = vs->job_update;
 712            vs->job_update = VNC_STATE_UPDATE_NONE;
 713        }
 714        vs->abort = false;
 715        vnc_unlock_output(vs);
 716    }
 717}
 718
 719int vnc_server_fb_stride(VncDisplay *vd)
 720{
 721    return pixman_image_get_stride(vd->server);
 722}
 723
 724void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
 725{
 726    uint8_t *ptr;
 727
 728    ptr  = (uint8_t *)pixman_image_get_data(vd->server);
 729    ptr += y * vnc_server_fb_stride(vd);
 730    ptr += x * VNC_SERVER_FB_BYTES;
 731    return ptr;
 732}
 733
 734static void vnc_update_server_surface(VncDisplay *vd)
 735{
 736    int width, height;
 737
 738    qemu_pixman_image_unref(vd->server);
 739    vd->server = NULL;
 740
 741    if (QTAILQ_EMPTY(&vd->clients)) {
 742        return;
 743    }
 744
 745    width = vnc_width(vd);
 746    height = vnc_height(vd);
 747    vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
 748                                          width, height,
 749                                          NULL, 0);
 750
 751    memset(vd->guest.dirty, 0x00, sizeof(vd->guest.dirty));
 752    vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
 753                       width, height);
 754}
 755
 756static bool vnc_check_pageflip(DisplaySurface *s1,
 757                               DisplaySurface *s2)
 758{
 759    return (s1 != NULL &&
 760            s2 != NULL &&
 761            surface_width(s1) == surface_width(s2) &&
 762            surface_height(s1) == surface_height(s2) &&
 763            surface_format(s1) == surface_format(s2));
 764
 765}
 766
 767static void vnc_dpy_switch(DisplayChangeListener *dcl,
 768                           DisplaySurface *surface)
 769{
 770    static const char placeholder_msg[] =
 771        "Display output is not active.";
 772    static DisplaySurface *placeholder;
 773    VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
 774    bool pageflip = vnc_check_pageflip(vd->ds, surface);
 775    VncState *vs;
 776
 777    if (surface == NULL) {
 778        if (placeholder == NULL) {
 779            placeholder = qemu_create_message_surface(640, 480, placeholder_msg);
 780        }
 781        surface = placeholder;
 782    }
 783
 784    vnc_abort_display_jobs(vd);
 785    vd->ds = surface;
 786
 787    /* guest surface */
 788    qemu_pixman_image_unref(vd->guest.fb);
 789    vd->guest.fb = pixman_image_ref(surface->image);
 790    vd->guest.format = surface->format;
 791
 792    if (pageflip) {
 793        vnc_set_area_dirty(vd->guest.dirty, vd, 0, 0,
 794                           surface_width(surface),
 795                           surface_height(surface));
 796        return;
 797    }
 798
 799    /* server surface */
 800    vnc_update_server_surface(vd);
 801
 802    QTAILQ_FOREACH(vs, &vd->clients, next) {
 803        vnc_colordepth(vs);
 804        vnc_desktop_resize(vs);
 805        if (vs->vd->cursor) {
 806            vnc_cursor_define(vs);
 807        }
 808        memset(vs->dirty, 0x00, sizeof(vs->dirty));
 809        vnc_set_area_dirty(vs->dirty, vd, 0, 0,
 810                           vnc_width(vd),
 811                           vnc_height(vd));
 812        vnc_update_throttle_offset(vs);
 813    }
 814}
 815
 816/* fastest code */
 817static void vnc_write_pixels_copy(VncState *vs,
 818                                  void *pixels, int size)
 819{
 820    vnc_write(vs, pixels, size);
 821}
 822
 823/* slowest but generic code. */
 824void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
 825{
 826    uint8_t r, g, b;
 827
 828#if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
 829    r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
 830    g = (((v & 0x0000ff00) >>  8) << vs->client_pf.gbits) >> 8;
 831    b = (((v & 0x000000ff) >>  0) << vs->client_pf.bbits) >> 8;
 832#else
 833# error need some bits here if you change VNC_SERVER_FB_FORMAT
 834#endif
 835    v = (r << vs->client_pf.rshift) |
 836        (g << vs->client_pf.gshift) |
 837        (b << vs->client_pf.bshift);
 838    switch (vs->client_pf.bytes_per_pixel) {
 839    case 1:
 840        buf[0] = v;
 841        break;
 842    case 2:
 843        if (vs->client_be) {
 844            buf[0] = v >> 8;
 845            buf[1] = v;
 846        } else {
 847            buf[1] = v >> 8;
 848            buf[0] = v;
 849        }
 850        break;
 851    default:
 852    case 4:
 853        if (vs->client_be) {
 854            buf[0] = v >> 24;
 855            buf[1] = v >> 16;
 856            buf[2] = v >> 8;
 857            buf[3] = v;
 858        } else {
 859            buf[3] = v >> 24;
 860            buf[2] = v >> 16;
 861            buf[1] = v >> 8;
 862            buf[0] = v;
 863        }
 864        break;
 865    }
 866}
 867
 868static void vnc_write_pixels_generic(VncState *vs,
 869                                     void *pixels1, int size)
 870{
 871    uint8_t buf[4];
 872
 873    if (VNC_SERVER_FB_BYTES == 4) {
 874        uint32_t *pixels = pixels1;
 875        int n, i;
 876        n = size >> 2;
 877        for (i = 0; i < n; i++) {
 878            vnc_convert_pixel(vs, buf, pixels[i]);
 879            vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
 880        }
 881    }
 882}
 883
 884int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
 885{
 886    int i;
 887    uint8_t *row;
 888    VncDisplay *vd = vs->vd;
 889
 890    row = vnc_server_fb_ptr(vd, x, y);
 891    for (i = 0; i < h; i++) {
 892        vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
 893        row += vnc_server_fb_stride(vd);
 894    }
 895    return 1;
 896}
 897
 898int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
 899{
 900    int n = 0;
 901
 902    switch(vs->vnc_encoding) {
 903        case VNC_ENCODING_ZLIB:
 904            n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
 905            break;
 906        case VNC_ENCODING_HEXTILE:
 907            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
 908            n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
 909            break;
 910        case VNC_ENCODING_TIGHT:
 911            n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
 912            break;
 913        case VNC_ENCODING_TIGHT_PNG:
 914            n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
 915            break;
 916        case VNC_ENCODING_ZRLE:
 917            n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
 918            break;
 919        case VNC_ENCODING_ZYWRLE:
 920            n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
 921            break;
 922        default:
 923            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
 924            n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
 925            break;
 926    }
 927    return n;
 928}
 929
 930static void vnc_mouse_set(DisplayChangeListener *dcl,
 931                          int x, int y, int visible)
 932{
 933    /* can we ask the client(s) to move the pointer ??? */
 934}
 935
 936static int vnc_cursor_define(VncState *vs)
 937{
 938    QEMUCursor *c = vs->vd->cursor;
 939    int isize;
 940
 941    if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
 942        vnc_lock_output(vs);
 943        vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
 944        vnc_write_u8(vs,  0);  /*  padding     */
 945        vnc_write_u16(vs, 1);  /*  # of rects  */
 946        vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
 947                               VNC_ENCODING_RICH_CURSOR);
 948        isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
 949        vnc_write_pixels_generic(vs, c->data, isize);
 950        vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
 951        vnc_unlock_output(vs);
 952        return 0;
 953    }
 954    return -1;
 955}
 956
 957static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
 958                                  QEMUCursor *c)
 959{
 960    VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
 961    VncState *vs;
 962
 963    cursor_put(vd->cursor);
 964    g_free(vd->cursor_mask);
 965
 966    vd->cursor = c;
 967    cursor_get(vd->cursor);
 968    vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
 969    vd->cursor_mask = g_malloc0(vd->cursor_msize);
 970    cursor_get_mono_mask(c, 0, vd->cursor_mask);
 971
 972    QTAILQ_FOREACH(vs, &vd->clients, next) {
 973        vnc_cursor_define(vs);
 974    }
 975}
 976
 977static int find_and_clear_dirty_height(VncState *vs,
 978                                       int y, int last_x, int x, int height)
 979{
 980    int h;
 981
 982    for (h = 1; h < (height - y); h++) {
 983        if (!test_bit(last_x, vs->dirty[y + h])) {
 984            break;
 985        }
 986        bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
 987    }
 988
 989    return h;
 990}
 991
 992/*
 993 * Figure out how much pending data we should allow in the output
 994 * buffer before we throttle incremental display updates, and/or
 995 * drop audio samples.
 996 *
 997 * We allow for equiv of 1 full display's worth of FB updates,
 998 * and 1 second of audio samples. If audio backlog was larger
 999 * than that the client would already suffering awful audio
1000 * glitches, so dropping samples is no worse really).
1001 */
1002static void vnc_update_throttle_offset(VncState *vs)
1003{
1004    size_t offset =
1005        vs->client_width * vs->client_height * vs->client_pf.bytes_per_pixel;
1006
1007    if (vs->audio_cap) {
1008        int bps;
1009        switch (vs->as.fmt) {
1010        default:
1011        case  AUDIO_FORMAT_U8:
1012        case  AUDIO_FORMAT_S8:
1013            bps = 1;
1014            break;
1015        case  AUDIO_FORMAT_U16:
1016        case  AUDIO_FORMAT_S16:
1017            bps = 2;
1018            break;
1019        case  AUDIO_FORMAT_U32:
1020        case  AUDIO_FORMAT_S32:
1021            bps = 4;
1022            break;
1023        }
1024        offset += vs->as.freq * bps * vs->as.nchannels;
1025    }
1026
1027    /* Put a floor of 1MB on offset, so that if we have a large pending
1028     * buffer and the display is resized to a small size & back again
1029     * we don't suddenly apply a tiny send limit
1030     */
1031    offset = MAX(offset, 1024 * 1024);
1032
1033    if (vs->throttle_output_offset != offset) {
1034        trace_vnc_client_throttle_threshold(
1035            vs, vs->ioc, vs->throttle_output_offset, offset, vs->client_width,
1036            vs->client_height, vs->client_pf.bytes_per_pixel, vs->audio_cap);
1037    }
1038
1039    vs->throttle_output_offset = offset;
1040}
1041
1042static bool vnc_should_update(VncState *vs)
1043{
1044    switch (vs->update) {
1045    case VNC_STATE_UPDATE_NONE:
1046        break;
1047    case VNC_STATE_UPDATE_INCREMENTAL:
1048        /* Only allow incremental updates if the pending send queue
1049         * is less than the permitted threshold, and the job worker
1050         * is completely idle.
1051         */
1052        if (vs->output.offset < vs->throttle_output_offset &&
1053            vs->job_update == VNC_STATE_UPDATE_NONE) {
1054            return true;
1055        }
1056        trace_vnc_client_throttle_incremental(
1057            vs, vs->ioc, vs->job_update, vs->output.offset);
1058        break;
1059    case VNC_STATE_UPDATE_FORCE:
1060        /* Only allow forced updates if the pending send queue
1061         * does not contain a previous forced update, and the
1062         * job worker is completely idle.
1063         *
1064         * Note this means we'll queue a forced update, even if
1065         * the output buffer size is otherwise over the throttle
1066         * output limit.
1067         */
1068        if (vs->force_update_offset == 0 &&
1069            vs->job_update == VNC_STATE_UPDATE_NONE) {
1070            return true;
1071        }
1072        trace_vnc_client_throttle_forced(
1073            vs, vs->ioc, vs->job_update, vs->force_update_offset);
1074        break;
1075    }
1076    return false;
1077}
1078
1079static int vnc_update_client(VncState *vs, int has_dirty)
1080{
1081    VncDisplay *vd = vs->vd;
1082    VncJob *job;
1083    int y;
1084    int height, width;
1085    int n = 0;
1086
1087    if (vs->disconnecting) {
1088        vnc_disconnect_finish(vs);
1089        return 0;
1090    }
1091
1092    vs->has_dirty += has_dirty;
1093    if (!vnc_should_update(vs)) {
1094        return 0;
1095    }
1096
1097    if (!vs->has_dirty && vs->update != VNC_STATE_UPDATE_FORCE) {
1098        return 0;
1099    }
1100
1101    /*
1102     * Send screen updates to the vnc client using the server
1103     * surface and server dirty map.  guest surface updates
1104     * happening in parallel don't disturb us, the next pass will
1105     * send them to the client.
1106     */
1107    job = vnc_job_new(vs);
1108
1109    height = pixman_image_get_height(vd->server);
1110    width = pixman_image_get_width(vd->server);
1111
1112    y = 0;
1113    for (;;) {
1114        int x, h;
1115        unsigned long x2;
1116        unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
1117                                             height * VNC_DIRTY_BPL(vs),
1118                                             y * VNC_DIRTY_BPL(vs));
1119        if (offset == height * VNC_DIRTY_BPL(vs)) {
1120            /* no more dirty bits */
1121            break;
1122        }
1123        y = offset / VNC_DIRTY_BPL(vs);
1124        x = offset % VNC_DIRTY_BPL(vs);
1125        x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
1126                                VNC_DIRTY_BPL(vs), x);
1127        bitmap_clear(vs->dirty[y], x, x2 - x);
1128        h = find_and_clear_dirty_height(vs, y, x, x2, height);
1129        x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
1130        if (x2 > x) {
1131            n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
1132                                  (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
1133        }
1134        if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {
1135            y += h;
1136            if (y == height) {
1137                break;
1138            }
1139        }
1140    }
1141
1142    vs->job_update = vs->update;
1143    vs->update = VNC_STATE_UPDATE_NONE;
1144    vnc_job_push(job);
1145    vs->has_dirty = 0;
1146    return n;
1147}
1148
1149/* audio */
1150static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1151{
1152    VncState *vs = opaque;
1153
1154    assert(vs->magic == VNC_MAGIC);
1155    switch (cmd) {
1156    case AUD_CNOTIFY_DISABLE:
1157        vnc_lock_output(vs);
1158        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1159        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1160        vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
1161        vnc_unlock_output(vs);
1162        vnc_flush(vs);
1163        break;
1164
1165    case AUD_CNOTIFY_ENABLE:
1166        vnc_lock_output(vs);
1167        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1168        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1169        vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
1170        vnc_unlock_output(vs);
1171        vnc_flush(vs);
1172        break;
1173    }
1174}
1175
1176static void audio_capture_destroy(void *opaque)
1177{
1178}
1179
1180static void audio_capture(void *opaque, void *buf, int size)
1181{
1182    VncState *vs = opaque;
1183
1184    assert(vs->magic == VNC_MAGIC);
1185    vnc_lock_output(vs);
1186    if (vs->output.offset < vs->throttle_output_offset) {
1187        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
1188        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
1189        vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
1190        vnc_write_u32(vs, size);
1191        vnc_write(vs, buf, size);
1192    } else {
1193        trace_vnc_client_throttle_audio(vs, vs->ioc, vs->output.offset);
1194    }
1195    vnc_unlock_output(vs);
1196    vnc_flush(vs);
1197}
1198
1199static void audio_add(VncState *vs)
1200{
1201    struct audio_capture_ops ops;
1202
1203    if (vs->audio_cap) {
1204        error_report("audio already running");
1205        return;
1206    }
1207
1208    ops.notify = audio_capture_notify;
1209    ops.destroy = audio_capture_destroy;
1210    ops.capture = audio_capture;
1211
1212    vs->audio_cap = AUD_add_capture(vs->vd->audio_state, &vs->as, &ops, vs);
1213    if (!vs->audio_cap) {
1214        error_report("Failed to add audio capture");
1215    }
1216}
1217
1218static void audio_del(VncState *vs)
1219{
1220    if (vs->audio_cap) {
1221        AUD_del_capture(vs->audio_cap, vs);
1222        vs->audio_cap = NULL;
1223    }
1224}
1225
1226static void vnc_disconnect_start(VncState *vs)
1227{
1228    if (vs->disconnecting) {
1229        return;
1230    }
1231    trace_vnc_client_disconnect_start(vs, vs->ioc);
1232    vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1233    if (vs->ioc_tag) {
1234        g_source_remove(vs->ioc_tag);
1235        vs->ioc_tag = 0;
1236    }
1237    qio_channel_close(vs->ioc, NULL);
1238    vs->disconnecting = TRUE;
1239}
1240
1241void vnc_disconnect_finish(VncState *vs)
1242{
1243    int i;
1244
1245    trace_vnc_client_disconnect_finish(vs, vs->ioc);
1246
1247    vnc_jobs_join(vs); /* Wait encoding jobs */
1248
1249    vnc_lock_output(vs);
1250    vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
1251
1252    buffer_free(&vs->input);
1253    buffer_free(&vs->output);
1254
1255    qapi_free_VncClientInfo(vs->info);
1256
1257    vnc_zlib_clear(vs);
1258    vnc_tight_clear(vs);
1259    vnc_zrle_clear(vs);
1260
1261#ifdef CONFIG_VNC_SASL
1262    vnc_sasl_client_cleanup(vs);
1263#endif /* CONFIG_VNC_SASL */
1264    audio_del(vs);
1265    qkbd_state_lift_all_keys(vs->vd->kbd);
1266
1267    if (vs->mouse_mode_notifier.notify != NULL) {
1268        qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1269    }
1270    QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1271    if (QTAILQ_EMPTY(&vs->vd->clients)) {
1272        /* last client gone */
1273        vnc_update_server_surface(vs->vd);
1274    }
1275
1276    vnc_unlock_output(vs);
1277
1278    qemu_mutex_destroy(&vs->output_mutex);
1279    if (vs->bh != NULL) {
1280        qemu_bh_delete(vs->bh);
1281    }
1282    buffer_free(&vs->jobs_buffer);
1283
1284    for (i = 0; i < VNC_STAT_ROWS; ++i) {
1285        g_free(vs->lossy_rect[i]);
1286    }
1287    g_free(vs->lossy_rect);
1288
1289    object_unref(OBJECT(vs->ioc));
1290    vs->ioc = NULL;
1291    object_unref(OBJECT(vs->sioc));
1292    vs->sioc = NULL;
1293    vs->magic = 0;
1294    g_free(vs->zrle);
1295    g_free(vs->tight);
1296    g_free(vs);
1297}
1298
1299size_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)
1300{
1301    if (ret <= 0) {
1302        if (ret == 0) {
1303            trace_vnc_client_eof(vs, vs->ioc);
1304            vnc_disconnect_start(vs);
1305        } else if (ret != QIO_CHANNEL_ERR_BLOCK) {
1306            trace_vnc_client_io_error(vs, vs->ioc,
1307                                      errp ? error_get_pretty(*errp) :
1308                                      "Unknown");
1309            vnc_disconnect_start(vs);
1310        }
1311
1312        if (errp) {
1313            error_free(*errp);
1314            *errp = NULL;
1315        }
1316        return 0;
1317    }
1318    return ret;
1319}
1320
1321
1322void vnc_client_error(VncState *vs)
1323{
1324    VNC_DEBUG("Closing down client sock: protocol error\n");
1325    vnc_disconnect_start(vs);
1326}
1327
1328
1329/*
1330 * Called to write a chunk of data to the client socket. The data may
1331 * be the raw data, or may have already been encoded by SASL.
1332 * The data will be written either straight onto the socket, or
1333 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1334 *
1335 * NB, it is theoretically possible to have 2 layers of encryption,
1336 * both SASL, and this TLS layer. It is highly unlikely in practice
1337 * though, since SASL encryption will typically be a no-op if TLS
1338 * is active
1339 *
1340 * Returns the number of bytes written, which may be less than
1341 * the requested 'datalen' if the socket would block. Returns
1342 * 0 on I/O error, and disconnects the client socket.
1343 */
1344size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1345{
1346    Error *err = NULL;
1347    ssize_t ret;
1348    ret = qio_channel_write(
1349        vs->ioc, (const char *)data, datalen, &err);
1350    VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1351    return vnc_client_io_error(vs, ret, &err);
1352}
1353
1354
1355/*
1356 * Called to write buffered data to the client socket, when not
1357 * using any SASL SSF encryption layers. Will write as much data
1358 * as possible without blocking. If all buffered data is written,
1359 * will switch the FD poll() handler back to read monitoring.
1360 *
1361 * Returns the number of bytes written, which may be less than
1362 * the buffered output data if the socket would block.  Returns
1363 * 0 on I/O error, and disconnects the client socket.
1364 */
1365static size_t vnc_client_write_plain(VncState *vs)
1366{
1367    size_t offset;
1368    size_t ret;
1369
1370#ifdef CONFIG_VNC_SASL
1371    VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1372              vs->output.buffer, vs->output.capacity, vs->output.offset,
1373              vs->sasl.waitWriteSSF);
1374
1375    if (vs->sasl.conn &&
1376        vs->sasl.runSSF &&
1377        vs->sasl.waitWriteSSF) {
1378        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1379        if (ret)
1380            vs->sasl.waitWriteSSF -= ret;
1381    } else
1382#endif /* CONFIG_VNC_SASL */
1383        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1384    if (!ret)
1385        return 0;
1386
1387    if (ret >= vs->force_update_offset) {
1388        if (vs->force_update_offset != 0) {
1389            trace_vnc_client_unthrottle_forced(vs, vs->ioc);
1390        }
1391        vs->force_update_offset = 0;
1392    } else {
1393        vs->force_update_offset -= ret;
1394    }
1395    offset = vs->output.offset;
1396    buffer_advance(&vs->output, ret);
1397    if (offset >= vs->throttle_output_offset &&
1398        vs->output.offset < vs->throttle_output_offset) {
1399        trace_vnc_client_unthrottle_incremental(vs, vs->ioc, vs->output.offset);
1400    }
1401
1402    if (vs->output.offset == 0) {
1403        if (vs->ioc_tag) {
1404            g_source_remove(vs->ioc_tag);
1405        }
1406        vs->ioc_tag = qio_channel_add_watch(
1407            vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1408    }
1409
1410    return ret;
1411}
1412
1413
1414/*
1415 * First function called whenever there is data to be written to
1416 * the client socket. Will delegate actual work according to whether
1417 * SASL SSF layers are enabled (thus requiring encryption calls)
1418 */
1419static void vnc_client_write_locked(VncState *vs)
1420{
1421#ifdef CONFIG_VNC_SASL
1422    if (vs->sasl.conn &&
1423        vs->sasl.runSSF &&
1424        !vs->sasl.waitWriteSSF) {
1425        vnc_client_write_sasl(vs);
1426    } else
1427#endif /* CONFIG_VNC_SASL */
1428    {
1429        vnc_client_write_plain(vs);
1430    }
1431}
1432
1433static void vnc_client_write(VncState *vs)
1434{
1435    assert(vs->magic == VNC_MAGIC);
1436    vnc_lock_output(vs);
1437    if (vs->output.offset) {
1438        vnc_client_write_locked(vs);
1439    } else if (vs->ioc != NULL) {
1440        if (vs->ioc_tag) {
1441            g_source_remove(vs->ioc_tag);
1442        }
1443        vs->ioc_tag = qio_channel_add_watch(
1444            vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
1445    }
1446    vnc_unlock_output(vs);
1447}
1448
1449void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1450{
1451    vs->read_handler = func;
1452    vs->read_handler_expect = expecting;
1453}
1454
1455
1456/*
1457 * Called to read a chunk of data from the client socket. The data may
1458 * be the raw data, or may need to be further decoded by SASL.
1459 * The data will be read either straight from to the socket, or
1460 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1461 *
1462 * NB, it is theoretically possible to have 2 layers of encryption,
1463 * both SASL, and this TLS layer. It is highly unlikely in practice
1464 * though, since SASL encryption will typically be a no-op if TLS
1465 * is active
1466 *
1467 * Returns the number of bytes read, which may be less than
1468 * the requested 'datalen' if the socket would block. Returns
1469 * 0 on I/O error or EOF, and disconnects the client socket.
1470 */
1471size_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1472{
1473    ssize_t ret;
1474    Error *err = NULL;
1475    ret = qio_channel_read(
1476        vs->ioc, (char *)data, datalen, &err);
1477    VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1478    return vnc_client_io_error(vs, ret, &err);
1479}
1480
1481
1482/*
1483 * Called to read data from the client socket to the input buffer,
1484 * when not using any SASL SSF encryption layers. Will read as much
1485 * data as possible without blocking.
1486 *
1487 * Returns the number of bytes read, which may be less than
1488 * the requested 'datalen' if the socket would block. Returns
1489 * 0 on I/O error or EOF, and disconnects the client socket.
1490 */
1491static size_t vnc_client_read_plain(VncState *vs)
1492{
1493    size_t ret;
1494    VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1495              vs->input.buffer, vs->input.capacity, vs->input.offset);
1496    buffer_reserve(&vs->input, 4096);
1497    ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1498    if (!ret)
1499        return 0;
1500    vs->input.offset += ret;
1501    return ret;
1502}
1503
1504static void vnc_jobs_bh(void *opaque)
1505{
1506    VncState *vs = opaque;
1507
1508    assert(vs->magic == VNC_MAGIC);
1509    vnc_jobs_consume_buffer(vs);
1510}
1511
1512/*
1513 * First function called whenever there is more data to be read from
1514 * the client socket. Will delegate actual work according to whether
1515 * SASL SSF layers are enabled (thus requiring decryption calls)
1516 * Returns 0 on success, -1 if client disconnected
1517 */
1518static int vnc_client_read(VncState *vs)
1519{
1520    size_t ret;
1521
1522#ifdef CONFIG_VNC_SASL
1523    if (vs->sasl.conn && vs->sasl.runSSF)
1524        ret = vnc_client_read_sasl(vs);
1525    else
1526#endif /* CONFIG_VNC_SASL */
1527        ret = vnc_client_read_plain(vs);
1528    if (!ret) {
1529        if (vs->disconnecting) {
1530            vnc_disconnect_finish(vs);
1531            return -1;
1532        }
1533        return 0;
1534    }
1535
1536    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1537        size_t len = vs->read_handler_expect;
1538        int ret;
1539
1540        ret = vs->read_handler(vs, vs->input.buffer, len);
1541        if (vs->disconnecting) {
1542            vnc_disconnect_finish(vs);
1543            return -1;
1544        }
1545
1546        if (!ret) {
1547            buffer_advance(&vs->input, len);
1548        } else {
1549            vs->read_handler_expect = ret;
1550        }
1551    }
1552    return 0;
1553}
1554
1555gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
1556                       GIOCondition condition, void *opaque)
1557{
1558    VncState *vs = opaque;
1559
1560    assert(vs->magic == VNC_MAGIC);
1561    if (condition & G_IO_IN) {
1562        if (vnc_client_read(vs) < 0) {
1563            /* vs is free()ed here */
1564            return TRUE;
1565        }
1566    }
1567    if (condition & G_IO_OUT) {
1568        vnc_client_write(vs);
1569    }
1570
1571    if (vs->disconnecting) {
1572        if (vs->ioc_tag != 0) {
1573            g_source_remove(vs->ioc_tag);
1574        }
1575        vs->ioc_tag = 0;
1576    }
1577    return TRUE;
1578}
1579
1580
1581/*
1582 * Scale factor to apply to vs->throttle_output_offset when checking for
1583 * hard limit. Worst case normal usage could be x2, if we have a complete
1584 * incremental update and complete forced update in the output buffer.
1585 * So x3 should be good enough, but we pick x5 to be conservative and thus
1586 * (hopefully) never trigger incorrectly.
1587 */
1588#define VNC_THROTTLE_OUTPUT_LIMIT_SCALE 5
1589
1590void vnc_write(VncState *vs, const void *data, size_t len)
1591{
1592    assert(vs->magic == VNC_MAGIC);
1593    if (vs->disconnecting) {
1594        return;
1595    }
1596    /* Protection against malicious client/guest to prevent our output
1597     * buffer growing without bound if client stops reading data. This
1598     * should rarely trigger, because we have earlier throttling code
1599     * which stops issuing framebuffer updates and drops audio data
1600     * if the throttle_output_offset value is exceeded. So we only reach
1601     * this higher level if a huge number of pseudo-encodings get
1602     * triggered while data can't be sent on the socket.
1603     *
1604     * NB throttle_output_offset can be zero during early protocol
1605     * handshake, or from the job thread's VncState clone
1606     */
1607    if (vs->throttle_output_offset != 0 &&
1608        (vs->output.offset / VNC_THROTTLE_OUTPUT_LIMIT_SCALE) >
1609        vs->throttle_output_offset) {
1610        trace_vnc_client_output_limit(vs, vs->ioc, vs->output.offset,
1611                                      vs->throttle_output_offset);
1612        vnc_disconnect_start(vs);
1613        return;
1614    }
1615    buffer_reserve(&vs->output, len);
1616
1617    if (vs->ioc != NULL && buffer_empty(&vs->output)) {
1618        if (vs->ioc_tag) {
1619            g_source_remove(vs->ioc_tag);
1620        }
1621        vs->ioc_tag = qio_channel_add_watch(
1622            vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
1623    }
1624
1625    buffer_append(&vs->output, data, len);
1626}
1627
1628void vnc_write_s32(VncState *vs, int32_t value)
1629{
1630    vnc_write_u32(vs, *(uint32_t *)&value);
1631}
1632
1633void vnc_write_u32(VncState *vs, uint32_t value)
1634{
1635    uint8_t buf[4];
1636
1637    buf[0] = (value >> 24) & 0xFF;
1638    buf[1] = (value >> 16) & 0xFF;
1639    buf[2] = (value >>  8) & 0xFF;
1640    buf[3] = value & 0xFF;
1641
1642    vnc_write(vs, buf, 4);
1643}
1644
1645void vnc_write_u16(VncState *vs, uint16_t value)
1646{
1647    uint8_t buf[2];
1648
1649    buf[0] = (value >> 8) & 0xFF;
1650    buf[1] = value & 0xFF;
1651
1652    vnc_write(vs, buf, 2);
1653}
1654
1655void vnc_write_u8(VncState *vs, uint8_t value)
1656{
1657    vnc_write(vs, (char *)&value, 1);
1658}
1659
1660void vnc_flush(VncState *vs)
1661{
1662    vnc_lock_output(vs);
1663    if (vs->ioc != NULL && vs->output.offset) {
1664        vnc_client_write_locked(vs);
1665    }
1666    if (vs->disconnecting) {
1667        if (vs->ioc_tag != 0) {
1668            g_source_remove(vs->ioc_tag);
1669        }
1670        vs->ioc_tag = 0;
1671    }
1672    vnc_unlock_output(vs);
1673}
1674
1675static uint8_t read_u8(uint8_t *data, size_t offset)
1676{
1677    return data[offset];
1678}
1679
1680static uint16_t read_u16(uint8_t *data, size_t offset)
1681{
1682    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1683}
1684
1685static int32_t read_s32(uint8_t *data, size_t offset)
1686{
1687    return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1688                     (data[offset + 2] << 8) | data[offset + 3]);
1689}
1690
1691uint32_t read_u32(uint8_t *data, size_t offset)
1692{
1693    return ((data[offset] << 24) | (data[offset + 1] << 16) |
1694            (data[offset + 2] << 8) | data[offset + 3]);
1695}
1696
1697static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1698{
1699}
1700
1701static void check_pointer_type_change(Notifier *notifier, void *data)
1702{
1703    VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1704    int absolute = qemu_input_is_absolute();
1705
1706    if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1707        vnc_lock_output(vs);
1708        vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1709        vnc_write_u8(vs, 0);
1710        vnc_write_u16(vs, 1);
1711        vnc_framebuffer_update(vs, absolute, 0,
1712                               pixman_image_get_width(vs->vd->server),
1713                               pixman_image_get_height(vs->vd->server),
1714                               VNC_ENCODING_POINTER_TYPE_CHANGE);
1715        vnc_unlock_output(vs);
1716        vnc_flush(vs);
1717    }
1718    vs->absolute = absolute;
1719}
1720
1721static void pointer_event(VncState *vs, int button_mask, int x, int y)
1722{
1723    static uint32_t bmap[INPUT_BUTTON__MAX] = {
1724        [INPUT_BUTTON_LEFT]       = 0x01,
1725        [INPUT_BUTTON_MIDDLE]     = 0x02,
1726        [INPUT_BUTTON_RIGHT]      = 0x04,
1727        [INPUT_BUTTON_WHEEL_UP]   = 0x08,
1728        [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
1729    };
1730    QemuConsole *con = vs->vd->dcl.con;
1731    int width = pixman_image_get_width(vs->vd->server);
1732    int height = pixman_image_get_height(vs->vd->server);
1733
1734    if (vs->last_bmask != button_mask) {
1735        qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
1736        vs->last_bmask = button_mask;
1737    }
1738
1739    if (vs->absolute) {
1740        qemu_input_queue_abs(con, INPUT_AXIS_X, x, 0, width);
1741        qemu_input_queue_abs(con, INPUT_AXIS_Y, y, 0, height);
1742    } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1743        qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
1744        qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
1745    } else {
1746        if (vs->last_x != -1) {
1747            qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
1748            qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
1749        }
1750        vs->last_x = x;
1751        vs->last_y = y;
1752    }
1753    qemu_input_event_sync();
1754}
1755
1756static void press_key(VncState *vs, QKeyCode qcode)
1757{
1758    qkbd_state_key_event(vs->vd->kbd, qcode, true);
1759    qkbd_state_key_event(vs->vd->kbd, qcode, false);
1760}
1761
1762static void vnc_led_state_change(VncState *vs)
1763{
1764    if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
1765        return;
1766    }
1767
1768    vnc_lock_output(vs);
1769    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1770    vnc_write_u8(vs, 0);
1771    vnc_write_u16(vs, 1);
1772    vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
1773    vnc_write_u8(vs, vs->vd->ledstate);
1774    vnc_unlock_output(vs);
1775    vnc_flush(vs);
1776}
1777
1778static void kbd_leds(void *opaque, int ledstate)
1779{
1780    VncDisplay *vd = opaque;
1781    VncState *client;
1782
1783    trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
1784                             (ledstate & QEMU_NUM_LOCK_LED),
1785                             (ledstate & QEMU_SCROLL_LOCK_LED));
1786
1787    if (ledstate == vd->ledstate) {
1788        return;
1789    }
1790
1791    vd->ledstate = ledstate;
1792
1793    QTAILQ_FOREACH(client, &vd->clients, next) {
1794        vnc_led_state_change(client);
1795    }
1796}
1797
1798static void do_key_event(VncState *vs, int down, int keycode, int sym)
1799{
1800    QKeyCode qcode = qemu_input_key_number_to_qcode(keycode);
1801
1802    /* QEMU console switch */
1803    switch (qcode) {
1804    case Q_KEY_CODE_1 ... Q_KEY_CODE_9: /* '1' to '9' keys */
1805        if (vs->vd->dcl.con == NULL && down &&
1806            qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL) &&
1807            qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_ALT)) {
1808            /* Reset the modifiers sent to the current console */
1809            qkbd_state_lift_all_keys(vs->vd->kbd);
1810            console_select(qcode - Q_KEY_CODE_1);
1811            return;
1812        }
1813    default:
1814        break;
1815    }
1816
1817    /* Turn off the lock state sync logic if the client support the led
1818       state extension.
1819    */
1820    if (down && vs->vd->lock_key_sync &&
1821        !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1822        keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1823        /* If the numlock state needs to change then simulate an additional
1824           keypress before sending this one.  This will happen if the user
1825           toggles numlock away from the VNC window.
1826        */
1827        if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1828            if (!qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1829                trace_vnc_key_sync_numlock(true);
1830                press_key(vs, Q_KEY_CODE_NUM_LOCK);
1831            }
1832        } else {
1833            if (qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK)) {
1834                trace_vnc_key_sync_numlock(false);
1835                press_key(vs, Q_KEY_CODE_NUM_LOCK);
1836            }
1837        }
1838    }
1839
1840    if (down && vs->vd->lock_key_sync &&
1841        !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
1842        ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1843        /* If the capslock state needs to change then simulate an additional
1844           keypress before sending this one.  This will happen if the user
1845           toggles capslock away from the VNC window.
1846        */
1847        int uppercase = !!(sym >= 'A' && sym <= 'Z');
1848        bool shift = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_SHIFT);
1849        bool capslock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CAPSLOCK);
1850        if (capslock) {
1851            if (uppercase == shift) {
1852                trace_vnc_key_sync_capslock(false);
1853                press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1854            }
1855        } else {
1856            if (uppercase != shift) {
1857                trace_vnc_key_sync_capslock(true);
1858                press_key(vs, Q_KEY_CODE_CAPS_LOCK);
1859            }
1860        }
1861    }
1862
1863    qkbd_state_key_event(vs->vd->kbd, qcode, down);
1864    if (!qemu_console_is_graphic(NULL)) {
1865        bool numlock = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_NUMLOCK);
1866        bool control = qkbd_state_modifier_get(vs->vd->kbd, QKBD_MOD_CTRL);
1867        /* QEMU console emulation */
1868        if (down) {
1869            switch (keycode) {
1870            case 0x2a:                          /* Left Shift */
1871            case 0x36:                          /* Right Shift */
1872            case 0x1d:                          /* Left CTRL */
1873            case 0x9d:                          /* Right CTRL */
1874            case 0x38:                          /* Left ALT */
1875            case 0xb8:                          /* Right ALT */
1876                break;
1877            case 0xc8:
1878                kbd_put_keysym(QEMU_KEY_UP);
1879                break;
1880            case 0xd0:
1881                kbd_put_keysym(QEMU_KEY_DOWN);
1882                break;
1883            case 0xcb:
1884                kbd_put_keysym(QEMU_KEY_LEFT);
1885                break;
1886            case 0xcd:
1887                kbd_put_keysym(QEMU_KEY_RIGHT);
1888                break;
1889            case 0xd3:
1890                kbd_put_keysym(QEMU_KEY_DELETE);
1891                break;
1892            case 0xc7:
1893                kbd_put_keysym(QEMU_KEY_HOME);
1894                break;
1895            case 0xcf:
1896                kbd_put_keysym(QEMU_KEY_END);
1897                break;
1898            case 0xc9:
1899                kbd_put_keysym(QEMU_KEY_PAGEUP);
1900                break;
1901            case 0xd1:
1902                kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1903                break;
1904
1905            case 0x47:
1906                kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1907                break;
1908            case 0x48:
1909                kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1910                break;
1911            case 0x49:
1912                kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1913                break;
1914            case 0x4b:
1915                kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1916                break;
1917            case 0x4c:
1918                kbd_put_keysym('5');
1919                break;
1920            case 0x4d:
1921                kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1922                break;
1923            case 0x4f:
1924                kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1925                break;
1926            case 0x50:
1927                kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1928                break;
1929            case 0x51:
1930                kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1931                break;
1932            case 0x52:
1933                kbd_put_keysym('0');
1934                break;
1935            case 0x53:
1936                kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1937                break;
1938
1939            case 0xb5:
1940                kbd_put_keysym('/');
1941                break;
1942            case 0x37:
1943                kbd_put_keysym('*');
1944                break;
1945            case 0x4a:
1946                kbd_put_keysym('-');
1947                break;
1948            case 0x4e:
1949                kbd_put_keysym('+');
1950                break;
1951            case 0x9c:
1952                kbd_put_keysym('\n');
1953                break;
1954
1955            default:
1956                if (control) {
1957                    kbd_put_keysym(sym & 0x1f);
1958                } else {
1959                    kbd_put_keysym(sym);
1960                }
1961                break;
1962            }
1963        }
1964    }
1965}
1966
1967static const char *code2name(int keycode)
1968{
1969    return QKeyCode_str(qemu_input_key_number_to_qcode(keycode));
1970}
1971
1972static void key_event(VncState *vs, int down, uint32_t sym)
1973{
1974    int keycode;
1975    int lsym = sym;
1976
1977    if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
1978        lsym = lsym - 'A' + 'a';
1979    }
1980
1981    keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF,
1982                              vs->vd->kbd, down) & SCANCODE_KEYMASK;
1983    trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
1984    do_key_event(vs, down, keycode, sym);
1985}
1986
1987static void ext_key_event(VncState *vs, int down,
1988                          uint32_t sym, uint16_t keycode)
1989{
1990    /* if the user specifies a keyboard layout, always use it */
1991    if (keyboard_layout) {
1992        key_event(vs, down, sym);
1993    } else {
1994        trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
1995        do_key_event(vs, down, keycode, sym);
1996    }
1997}
1998
1999static void framebuffer_update_request(VncState *vs, int incremental,
2000                                       int x, int y, int w, int h)
2001{
2002    if (incremental) {
2003        if (vs->update != VNC_STATE_UPDATE_FORCE) {
2004            vs->update = VNC_STATE_UPDATE_INCREMENTAL;
2005        }
2006    } else {
2007        vs->update = VNC_STATE_UPDATE_FORCE;
2008        vnc_set_area_dirty(vs->dirty, vs->vd, x, y, w, h);
2009    }
2010}
2011
2012static void send_ext_key_event_ack(VncState *vs)
2013{
2014    vnc_lock_output(vs);
2015    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2016    vnc_write_u8(vs, 0);
2017    vnc_write_u16(vs, 1);
2018    vnc_framebuffer_update(vs, 0, 0,
2019                           pixman_image_get_width(vs->vd->server),
2020                           pixman_image_get_height(vs->vd->server),
2021                           VNC_ENCODING_EXT_KEY_EVENT);
2022    vnc_unlock_output(vs);
2023    vnc_flush(vs);
2024}
2025
2026static void send_ext_audio_ack(VncState *vs)
2027{
2028    vnc_lock_output(vs);
2029    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2030    vnc_write_u8(vs, 0);
2031    vnc_write_u16(vs, 1);
2032    vnc_framebuffer_update(vs, 0, 0,
2033                           pixman_image_get_width(vs->vd->server),
2034                           pixman_image_get_height(vs->vd->server),
2035                           VNC_ENCODING_AUDIO);
2036    vnc_unlock_output(vs);
2037    vnc_flush(vs);
2038}
2039
2040static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
2041{
2042    int i;
2043    unsigned int enc = 0;
2044
2045    vs->features = 0;
2046    vs->vnc_encoding = 0;
2047    vs->tight->compression = 9;
2048    vs->tight->quality = -1; /* Lossless by default */
2049    vs->absolute = -1;
2050
2051    /*
2052     * Start from the end because the encodings are sent in order of preference.
2053     * This way the preferred encoding (first encoding defined in the array)
2054     * will be set at the end of the loop.
2055     */
2056    for (i = n_encodings - 1; i >= 0; i--) {
2057        enc = encodings[i];
2058        switch (enc) {
2059        case VNC_ENCODING_RAW:
2060            vs->vnc_encoding = enc;
2061            break;
2062        case VNC_ENCODING_COPYRECT:
2063            vs->features |= VNC_FEATURE_COPYRECT_MASK;
2064            break;
2065        case VNC_ENCODING_HEXTILE:
2066            vs->features |= VNC_FEATURE_HEXTILE_MASK;
2067            vs->vnc_encoding = enc;
2068            break;
2069        case VNC_ENCODING_TIGHT:
2070            vs->features |= VNC_FEATURE_TIGHT_MASK;
2071            vs->vnc_encoding = enc;
2072            break;
2073#ifdef CONFIG_VNC_PNG
2074        case VNC_ENCODING_TIGHT_PNG:
2075            vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
2076            vs->vnc_encoding = enc;
2077            break;
2078#endif
2079        case VNC_ENCODING_ZLIB:
2080            vs->features |= VNC_FEATURE_ZLIB_MASK;
2081            vs->vnc_encoding = enc;
2082            break;
2083        case VNC_ENCODING_ZRLE:
2084            vs->features |= VNC_FEATURE_ZRLE_MASK;
2085            vs->vnc_encoding = enc;
2086            break;
2087        case VNC_ENCODING_ZYWRLE:
2088            vs->features |= VNC_FEATURE_ZYWRLE_MASK;
2089            vs->vnc_encoding = enc;
2090            break;
2091        case VNC_ENCODING_DESKTOPRESIZE:
2092            vs->features |= VNC_FEATURE_RESIZE_MASK;
2093            break;
2094        case VNC_ENCODING_POINTER_TYPE_CHANGE:
2095            vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
2096            break;
2097        case VNC_ENCODING_RICH_CURSOR:
2098            vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
2099            if (vs->vd->cursor) {
2100                vnc_cursor_define(vs);
2101            }
2102            break;
2103        case VNC_ENCODING_EXT_KEY_EVENT:
2104            send_ext_key_event_ack(vs);
2105            break;
2106        case VNC_ENCODING_AUDIO:
2107            send_ext_audio_ack(vs);
2108            break;
2109        case VNC_ENCODING_WMVi:
2110            vs->features |= VNC_FEATURE_WMVI_MASK;
2111            break;
2112        case VNC_ENCODING_LED_STATE:
2113            vs->features |= VNC_FEATURE_LED_STATE_MASK;
2114            break;
2115        case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
2116            vs->tight->compression = (enc & 0x0F);
2117            break;
2118        case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
2119            if (vs->vd->lossy) {
2120                vs->tight->quality = (enc & 0x0F);
2121            }
2122            break;
2123        default:
2124            VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
2125            break;
2126        }
2127    }
2128    vnc_desktop_resize(vs);
2129    check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
2130    vnc_led_state_change(vs);
2131}
2132
2133static void set_pixel_conversion(VncState *vs)
2134{
2135    pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
2136
2137    if (fmt == VNC_SERVER_FB_FORMAT) {
2138        vs->write_pixels = vnc_write_pixels_copy;
2139        vnc_hextile_set_pixel_conversion(vs, 0);
2140    } else {
2141        vs->write_pixels = vnc_write_pixels_generic;
2142        vnc_hextile_set_pixel_conversion(vs, 1);
2143    }
2144}
2145
2146static void send_color_map(VncState *vs)
2147{
2148    int i;
2149
2150    vnc_write_u8(vs, VNC_MSG_SERVER_SET_COLOUR_MAP_ENTRIES);
2151    vnc_write_u8(vs,  0);    /* padding     */
2152    vnc_write_u16(vs, 0);    /* first color */
2153    vnc_write_u16(vs, 256);  /* # of colors */
2154
2155    for (i = 0; i < 256; i++) {
2156        PixelFormat *pf = &vs->client_pf;
2157
2158        vnc_write_u16(vs, (((i >> pf->rshift) & pf->rmax) << (16 - pf->rbits)));
2159        vnc_write_u16(vs, (((i >> pf->gshift) & pf->gmax) << (16 - pf->gbits)));
2160        vnc_write_u16(vs, (((i >> pf->bshift) & pf->bmax) << (16 - pf->bbits)));
2161    }
2162}
2163
2164static void set_pixel_format(VncState *vs, int bits_per_pixel,
2165                             int big_endian_flag, int true_color_flag,
2166                             int red_max, int green_max, int blue_max,
2167                             int red_shift, int green_shift, int blue_shift)
2168{
2169    if (!true_color_flag) {
2170        /* Expose a reasonable default 256 color map */
2171        bits_per_pixel = 8;
2172        red_max = 7;
2173        green_max = 7;
2174        blue_max = 3;
2175        red_shift = 0;
2176        green_shift = 3;
2177        blue_shift = 6;
2178    }
2179
2180    switch (bits_per_pixel) {
2181    case 8:
2182    case 16:
2183    case 32:
2184        break;
2185    default:
2186        vnc_client_error(vs);
2187        return;
2188    }
2189
2190    vs->client_pf.rmax = red_max ? red_max : 0xFF;
2191    vs->client_pf.rbits = ctpopl(red_max);
2192    vs->client_pf.rshift = red_shift;
2193    vs->client_pf.rmask = red_max << red_shift;
2194    vs->client_pf.gmax = green_max ? green_max : 0xFF;
2195    vs->client_pf.gbits = ctpopl(green_max);
2196    vs->client_pf.gshift = green_shift;
2197    vs->client_pf.gmask = green_max << green_shift;
2198    vs->client_pf.bmax = blue_max ? blue_max : 0xFF;
2199    vs->client_pf.bbits = ctpopl(blue_max);
2200    vs->client_pf.bshift = blue_shift;
2201    vs->client_pf.bmask = blue_max << blue_shift;
2202    vs->client_pf.bits_per_pixel = bits_per_pixel;
2203    vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
2204    vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
2205    vs->client_be = big_endian_flag;
2206
2207    if (!true_color_flag) {
2208        send_color_map(vs);
2209    }
2210
2211    set_pixel_conversion(vs);
2212
2213    graphic_hw_invalidate(vs->vd->dcl.con);
2214    graphic_hw_update(vs->vd->dcl.con);
2215}
2216
2217static void pixel_format_message (VncState *vs) {
2218    char pad[3] = { 0, 0, 0 };
2219
2220    vs->client_pf = qemu_default_pixelformat(32);
2221
2222    vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
2223    vnc_write_u8(vs, vs->client_pf.depth); /* depth */
2224
2225#ifdef HOST_WORDS_BIGENDIAN
2226    vnc_write_u8(vs, 1);             /* big-endian-flag */
2227#else
2228    vnc_write_u8(vs, 0);             /* big-endian-flag */
2229#endif
2230    vnc_write_u8(vs, 1);             /* true-color-flag */
2231    vnc_write_u16(vs, vs->client_pf.rmax);     /* red-max */
2232    vnc_write_u16(vs, vs->client_pf.gmax);     /* green-max */
2233    vnc_write_u16(vs, vs->client_pf.bmax);     /* blue-max */
2234    vnc_write_u8(vs, vs->client_pf.rshift);    /* red-shift */
2235    vnc_write_u8(vs, vs->client_pf.gshift);    /* green-shift */
2236    vnc_write_u8(vs, vs->client_pf.bshift);    /* blue-shift */
2237    vnc_write(vs, pad, 3);           /* padding */
2238
2239    vnc_hextile_set_pixel_conversion(vs, 0);
2240    vs->write_pixels = vnc_write_pixels_copy;
2241}
2242
2243static void vnc_colordepth(VncState *vs)
2244{
2245    if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
2246        /* Sending a WMVi message to notify the client*/
2247        vnc_lock_output(vs);
2248        vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
2249        vnc_write_u8(vs, 0);
2250        vnc_write_u16(vs, 1); /* number of rects */
2251        vnc_framebuffer_update(vs, 0, 0,
2252                               pixman_image_get_width(vs->vd->server),
2253                               pixman_image_get_height(vs->vd->server),
2254                               VNC_ENCODING_WMVi);
2255        pixel_format_message(vs);
2256        vnc_unlock_output(vs);
2257        vnc_flush(vs);
2258    } else {
2259        set_pixel_conversion(vs);
2260    }
2261}
2262
2263static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
2264{
2265    int i;
2266    uint16_t limit;
2267    uint32_t freq;
2268    VncDisplay *vd = vs->vd;
2269
2270    if (data[0] > 3) {
2271        update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2272    }
2273
2274    switch (data[0]) {
2275    case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
2276        if (len == 1)
2277            return 20;
2278
2279        set_pixel_format(vs, read_u8(data, 4),
2280                         read_u8(data, 6), read_u8(data, 7),
2281                         read_u16(data, 8), read_u16(data, 10),
2282                         read_u16(data, 12), read_u8(data, 14),
2283                         read_u8(data, 15), read_u8(data, 16));
2284        break;
2285    case VNC_MSG_CLIENT_SET_ENCODINGS:
2286        if (len == 1)
2287            return 4;
2288
2289        if (len == 4) {
2290            limit = read_u16(data, 2);
2291            if (limit > 0)
2292                return 4 + (limit * 4);
2293        } else
2294            limit = read_u16(data, 2);
2295
2296        for (i = 0; i < limit; i++) {
2297            int32_t val = read_s32(data, 4 + (i * 4));
2298            memcpy(data + 4 + (i * 4), &val, sizeof(val));
2299        }
2300
2301        set_encodings(vs, (int32_t *)(data + 4), limit);
2302        break;
2303    case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
2304        if (len == 1)
2305            return 10;
2306
2307        framebuffer_update_request(vs,
2308                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2309                                   read_u16(data, 6), read_u16(data, 8));
2310        break;
2311    case VNC_MSG_CLIENT_KEY_EVENT:
2312        if (len == 1)
2313            return 8;
2314
2315        key_event(vs, read_u8(data, 1), read_u32(data, 4));
2316        break;
2317    case VNC_MSG_CLIENT_POINTER_EVENT:
2318        if (len == 1)
2319            return 6;
2320
2321        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2322        break;
2323    case VNC_MSG_CLIENT_CUT_TEXT:
2324        if (len == 1) {
2325            return 8;
2326        }
2327        if (len == 8) {
2328            uint32_t dlen = read_u32(data, 4);
2329            if (dlen > (1 << 20)) {
2330                error_report("vnc: client_cut_text msg payload has %u bytes"
2331                             " which exceeds our limit of 1MB.", dlen);
2332                vnc_client_error(vs);
2333                break;
2334            }
2335            if (dlen > 0) {
2336                return 8 + dlen;
2337            }
2338        }
2339
2340        client_cut_text(vs, read_u32(data, 4), data + 8);
2341        break;
2342    case VNC_MSG_CLIENT_QEMU:
2343        if (len == 1)
2344            return 2;
2345
2346        switch (read_u8(data, 1)) {
2347        case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2348            if (len == 2)
2349                return 12;
2350
2351            ext_key_event(vs, read_u16(data, 2),
2352                          read_u32(data, 4), read_u32(data, 8));
2353            break;
2354        case VNC_MSG_CLIENT_QEMU_AUDIO:
2355            if (len == 2)
2356                return 4;
2357
2358            switch (read_u16 (data, 2)) {
2359            case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2360                audio_add(vs);
2361                break;
2362            case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2363                audio_del(vs);
2364                break;
2365            case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2366                if (len == 4)
2367                    return 10;
2368                switch (read_u8(data, 4)) {
2369                case 0: vs->as.fmt = AUDIO_FORMAT_U8; break;
2370                case 1: vs->as.fmt = AUDIO_FORMAT_S8; break;
2371                case 2: vs->as.fmt = AUDIO_FORMAT_U16; break;
2372                case 3: vs->as.fmt = AUDIO_FORMAT_S16; break;
2373                case 4: vs->as.fmt = AUDIO_FORMAT_U32; break;
2374                case 5: vs->as.fmt = AUDIO_FORMAT_S32; break;
2375                default:
2376                    VNC_DEBUG("Invalid audio format %d\n", read_u8(data, 4));
2377                    vnc_client_error(vs);
2378                    break;
2379                }
2380                vs->as.nchannels = read_u8(data, 5);
2381                if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2382                    VNC_DEBUG("Invalid audio channel count %d\n",
2383                              read_u8(data, 5));
2384                    vnc_client_error(vs);
2385                    break;
2386                }
2387                freq = read_u32(data, 6);
2388                /* No official limit for protocol, but 48khz is a sensible
2389                 * upper bound for trustworthy clients, and this limit
2390                 * protects calculations involving 'vs->as.freq' later.
2391                 */
2392                if (freq > 48000) {
2393                    VNC_DEBUG("Invalid audio frequency %u > 48000", freq);
2394                    vnc_client_error(vs);
2395                    break;
2396                }
2397                vs->as.freq = freq;
2398                break;
2399            default:
2400                VNC_DEBUG("Invalid audio message %d\n", read_u8(data, 4));
2401                vnc_client_error(vs);
2402                break;
2403            }
2404            break;
2405
2406        default:
2407            VNC_DEBUG("Msg: %d\n", read_u16(data, 0));
2408            vnc_client_error(vs);
2409            break;
2410        }
2411        break;
2412    default:
2413        VNC_DEBUG("Msg: %d\n", data[0]);
2414        vnc_client_error(vs);
2415        break;
2416    }
2417
2418    vnc_update_throttle_offset(vs);
2419    vnc_read_when(vs, protocol_client_msg, 1);
2420    return 0;
2421}
2422
2423static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2424{
2425    char buf[1024];
2426    VncShareMode mode;
2427    int size;
2428
2429    mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2430    switch (vs->vd->share_policy) {
2431    case VNC_SHARE_POLICY_IGNORE:
2432        /*
2433         * Ignore the shared flag.  Nothing to do here.
2434         *
2435         * Doesn't conform to the rfb spec but is traditional qemu
2436         * behavior, thus left here as option for compatibility
2437         * reasons.
2438         */
2439        break;
2440    case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2441        /*
2442         * Policy: Allow clients ask for exclusive access.
2443         *
2444         * Implementation: When a client asks for exclusive access,
2445         * disconnect all others. Shared connects are allowed as long
2446         * as no exclusive connection exists.
2447         *
2448         * This is how the rfb spec suggests to handle the shared flag.
2449         */
2450        if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2451            VncState *client;
2452            QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2453                if (vs == client) {
2454                    continue;
2455                }
2456                if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2457                    client->share_mode != VNC_SHARE_MODE_SHARED) {
2458                    continue;
2459                }
2460                vnc_disconnect_start(client);
2461            }
2462        }
2463        if (mode == VNC_SHARE_MODE_SHARED) {
2464            if (vs->vd->num_exclusive > 0) {
2465                vnc_disconnect_start(vs);
2466                return 0;
2467            }
2468        }
2469        break;
2470    case VNC_SHARE_POLICY_FORCE_SHARED:
2471        /*
2472         * Policy: Shared connects only.
2473         * Implementation: Disallow clients asking for exclusive access.
2474         *
2475         * Useful for shared desktop sessions where you don't want
2476         * someone forgetting to say -shared when running the vnc
2477         * client disconnect everybody else.
2478         */
2479        if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2480            vnc_disconnect_start(vs);
2481            return 0;
2482        }
2483        break;
2484    }
2485    vnc_set_share_mode(vs, mode);
2486
2487    if (vs->vd->num_shared > vs->vd->connections_limit) {
2488        vnc_disconnect_start(vs);
2489        return 0;
2490    }
2491
2492    assert(pixman_image_get_width(vs->vd->server) < 65536 &&
2493           pixman_image_get_width(vs->vd->server) >= 0);
2494    assert(pixman_image_get_height(vs->vd->server) < 65536 &&
2495           pixman_image_get_height(vs->vd->server) >= 0);
2496    vs->client_width = pixman_image_get_width(vs->vd->server);
2497    vs->client_height = pixman_image_get_height(vs->vd->server);
2498    vnc_write_u16(vs, vs->client_width);
2499    vnc_write_u16(vs, vs->client_height);
2500
2501    pixel_format_message(vs);
2502
2503    if (qemu_name) {
2504        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2505        if (size > sizeof(buf)) {
2506            size = sizeof(buf);
2507        }
2508    } else {
2509        size = snprintf(buf, sizeof(buf), "QEMU");
2510    }
2511
2512    vnc_write_u32(vs, size);
2513    vnc_write(vs, buf, size);
2514    vnc_flush(vs);
2515
2516    vnc_client_cache_auth(vs);
2517    vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
2518
2519    vnc_read_when(vs, protocol_client_msg, 1);
2520
2521    return 0;
2522}
2523
2524void start_client_init(VncState *vs)
2525{
2526    vnc_read_when(vs, protocol_client_init, 1);
2527}
2528
2529static void authentication_failed(VncState *vs)
2530{
2531    vnc_write_u32(vs, 1); /* Reject auth */
2532    if (vs->minor >= 8) {
2533        static const char err[] = "Authentication failed";
2534        vnc_write_u32(vs, sizeof(err));
2535        vnc_write(vs, err, sizeof(err));
2536    }
2537    vnc_flush(vs);
2538    vnc_client_error(vs);
2539}
2540
2541static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2542{
2543    unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2544    size_t i, pwlen;
2545    unsigned char key[8];
2546    time_t now = time(NULL);
2547    QCryptoCipher *cipher = NULL;
2548    Error *err = NULL;
2549
2550    if (!vs->vd->password) {
2551        trace_vnc_auth_fail(vs, vs->auth, "password is not set", "");
2552        goto reject;
2553    }
2554    if (vs->vd->expires < now) {
2555        trace_vnc_auth_fail(vs, vs->auth, "password is expired", "");
2556        goto reject;
2557    }
2558
2559    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2560
2561    /* Calculate the expected challenge response */
2562    pwlen = strlen(vs->vd->password);
2563    for (i=0; i<sizeof(key); i++)
2564        key[i] = i<pwlen ? vs->vd->password[i] : 0;
2565
2566    cipher = qcrypto_cipher_new(
2567        QCRYPTO_CIPHER_ALG_DES_RFB,
2568        QCRYPTO_CIPHER_MODE_ECB,
2569        key, G_N_ELEMENTS(key),
2570        &err);
2571    if (!cipher) {
2572        trace_vnc_auth_fail(vs, vs->auth, "cannot create cipher",
2573                            error_get_pretty(err));
2574        error_free(err);
2575        goto reject;
2576    }
2577
2578    if (qcrypto_cipher_encrypt(cipher,
2579                               vs->challenge,
2580                               response,
2581                               VNC_AUTH_CHALLENGE_SIZE,
2582                               &err) < 0) {
2583        trace_vnc_auth_fail(vs, vs->auth, "cannot encrypt challenge response",
2584                            error_get_pretty(err));
2585        error_free(err);
2586        goto reject;
2587    }
2588
2589    /* Compare expected vs actual challenge response */
2590    if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2591        trace_vnc_auth_fail(vs, vs->auth, "mis-matched challenge response", "");
2592        goto reject;
2593    } else {
2594        trace_vnc_auth_pass(vs, vs->auth);
2595        vnc_write_u32(vs, 0); /* Accept auth */
2596        vnc_flush(vs);
2597
2598        start_client_init(vs);
2599    }
2600
2601    qcrypto_cipher_free(cipher);
2602    return 0;
2603
2604reject:
2605    authentication_failed(vs);
2606    qcrypto_cipher_free(cipher);
2607    return 0;
2608}
2609
2610void start_auth_vnc(VncState *vs)
2611{
2612    Error *err = NULL;
2613
2614    if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
2615        trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
2616                            error_get_pretty(err));
2617        error_free(err);
2618        authentication_failed(vs);
2619        return;
2620    }
2621
2622    /* Send client a 'random' challenge */
2623    vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2624    vnc_flush(vs);
2625
2626    vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2627}
2628
2629
2630static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2631{
2632    /* We only advertise 1 auth scheme at a time, so client
2633     * must pick the one we sent. Verify this */
2634    if (data[0] != vs->auth) { /* Reject auth */
2635       trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
2636       authentication_failed(vs);
2637    } else { /* Accept requested auth */
2638       trace_vnc_auth_start(vs, vs->auth);
2639       switch (vs->auth) {
2640       case VNC_AUTH_NONE:
2641           if (vs->minor >= 8) {
2642               vnc_write_u32(vs, 0); /* Accept auth completion */
2643               vnc_flush(vs);
2644           }
2645           trace_vnc_auth_pass(vs, vs->auth);
2646           start_client_init(vs);
2647           break;
2648
2649       case VNC_AUTH_VNC:
2650           start_auth_vnc(vs);
2651           break;
2652
2653       case VNC_AUTH_VENCRYPT:
2654           start_auth_vencrypt(vs);
2655           break;
2656
2657#ifdef CONFIG_VNC_SASL
2658       case VNC_AUTH_SASL:
2659           start_auth_sasl(vs);
2660           break;
2661#endif /* CONFIG_VNC_SASL */
2662
2663       default: /* Should not be possible, but just in case */
2664           trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
2665           authentication_failed(vs);
2666       }
2667    }
2668    return 0;
2669}
2670
2671static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2672{
2673    char local[13];
2674
2675    memcpy(local, version, 12);
2676    local[12] = 0;
2677
2678    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2679        VNC_DEBUG("Malformed protocol version %s\n", local);
2680        vnc_client_error(vs);
2681        return 0;
2682    }
2683    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2684    if (vs->major != 3 ||
2685        (vs->minor != 3 &&
2686         vs->minor != 4 &&
2687         vs->minor != 5 &&
2688         vs->minor != 7 &&
2689         vs->minor != 8)) {
2690        VNC_DEBUG("Unsupported client version\n");
2691        vnc_write_u32(vs, VNC_AUTH_INVALID);
2692        vnc_flush(vs);
2693        vnc_client_error(vs);
2694        return 0;
2695    }
2696    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2697     * as equivalent to v3.3 by servers
2698     */
2699    if (vs->minor == 4 || vs->minor == 5)
2700        vs->minor = 3;
2701
2702    if (vs->minor == 3) {
2703        trace_vnc_auth_start(vs, vs->auth);
2704        if (vs->auth == VNC_AUTH_NONE) {
2705            vnc_write_u32(vs, vs->auth);
2706            vnc_flush(vs);
2707            trace_vnc_auth_pass(vs, vs->auth);
2708            start_client_init(vs);
2709       } else if (vs->auth == VNC_AUTH_VNC) {
2710            VNC_DEBUG("Tell client VNC auth\n");
2711            vnc_write_u32(vs, vs->auth);
2712            vnc_flush(vs);
2713            start_auth_vnc(vs);
2714       } else {
2715            trace_vnc_auth_fail(vs, vs->auth,
2716                                "Unsupported auth method for v3.3", "");
2717            vnc_write_u32(vs, VNC_AUTH_INVALID);
2718            vnc_flush(vs);
2719            vnc_client_error(vs);
2720       }
2721    } else {
2722        vnc_write_u8(vs, 1); /* num auth */
2723        vnc_write_u8(vs, vs->auth);
2724        vnc_read_when(vs, protocol_client_auth, 1);
2725        vnc_flush(vs);
2726    }
2727
2728    return 0;
2729}
2730
2731static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2732{
2733    struct VncSurface *vs = &vd->guest;
2734
2735    return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2736}
2737
2738void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2739{
2740    int i, j;
2741
2742    w = (x + w) / VNC_STAT_RECT;
2743    h = (y + h) / VNC_STAT_RECT;
2744    x /= VNC_STAT_RECT;
2745    y /= VNC_STAT_RECT;
2746
2747    for (j = y; j <= h; j++) {
2748        for (i = x; i <= w; i++) {
2749            vs->lossy_rect[j][i] = 1;
2750        }
2751    }
2752}
2753
2754static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2755{
2756    VncState *vs;
2757    int sty = y / VNC_STAT_RECT;
2758    int stx = x / VNC_STAT_RECT;
2759    int has_dirty = 0;
2760
2761    y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2762    x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2763
2764    QTAILQ_FOREACH(vs, &vd->clients, next) {
2765        int j;
2766
2767        /* kernel send buffers are full -> refresh later */
2768        if (vs->output.offset) {
2769            continue;
2770        }
2771
2772        if (!vs->lossy_rect[sty][stx]) {
2773            continue;
2774        }
2775
2776        vs->lossy_rect[sty][stx] = 0;
2777        for (j = 0; j < VNC_STAT_RECT; ++j) {
2778            bitmap_set(vs->dirty[y + j],
2779                       x / VNC_DIRTY_PIXELS_PER_BIT,
2780                       VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
2781        }
2782        has_dirty++;
2783    }
2784
2785    return has_dirty;
2786}
2787
2788static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2789{
2790    int width = MIN(pixman_image_get_width(vd->guest.fb),
2791                    pixman_image_get_width(vd->server));
2792    int height = MIN(pixman_image_get_height(vd->guest.fb),
2793                     pixman_image_get_height(vd->server));
2794    int x, y;
2795    struct timeval res;
2796    int has_dirty = 0;
2797
2798    for (y = 0; y < height; y += VNC_STAT_RECT) {
2799        for (x = 0; x < width; x += VNC_STAT_RECT) {
2800            VncRectStat *rect = vnc_stat_rect(vd, x, y);
2801
2802            rect->updated = false;
2803        }
2804    }
2805
2806    qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2807
2808    if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2809        return has_dirty;
2810    }
2811    vd->guest.last_freq_check = *tv;
2812
2813    for (y = 0; y < height; y += VNC_STAT_RECT) {
2814        for (x = 0; x < width; x += VNC_STAT_RECT) {
2815            VncRectStat *rect= vnc_stat_rect(vd, x, y);
2816            int count = ARRAY_SIZE(rect->times);
2817            struct timeval min, max;
2818
2819            if (!timerisset(&rect->times[count - 1])) {
2820                continue ;
2821            }
2822
2823            max = rect->times[(rect->idx + count - 1) % count];
2824            qemu_timersub(tv, &max, &res);
2825
2826            if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2827                rect->freq = 0;
2828                has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2829                memset(rect->times, 0, sizeof (rect->times));
2830                continue ;
2831            }
2832
2833            min = rect->times[rect->idx];
2834            max = rect->times[(rect->idx + count - 1) % count];
2835            qemu_timersub(&max, &min, &res);
2836
2837            rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2838            rect->freq /= count;
2839            rect->freq = 1. / rect->freq;
2840        }
2841    }
2842    return has_dirty;
2843}
2844
2845double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2846{
2847    int i, j;
2848    double total = 0;
2849    int num = 0;
2850
2851    x =  QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
2852    y =  QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
2853
2854    for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2855        for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2856            total += vnc_stat_rect(vs->vd, i, j)->freq;
2857            num++;
2858        }
2859    }
2860
2861    if (num) {
2862        return total / num;
2863    } else {
2864        return 0;
2865    }
2866}
2867
2868static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2869{
2870    VncRectStat *rect;
2871
2872    rect = vnc_stat_rect(vd, x, y);
2873    if (rect->updated) {
2874        return ;
2875    }
2876    rect->times[rect->idx] = *tv;
2877    rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2878    rect->updated = true;
2879}
2880
2881static int vnc_refresh_server_surface(VncDisplay *vd)
2882{
2883    int width = MIN(pixman_image_get_width(vd->guest.fb),
2884                    pixman_image_get_width(vd->server));
2885    int height = MIN(pixman_image_get_height(vd->guest.fb),
2886                     pixman_image_get_height(vd->server));
2887    int cmp_bytes, server_stride, line_bytes, guest_ll, guest_stride, y = 0;
2888    uint8_t *guest_row0 = NULL, *server_row0;
2889    VncState *vs;
2890    int has_dirty = 0;
2891    pixman_image_t *tmpbuf = NULL;
2892
2893    struct timeval tv = { 0, 0 };
2894
2895    if (!vd->non_adaptive) {
2896        gettimeofday(&tv, NULL);
2897        has_dirty = vnc_update_stats(vd, &tv);
2898    }
2899
2900    /*
2901     * Walk through the guest dirty map.
2902     * Check and copy modified bits from guest to server surface.
2903     * Update server dirty map.
2904     */
2905    server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
2906    server_stride = guest_stride = guest_ll =
2907        pixman_image_get_stride(vd->server);
2908    cmp_bytes = MIN(VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES,
2909                    server_stride);
2910    if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2911        int width = pixman_image_get_width(vd->server);
2912        tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
2913    } else {
2914        int guest_bpp =
2915            PIXMAN_FORMAT_BPP(pixman_image_get_format(vd->guest.fb));
2916        guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
2917        guest_stride = pixman_image_get_stride(vd->guest.fb);
2918        guest_ll = pixman_image_get_width(vd->guest.fb)
2919                   * DIV_ROUND_UP(guest_bpp, 8);
2920    }
2921    line_bytes = MIN(server_stride, guest_ll);
2922
2923    for (;;) {
2924        int x;
2925        uint8_t *guest_ptr, *server_ptr;
2926        unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
2927                                             height * VNC_DIRTY_BPL(&vd->guest),
2928                                             y * VNC_DIRTY_BPL(&vd->guest));
2929        if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
2930            /* no more dirty bits */
2931            break;
2932        }
2933        y = offset / VNC_DIRTY_BPL(&vd->guest);
2934        x = offset % VNC_DIRTY_BPL(&vd->guest);
2935
2936        server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
2937
2938        if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
2939            qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
2940            guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
2941        } else {
2942            guest_ptr = guest_row0 + y * guest_stride;
2943        }
2944        guest_ptr += x * cmp_bytes;
2945
2946        for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
2947             x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2948            int _cmp_bytes = cmp_bytes;
2949            if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
2950                continue;
2951            }
2952            if ((x + 1) * cmp_bytes > line_bytes) {
2953                _cmp_bytes = line_bytes - x * cmp_bytes;
2954            }
2955            assert(_cmp_bytes >= 0);
2956            if (memcmp(server_ptr, guest_ptr, _cmp_bytes) == 0) {
2957                continue;
2958            }
2959            memcpy(server_ptr, guest_ptr, _cmp_bytes);
2960            if (!vd->non_adaptive) {
2961                vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
2962                                 y, &tv);
2963            }
2964            QTAILQ_FOREACH(vs, &vd->clients, next) {
2965                set_bit(x, vs->dirty[y]);
2966            }
2967            has_dirty++;
2968        }
2969
2970        y++;
2971    }
2972    qemu_pixman_image_unref(tmpbuf);
2973    return has_dirty;
2974}
2975
2976static void vnc_refresh(DisplayChangeListener *dcl)
2977{
2978    VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
2979    VncState *vs, *vn;
2980    int has_dirty, rects = 0;
2981
2982    if (QTAILQ_EMPTY(&vd->clients)) {
2983        update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
2984        return;
2985    }
2986
2987    graphic_hw_update(vd->dcl.con);
2988
2989    if (vnc_trylock_display(vd)) {
2990        update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
2991        return;
2992    }
2993
2994    has_dirty = vnc_refresh_server_surface(vd);
2995    vnc_unlock_display(vd);
2996
2997    QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2998        rects += vnc_update_client(vs, has_dirty);
2999        /* vs might be free()ed here */
3000    }
3001
3002    if (has_dirty && rects) {
3003        vd->dcl.update_interval /= 2;
3004        if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
3005            vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
3006        }
3007    } else {
3008        vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
3009        if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
3010            vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
3011        }
3012    }
3013}
3014
3015static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,
3016                        bool skipauth, bool websocket)
3017{
3018    VncState *vs = g_new0(VncState, 1);
3019    bool first_client = QTAILQ_EMPTY(&vd->clients);
3020    int i;
3021
3022    trace_vnc_client_connect(vs, sioc);
3023    vs->zrle = g_new0(VncZrle, 1);
3024    vs->tight = g_new0(VncTight, 1);
3025    vs->magic = VNC_MAGIC;
3026    vs->sioc = sioc;
3027    object_ref(OBJECT(vs->sioc));
3028    vs->ioc = QIO_CHANNEL(sioc);
3029    object_ref(OBJECT(vs->ioc));
3030    vs->vd = vd;
3031
3032    buffer_init(&vs->input,          "vnc-input/%p", sioc);
3033    buffer_init(&vs->output,         "vnc-output/%p", sioc);
3034    buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);
3035
3036    buffer_init(&vs->tight->tight,    "vnc-tight/%p", sioc);
3037    buffer_init(&vs->tight->zlib,     "vnc-tight-zlib/%p", sioc);
3038    buffer_init(&vs->tight->gradient, "vnc-tight-gradient/%p", sioc);
3039#ifdef CONFIG_VNC_JPEG
3040    buffer_init(&vs->tight->jpeg,     "vnc-tight-jpeg/%p", sioc);
3041#endif
3042#ifdef CONFIG_VNC_PNG
3043    buffer_init(&vs->tight->png,      "vnc-tight-png/%p", sioc);
3044#endif
3045    buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);
3046    buffer_init(&vs->zrle->zrle,      "vnc-zrle/%p", sioc);
3047    buffer_init(&vs->zrle->fb,        "vnc-zrle-fb/%p", sioc);
3048    buffer_init(&vs->zrle->zlib,      "vnc-zrle-zlib/%p", sioc);
3049
3050    if (skipauth) {
3051        vs->auth = VNC_AUTH_NONE;
3052        vs->subauth = VNC_AUTH_INVALID;
3053    } else {
3054        if (websocket) {
3055            vs->auth = vd->ws_auth;
3056            vs->subauth = VNC_AUTH_INVALID;
3057        } else {
3058            vs->auth = vd->auth;
3059            vs->subauth = vd->subauth;
3060        }
3061    }
3062    VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",
3063              sioc, websocket, vs->auth, vs->subauth);
3064
3065    vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
3066    for (i = 0; i < VNC_STAT_ROWS; ++i) {
3067        vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);
3068    }
3069
3070    VNC_DEBUG("New client on socket %p\n", vs->sioc);
3071    update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
3072    qio_channel_set_blocking(vs->ioc, false, NULL);
3073    if (vs->ioc_tag) {
3074        g_source_remove(vs->ioc_tag);
3075    }
3076    if (websocket) {
3077        vs->websocket = 1;
3078        if (vd->tlscreds) {
3079            vs->ioc_tag = qio_channel_add_watch(
3080                vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);
3081        } else {
3082            vs->ioc_tag = qio_channel_add_watch(
3083                vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);
3084        }
3085    } else {
3086        vs->ioc_tag = qio_channel_add_watch(
3087            vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);
3088    }
3089
3090    vnc_client_cache_addr(vs);
3091    vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
3092    vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
3093
3094    vs->last_x = -1;
3095    vs->last_y = -1;
3096
3097    vs->as.freq = 44100;
3098    vs->as.nchannels = 2;
3099    vs->as.fmt = AUDIO_FORMAT_S16;
3100    vs->as.endianness = 0;
3101
3102    qemu_mutex_init(&vs->output_mutex);
3103    vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
3104
3105    QTAILQ_INSERT_TAIL(&vd->clients, vs, next);
3106    if (first_client) {
3107        vnc_update_server_surface(vd);
3108    }
3109
3110    graphic_hw_update(vd->dcl.con);
3111
3112    if (!vs->websocket) {
3113        vnc_start_protocol(vs);
3114    }
3115
3116    if (vd->num_connecting > vd->connections_limit) {
3117        QTAILQ_FOREACH(vs, &vd->clients, next) {
3118            if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {
3119                vnc_disconnect_start(vs);
3120                return;
3121            }
3122        }
3123    }
3124}
3125
3126void vnc_start_protocol(VncState *vs)
3127{
3128    vnc_write(vs, "RFB 003.008\n", 12);
3129    vnc_flush(vs);
3130    vnc_read_when(vs, protocol_version, 12);
3131
3132    vs->mouse_mode_notifier.notify = check_pointer_type_change;
3133    qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
3134}
3135
3136static void vnc_listen_io(QIONetListener *listener,
3137                          QIOChannelSocket *cioc,
3138                          void *opaque)
3139{
3140    VncDisplay *vd = opaque;
3141    bool isWebsock = listener == vd->wslistener;
3142
3143    qio_channel_set_name(QIO_CHANNEL(cioc),
3144                         isWebsock ? "vnc-ws-server" : "vnc-server");
3145    qio_channel_set_delay(QIO_CHANNEL(cioc), false);
3146    vnc_connect(vd, cioc, false, isWebsock);
3147}
3148
3149static const DisplayChangeListenerOps dcl_ops = {
3150    .dpy_name             = "vnc",
3151    .dpy_refresh          = vnc_refresh,
3152    .dpy_gfx_update       = vnc_dpy_update,
3153    .dpy_gfx_switch       = vnc_dpy_switch,
3154    .dpy_gfx_check_format = qemu_pixman_check_format,
3155    .dpy_mouse_set        = vnc_mouse_set,
3156    .dpy_cursor_define    = vnc_dpy_cursor_define,
3157};
3158
3159void vnc_display_init(const char *id, Error **errp)
3160{
3161    VncDisplay *vd;
3162
3163    if (vnc_display_find(id) != NULL) {
3164        return;
3165    }
3166    vd = g_malloc0(sizeof(*vd));
3167
3168    vd->id = strdup(id);
3169    QTAILQ_INSERT_TAIL(&vnc_displays, vd, next);
3170
3171    QTAILQ_INIT(&vd->clients);
3172    vd->expires = TIME_MAX;
3173
3174    if (keyboard_layout) {
3175        trace_vnc_key_map_init(keyboard_layout);
3176        vd->kbd_layout = init_keyboard_layout(name2keysym,
3177                                              keyboard_layout, errp);
3178    } else {
3179        vd->kbd_layout = init_keyboard_layout(name2keysym, "en-us", errp);
3180    }
3181
3182    if (!vd->kbd_layout) {
3183        return;
3184    }
3185
3186    vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3187    vd->connections_limit = 32;
3188
3189    qemu_mutex_init(&vd->mutex);
3190    vnc_start_worker_thread();
3191
3192    vd->dcl.ops = &dcl_ops;
3193    register_displaychangelistener(&vd->dcl);
3194    vd->kbd = qkbd_state_init(vd->dcl.con);
3195}
3196
3197
3198static void vnc_display_close(VncDisplay *vd)
3199{
3200    if (!vd) {
3201        return;
3202    }
3203    vd->is_unix = false;
3204
3205    if (vd->listener) {
3206        qio_net_listener_disconnect(vd->listener);
3207        object_unref(OBJECT(vd->listener));
3208    }
3209    vd->listener = NULL;
3210
3211    if (vd->wslistener) {
3212        qio_net_listener_disconnect(vd->wslistener);
3213        object_unref(OBJECT(vd->wslistener));
3214    }
3215    vd->wslistener = NULL;
3216
3217    vd->auth = VNC_AUTH_INVALID;
3218    vd->subauth = VNC_AUTH_INVALID;
3219    if (vd->tlscreds) {
3220        object_unparent(OBJECT(vd->tlscreds));
3221        vd->tlscreds = NULL;
3222    }
3223    if (vd->tlsauthz) {
3224        object_unparent(OBJECT(vd->tlsauthz));
3225        vd->tlsauthz = NULL;
3226    }
3227    g_free(vd->tlsauthzid);
3228    vd->tlsauthzid = NULL;
3229    if (vd->lock_key_sync) {
3230        qemu_remove_led_event_handler(vd->led);
3231        vd->led = NULL;
3232    }
3233#ifdef CONFIG_VNC_SASL
3234    if (vd->sasl.authz) {
3235        object_unparent(OBJECT(vd->sasl.authz));
3236        vd->sasl.authz = NULL;
3237    }
3238    g_free(vd->sasl.authzid);
3239    vd->sasl.authzid = NULL;
3240#endif
3241}
3242
3243int vnc_display_password(const char *id, const char *password)
3244{
3245    VncDisplay *vd = vnc_display_find(id);
3246
3247    if (!vd) {
3248        return -EINVAL;
3249    }
3250    if (vd->auth == VNC_AUTH_NONE) {
3251        error_printf_unless_qmp("If you want use passwords please enable "
3252                                "password auth using '-vnc ${dpy},password'.\n");
3253        return -EINVAL;
3254    }
3255
3256    g_free(vd->password);
3257    vd->password = g_strdup(password);
3258
3259    return 0;
3260}
3261
3262int vnc_display_pw_expire(const char *id, time_t expires)
3263{
3264    VncDisplay *vd = vnc_display_find(id);
3265
3266    if (!vd) {
3267        return -EINVAL;
3268    }
3269
3270    vd->expires = expires;
3271    return 0;
3272}
3273
3274static void vnc_display_print_local_addr(VncDisplay *vd)
3275{
3276    SocketAddress *addr;
3277    Error *err = NULL;
3278
3279    if (!vd->listener || !vd->listener->nsioc) {
3280        return;
3281    }
3282
3283    addr = qio_channel_socket_get_local_address(vd->listener->sioc[0], &err);
3284    if (!addr) {
3285        return;
3286    }
3287
3288    if (addr->type != SOCKET_ADDRESS_TYPE_INET) {
3289        qapi_free_SocketAddress(addr);
3290        return;
3291    }
3292    error_printf_unless_qmp("VNC server running on %s:%s\n",
3293                            addr->u.inet.host,
3294                            addr->u.inet.port);
3295    qapi_free_SocketAddress(addr);
3296}
3297
3298static QemuOptsList qemu_vnc_opts = {
3299    .name = "vnc",
3300    .head = QTAILQ_HEAD_INITIALIZER(qemu_vnc_opts.head),
3301    .implied_opt_name = "vnc",
3302    .desc = {
3303        {
3304            .name = "vnc",
3305            .type = QEMU_OPT_STRING,
3306        },{
3307            .name = "websocket",
3308            .type = QEMU_OPT_STRING,
3309        },{
3310            .name = "tls-creds",
3311            .type = QEMU_OPT_STRING,
3312        },{
3313            .name = "share",
3314            .type = QEMU_OPT_STRING,
3315        },{
3316            .name = "display",
3317            .type = QEMU_OPT_STRING,
3318        },{
3319            .name = "head",
3320            .type = QEMU_OPT_NUMBER,
3321        },{
3322            .name = "connections",
3323            .type = QEMU_OPT_NUMBER,
3324        },{
3325            .name = "to",
3326            .type = QEMU_OPT_NUMBER,
3327        },{
3328            .name = "ipv4",
3329            .type = QEMU_OPT_BOOL,
3330        },{
3331            .name = "ipv6",
3332            .type = QEMU_OPT_BOOL,
3333        },{
3334            .name = "password",
3335            .type = QEMU_OPT_BOOL,
3336        },{
3337            .name = "reverse",
3338            .type = QEMU_OPT_BOOL,
3339        },{
3340            .name = "lock-key-sync",
3341            .type = QEMU_OPT_BOOL,
3342        },{
3343            .name = "key-delay-ms",
3344            .type = QEMU_OPT_NUMBER,
3345        },{
3346            .name = "sasl",
3347            .type = QEMU_OPT_BOOL,
3348        },{
3349            .name = "acl",
3350            .type = QEMU_OPT_BOOL,
3351        },{
3352            .name = "tls-authz",
3353            .type = QEMU_OPT_STRING,
3354        },{
3355            .name = "sasl-authz",
3356            .type = QEMU_OPT_STRING,
3357        },{
3358            .name = "lossy",
3359            .type = QEMU_OPT_BOOL,
3360        },{
3361            .name = "non-adaptive",
3362            .type = QEMU_OPT_BOOL,
3363        },{
3364            .name = "audiodev",
3365            .type = QEMU_OPT_STRING,
3366        },
3367        { /* end of list */ }
3368    },
3369};
3370
3371
3372static int
3373vnc_display_setup_auth(int *auth,
3374                       int *subauth,
3375                       QCryptoTLSCreds *tlscreds,
3376                       bool password,
3377                       bool sasl,
3378                       bool websocket,
3379                       Error **errp)
3380{
3381    /*
3382     * We have a choice of 3 authentication options
3383     *
3384     *   1. none
3385     *   2. vnc
3386     *   3. sasl
3387     *
3388     * The channel can be run in 2 modes
3389     *
3390     *   1. clear
3391     *   2. tls
3392     *
3393     * And TLS can use 2 types of credentials
3394     *
3395     *   1. anon
3396     *   2. x509
3397     *
3398     * We thus have 9 possible logical combinations
3399     *
3400     *   1. clear + none
3401     *   2. clear + vnc
3402     *   3. clear + sasl
3403     *   4. tls + anon + none
3404     *   5. tls + anon + vnc
3405     *   6. tls + anon + sasl
3406     *   7. tls + x509 + none
3407     *   8. tls + x509 + vnc
3408     *   9. tls + x509 + sasl
3409     *
3410     * These need to be mapped into the VNC auth schemes
3411     * in an appropriate manner. In regular VNC, all the
3412     * TLS options get mapped into VNC_AUTH_VENCRYPT
3413     * sub-auth types.
3414     *
3415     * In websockets, the https:// protocol already provides
3416     * TLS support, so there is no need to make use of the
3417     * VeNCrypt extension. Furthermore, websockets browser
3418     * clients could not use VeNCrypt even if they wanted to,
3419     * as they cannot control when the TLS handshake takes
3420     * place. Thus there is no option but to rely on https://,
3421     * meaning combinations 4->6 and 7->9 will be mapped to
3422     * VNC auth schemes in the same way as combos 1->3.
3423     *
3424     * Regardless of fact that we have a different mapping to
3425     * VNC auth mechs for plain VNC vs websockets VNC, the end
3426     * result has the same security characteristics.
3427     */
3428    if (websocket || !tlscreds) {
3429        if (password) {
3430            VNC_DEBUG("Initializing VNC server with password auth\n");
3431            *auth = VNC_AUTH_VNC;
3432        } else if (sasl) {
3433            VNC_DEBUG("Initializing VNC server with SASL auth\n");
3434            *auth = VNC_AUTH_SASL;
3435        } else {
3436            VNC_DEBUG("Initializing VNC server with no auth\n");
3437            *auth = VNC_AUTH_NONE;
3438        }
3439        *subauth = VNC_AUTH_INVALID;
3440    } else {
3441        bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),
3442                                           TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;
3443        bool is_anon = object_dynamic_cast(OBJECT(tlscreds),
3444                                           TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;
3445
3446        if (!is_x509 && !is_anon) {
3447            error_setg(errp,
3448                       "Unsupported TLS cred type %s",
3449                       object_get_typename(OBJECT(tlscreds)));
3450            return -1;
3451        }
3452        *auth = VNC_AUTH_VENCRYPT;
3453        if (password) {
3454            if (is_x509) {
3455                VNC_DEBUG("Initializing VNC server with x509 password auth\n");
3456                *subauth = VNC_AUTH_VENCRYPT_X509VNC;
3457            } else {
3458                VNC_DEBUG("Initializing VNC server with TLS password auth\n");
3459                *subauth = VNC_AUTH_VENCRYPT_TLSVNC;
3460            }
3461
3462        } else if (sasl) {
3463            if (is_x509) {
3464                VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3465                *subauth = VNC_AUTH_VENCRYPT_X509SASL;
3466            } else {
3467                VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3468                *subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3469            }
3470        } else {
3471            if (is_x509) {
3472                VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3473                *subauth = VNC_AUTH_VENCRYPT_X509NONE;
3474            } else {
3475                VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3476                *subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3477            }
3478        }
3479    }
3480    return 0;
3481}
3482
3483
3484static int vnc_display_get_address(const char *addrstr,
3485                                   bool websocket,
3486                                   bool reverse,
3487                                   int displaynum,
3488                                   int to,
3489                                   bool has_ipv4,
3490                                   bool has_ipv6,
3491                                   bool ipv4,
3492                                   bool ipv6,
3493                                   SocketAddress **retaddr,
3494                                   Error **errp)
3495{
3496    int ret = -1;
3497    SocketAddress *addr = NULL;
3498
3499    addr = g_new0(SocketAddress, 1);
3500
3501    if (strncmp(addrstr, "unix:", 5) == 0) {
3502        addr->type = SOCKET_ADDRESS_TYPE_UNIX;
3503        addr->u.q_unix.path = g_strdup(addrstr + 5);
3504
3505        if (websocket) {
3506            error_setg(errp, "UNIX sockets not supported with websock");
3507            goto cleanup;
3508        }
3509
3510        if (to) {
3511            error_setg(errp, "Port range not support with UNIX socket");
3512            goto cleanup;
3513        }
3514        ret = 0;
3515    } else {
3516        const char *port;
3517        size_t hostlen;
3518        unsigned long long baseport = 0;
3519        InetSocketAddress *inet;
3520
3521        port = strrchr(addrstr, ':');
3522        if (!port) {
3523            if (websocket) {
3524                hostlen = 0;
3525                port = addrstr;
3526            } else {
3527                error_setg(errp, "no vnc port specified");
3528                goto cleanup;
3529            }
3530        } else {
3531            hostlen = port - addrstr;
3532            port++;
3533            if (*port == '\0') {
3534                error_setg(errp, "vnc port cannot be empty");
3535                goto cleanup;
3536            }
3537        }
3538
3539        addr->type = SOCKET_ADDRESS_TYPE_INET;
3540        inet = &addr->u.inet;
3541        if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') {
3542            inet->host = g_strndup(addrstr + 1, hostlen - 2);
3543        } else {
3544            inet->host = g_strndup(addrstr, hostlen);
3545        }
3546        /* plain VNC port is just an offset, for websocket
3547         * port is absolute */
3548        if (websocket) {
3549            if (g_str_equal(addrstr, "") ||
3550                g_str_equal(addrstr, "on")) {
3551                if (displaynum == -1) {
3552                    error_setg(errp, "explicit websocket port is required");
3553                    goto cleanup;
3554                }
3555                inet->port = g_strdup_printf(
3556                    "%d", displaynum + 5700);
3557                if (to) {
3558                    inet->has_to = true;
3559                    inet->to = to + 5700;
3560                }
3561            } else {
3562                inet->port = g_strdup(port);
3563            }
3564        } else {
3565            int offset = reverse ? 0 : 5900;
3566            if (parse_uint_full(port, &baseport, 10) < 0) {
3567                error_setg(errp, "can't convert to a number: %s", port);
3568                goto cleanup;
3569            }
3570            if (baseport > 65535 ||
3571                baseport + offset > 65535) {
3572                error_setg(errp, "port %s out of range", port);
3573                goto cleanup;
3574            }
3575            inet->port = g_strdup_printf(
3576                "%d", (int)baseport + offset);
3577
3578            if (to) {
3579                inet->has_to = true;
3580                inet->to = to + offset;
3581            }
3582        }
3583
3584        inet->ipv4 = ipv4;
3585        inet->has_ipv4 = has_ipv4;
3586        inet->ipv6 = ipv6;
3587        inet->has_ipv6 = has_ipv6;
3588
3589        ret = baseport;
3590    }
3591
3592    *retaddr = addr;
3593
3594 cleanup:
3595    if (ret < 0) {
3596        qapi_free_SocketAddress(addr);
3597    }
3598    return ret;
3599}
3600
3601static void vnc_free_addresses(SocketAddress ***retsaddr,
3602                               size_t *retnsaddr)
3603{
3604    size_t i;
3605
3606    for (i = 0; i < *retnsaddr; i++) {
3607        qapi_free_SocketAddress((*retsaddr)[i]);
3608    }
3609    g_free(*retsaddr);
3610
3611    *retsaddr = NULL;
3612    *retnsaddr = 0;
3613}
3614
3615static int vnc_display_get_addresses(QemuOpts *opts,
3616                                     bool reverse,
3617                                     SocketAddress ***retsaddr,
3618                                     size_t *retnsaddr,
3619                                     SocketAddress ***retwsaddr,
3620                                     size_t *retnwsaddr,
3621                                     Error **errp)
3622{
3623    SocketAddress *saddr = NULL;
3624    SocketAddress *wsaddr = NULL;
3625    QemuOptsIter addriter;
3626    const char *addr;
3627    int to = qemu_opt_get_number(opts, "to", 0);
3628    bool has_ipv4 = qemu_opt_get(opts, "ipv4");
3629    bool has_ipv6 = qemu_opt_get(opts, "ipv6");
3630    bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);
3631    bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);
3632    int displaynum = -1;
3633    int ret = -1;
3634
3635    *retsaddr = NULL;
3636    *retnsaddr = 0;
3637    *retwsaddr = NULL;
3638    *retnwsaddr = 0;
3639
3640    addr = qemu_opt_get(opts, "vnc");
3641    if (addr == NULL || g_str_equal(addr, "none")) {
3642        ret = 0;
3643        goto cleanup;
3644    }
3645    if (qemu_opt_get(opts, "websocket") &&
3646        !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
3647        error_setg(errp,
3648                   "SHA1 hash support is required for websockets");
3649        goto cleanup;
3650    }
3651
3652    qemu_opt_iter_init(&addriter, opts, "vnc");
3653    while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3654        int rv;
3655        rv = vnc_display_get_address(addr, false, reverse, 0, to,
3656                                     has_ipv4, has_ipv6,
3657                                     ipv4, ipv6,
3658                                     &saddr, errp);
3659        if (rv < 0) {
3660            goto cleanup;
3661        }
3662        /* Historical compat - first listen address can be used
3663         * to set the default websocket port
3664         */
3665        if (displaynum == -1) {
3666            displaynum = rv;
3667        }
3668        *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);
3669        (*retsaddr)[(*retnsaddr)++] = saddr;
3670    }
3671
3672    /* If we had multiple primary displays, we don't do defaults
3673     * for websocket, and require explicit config instead. */
3674    if (*retnsaddr > 1) {
3675        displaynum = -1;
3676    }
3677
3678    qemu_opt_iter_init(&addriter, opts, "websocket");
3679    while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {
3680        if (vnc_display_get_address(addr, true, reverse, displaynum, to,
3681                                    has_ipv4, has_ipv6,
3682                                    ipv4, ipv6,
3683                                    &wsaddr, errp) < 0) {
3684            goto cleanup;
3685        }
3686
3687        /* Historical compat - if only a single listen address was
3688         * provided, then this is used to set the default listen
3689         * address for websocket too
3690         */
3691        if (*retnsaddr == 1 &&
3692            (*retsaddr)[0]->type == SOCKET_ADDRESS_TYPE_INET &&
3693            wsaddr->type == SOCKET_ADDRESS_TYPE_INET &&
3694            g_str_equal(wsaddr->u.inet.host, "") &&
3695            !g_str_equal((*retsaddr)[0]->u.inet.host, "")) {
3696            g_free(wsaddr->u.inet.host);
3697            wsaddr->u.inet.host = g_strdup((*retsaddr)[0]->u.inet.host);
3698        }
3699
3700        *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);
3701        (*retwsaddr)[(*retnwsaddr)++] = wsaddr;
3702    }
3703
3704    ret = 0;
3705 cleanup:
3706    if (ret < 0) {
3707        vnc_free_addresses(retsaddr, retnsaddr);
3708        vnc_free_addresses(retwsaddr, retnwsaddr);
3709    }
3710    return ret;
3711}
3712
3713static int vnc_display_connect(VncDisplay *vd,
3714                               SocketAddress **saddr,
3715                               size_t nsaddr,
3716                               SocketAddress **wsaddr,
3717                               size_t nwsaddr,
3718                               Error **errp)
3719{
3720    /* connect to viewer */
3721    QIOChannelSocket *sioc = NULL;
3722    if (nwsaddr != 0) {
3723        error_setg(errp, "Cannot use websockets in reverse mode");
3724        return -1;
3725    }
3726    if (nsaddr != 1) {
3727        error_setg(errp, "Expected a single address in reverse mode");
3728        return -1;
3729    }
3730    /* TODO SOCKET_ADDRESS_TYPE_FD when fd has AF_UNIX */
3731    vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_TYPE_UNIX;
3732    sioc = qio_channel_socket_new();
3733    qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");
3734    if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {
3735        return -1;
3736    }
3737    vnc_connect(vd, sioc, false, false);
3738    object_unref(OBJECT(sioc));
3739    return 0;
3740}
3741
3742
3743static int vnc_display_listen(VncDisplay *vd,
3744                              SocketAddress **saddr,
3745                              size_t nsaddr,
3746                              SocketAddress **wsaddr,
3747                              size_t nwsaddr,
3748                              Error **errp)
3749{
3750    size_t i;
3751
3752    if (nsaddr) {
3753        vd->listener = qio_net_listener_new();
3754        qio_net_listener_set_name(vd->listener, "vnc-listen");
3755        for (i = 0; i < nsaddr; i++) {
3756            if (qio_net_listener_open_sync(vd->listener,
3757                                           saddr[i], 1,
3758                                           errp) < 0)  {
3759                return -1;
3760            }
3761        }
3762
3763        qio_net_listener_set_client_func(vd->listener,
3764                                         vnc_listen_io, vd, NULL);
3765    }
3766
3767    if (nwsaddr) {
3768        vd->wslistener = qio_net_listener_new();
3769        qio_net_listener_set_name(vd->wslistener, "vnc-ws-listen");
3770        for (i = 0; i < nwsaddr; i++) {
3771            if (qio_net_listener_open_sync(vd->wslistener,
3772                                           wsaddr[i], 1,
3773                                           errp) < 0)  {
3774                return -1;
3775            }
3776        }
3777
3778        qio_net_listener_set_client_func(vd->wslistener,
3779                                         vnc_listen_io, vd, NULL);
3780    }
3781
3782    return 0;
3783}
3784
3785
3786void vnc_display_open(const char *id, Error **errp)
3787{
3788    VncDisplay *vd = vnc_display_find(id);
3789    QemuOpts *opts = qemu_opts_find(&qemu_vnc_opts, id);
3790    SocketAddress **saddr = NULL, **wsaddr = NULL;
3791    size_t nsaddr, nwsaddr;
3792    const char *share, *device_id;
3793    QemuConsole *con;
3794    bool password = false;
3795    bool reverse = false;
3796    const char *credid;
3797    bool sasl = false;
3798    int acl = 0;
3799    const char *tlsauthz;
3800    const char *saslauthz;
3801    int lock_key_sync = 1;
3802    int key_delay_ms;
3803    const char *audiodev;
3804
3805    if (!vd) {
3806        error_setg(errp, "VNC display not active");
3807        return;
3808    }
3809    vnc_display_close(vd);
3810
3811    if (!opts) {
3812        return;
3813    }
3814
3815    reverse = qemu_opt_get_bool(opts, "reverse", false);
3816    if (vnc_display_get_addresses(opts, reverse, &saddr, &nsaddr,
3817                                  &wsaddr, &nwsaddr, errp) < 0) {
3818        goto fail;
3819    }
3820
3821    password = qemu_opt_get_bool(opts, "password", false);
3822    if (password) {
3823        if (fips_get_state()) {
3824            error_setg(errp,
3825                       "VNC password auth disabled due to FIPS mode, "
3826                       "consider using the VeNCrypt or SASL authentication "
3827                       "methods as an alternative");
3828            goto fail;
3829        }
3830        if (!qcrypto_cipher_supports(
3831                QCRYPTO_CIPHER_ALG_DES_RFB, QCRYPTO_CIPHER_MODE_ECB)) {
3832            error_setg(errp,
3833                       "Cipher backend does not support DES RFB algorithm");
3834            goto fail;
3835        }
3836    }
3837
3838    lock_key_sync = qemu_opt_get_bool(opts, "lock-key-sync", true);
3839    key_delay_ms = qemu_opt_get_number(opts, "key-delay-ms", 10);
3840    sasl = qemu_opt_get_bool(opts, "sasl", false);
3841#ifndef CONFIG_VNC_SASL
3842    if (sasl) {
3843        error_setg(errp, "VNC SASL auth requires cyrus-sasl support");
3844        goto fail;
3845    }
3846#endif /* CONFIG_VNC_SASL */
3847    credid = qemu_opt_get(opts, "tls-creds");
3848    if (credid) {
3849        Object *creds;
3850        creds = object_resolve_path_component(
3851            object_get_objects_root(), credid);
3852        if (!creds) {
3853            error_setg(errp, "No TLS credentials with id '%s'",
3854                       credid);
3855            goto fail;
3856        }
3857        vd->tlscreds = (QCryptoTLSCreds *)
3858            object_dynamic_cast(creds,
3859                                TYPE_QCRYPTO_TLS_CREDS);
3860        if (!vd->tlscreds) {
3861            error_setg(errp, "Object with id '%s' is not TLS credentials",
3862                       credid);
3863            goto fail;
3864        }
3865        object_ref(OBJECT(vd->tlscreds));
3866
3867        if (vd->tlscreds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
3868            error_setg(errp,
3869                       "Expecting TLS credentials with a server endpoint");
3870            goto fail;
3871        }
3872    }
3873    if (qemu_opt_get(opts, "acl")) {
3874        error_report("The 'acl' option to -vnc is deprecated. "
3875                     "Please use the 'tls-authz' and 'sasl-authz' "
3876                     "options instead");
3877    }
3878    acl = qemu_opt_get_bool(opts, "acl", false);
3879    tlsauthz = qemu_opt_get(opts, "tls-authz");
3880    if (acl && tlsauthz) {
3881        error_setg(errp, "'acl' option is mutually exclusive with the "
3882                   "'tls-authz' option");
3883        goto fail;
3884    }
3885    if (tlsauthz && !vd->tlscreds) {
3886        error_setg(errp, "'tls-authz' provided but TLS is not enabled");
3887        goto fail;
3888    }
3889
3890    saslauthz = qemu_opt_get(opts, "sasl-authz");
3891    if (acl && saslauthz) {
3892        error_setg(errp, "'acl' option is mutually exclusive with the "
3893                   "'sasl-authz' option");
3894        goto fail;
3895    }
3896    if (saslauthz && !sasl) {
3897        error_setg(errp, "'sasl-authz' provided but SASL auth is not enabled");
3898        goto fail;
3899    }
3900
3901    share = qemu_opt_get(opts, "share");
3902    if (share) {
3903        if (strcmp(share, "ignore") == 0) {
3904            vd->share_policy = VNC_SHARE_POLICY_IGNORE;
3905        } else if (strcmp(share, "allow-exclusive") == 0) {
3906            vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3907        } else if (strcmp(share, "force-shared") == 0) {
3908            vd->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
3909        } else {
3910            error_setg(errp, "unknown vnc share= option");
3911            goto fail;
3912        }
3913    } else {
3914        vd->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
3915    }
3916    vd->connections_limit = qemu_opt_get_number(opts, "connections", 32);
3917
3918#ifdef CONFIG_VNC_JPEG
3919    vd->lossy = qemu_opt_get_bool(opts, "lossy", false);
3920#endif
3921    vd->non_adaptive = qemu_opt_get_bool(opts, "non-adaptive", false);
3922    /* adaptive updates are only used with tight encoding and
3923     * if lossy updates are enabled so we can disable all the
3924     * calculations otherwise */
3925    if (!vd->lossy) {
3926        vd->non_adaptive = true;
3927    }
3928
3929    if (tlsauthz) {
3930        vd->tlsauthzid = g_strdup(tlsauthz);
3931    } else if (acl) {
3932        if (strcmp(vd->id, "default") == 0) {
3933            vd->tlsauthzid = g_strdup("vnc.x509dname");
3934        } else {
3935            vd->tlsauthzid = g_strdup_printf("vnc.%s.x509dname", vd->id);
3936        }
3937        vd->tlsauthz = QAUTHZ(qauthz_list_new(vd->tlsauthzid,
3938                                              QAUTHZ_LIST_POLICY_DENY,
3939                                              &error_abort));
3940    }
3941#ifdef CONFIG_VNC_SASL
3942    if (sasl) {
3943        if (saslauthz) {
3944            vd->sasl.authzid = g_strdup(saslauthz);
3945        } else if (acl) {
3946            if (strcmp(vd->id, "default") == 0) {
3947                vd->sasl.authzid = g_strdup("vnc.username");
3948            } else {
3949                vd->sasl.authzid = g_strdup_printf("vnc.%s.username", vd->id);
3950            }
3951            vd->sasl.authz = QAUTHZ(qauthz_list_new(vd->sasl.authzid,
3952                                                    QAUTHZ_LIST_POLICY_DENY,
3953                                                    &error_abort));
3954        }
3955    }
3956#endif
3957
3958    if (vnc_display_setup_auth(&vd->auth, &vd->subauth,
3959                               vd->tlscreds, password,
3960                               sasl, false, errp) < 0) {
3961        goto fail;
3962    }
3963    trace_vnc_auth_init(vd, 0, vd->auth, vd->subauth);
3964
3965    if (vnc_display_setup_auth(&vd->ws_auth, &vd->ws_subauth,
3966                               vd->tlscreds, password,
3967                               sasl, true, errp) < 0) {
3968        goto fail;
3969    }
3970    trace_vnc_auth_init(vd, 1, vd->ws_auth, vd->ws_subauth);
3971
3972#ifdef CONFIG_VNC_SASL
3973    if (sasl) {
3974        int saslErr = sasl_server_init(NULL, "qemu");
3975
3976        if (saslErr != SASL_OK) {
3977            error_setg(errp, "Failed to initialize SASL auth: %s",
3978                       sasl_errstring(saslErr, NULL, NULL));
3979            goto fail;
3980        }
3981    }
3982#endif
3983    vd->lock_key_sync = lock_key_sync;
3984    if (lock_key_sync) {
3985        vd->led = qemu_add_led_event_handler(kbd_leds, vd);
3986    }
3987    vd->ledstate = 0;
3988
3989    audiodev = qemu_opt_get(opts, "audiodev");
3990    if (audiodev) {
3991        vd->audio_state = audio_state_by_name(audiodev);
3992        if (!vd->audio_state) {
3993            error_setg(errp, "Audiodev '%s' not found", audiodev);
3994            goto fail;
3995        }
3996    }
3997
3998    device_id = qemu_opt_get(opts, "display");
3999    if (device_id) {
4000        int head = qemu_opt_get_number(opts, "head", 0);
4001        Error *err = NULL;
4002
4003        con = qemu_console_lookup_by_device_name(device_id, head, &err);
4004        if (err) {
4005            error_propagate(errp, err);
4006            goto fail;
4007        }
4008    } else {
4009        con = NULL;
4010    }
4011
4012    if (con != vd->dcl.con) {
4013        qkbd_state_free(vd->kbd);
4014        unregister_displaychangelistener(&vd->dcl);
4015        vd->dcl.con = con;
4016        register_displaychangelistener(&vd->dcl);
4017        vd->kbd = qkbd_state_init(vd->dcl.con);
4018    }
4019    qkbd_state_set_delay(vd->kbd, key_delay_ms);
4020
4021    if (saddr == NULL) {
4022        goto cleanup;
4023    }
4024
4025    if (reverse) {
4026        if (vnc_display_connect(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4027            goto fail;
4028        }
4029    } else {
4030        if (vnc_display_listen(vd, saddr, nsaddr, wsaddr, nwsaddr, errp) < 0) {
4031            goto fail;
4032        }
4033    }
4034
4035    if (qemu_opt_get(opts, "to")) {
4036        vnc_display_print_local_addr(vd);
4037    }
4038
4039 cleanup:
4040    vnc_free_addresses(&saddr, &nsaddr);
4041    vnc_free_addresses(&wsaddr, &nwsaddr);
4042    return;
4043
4044fail:
4045    vnc_display_close(vd);
4046    goto cleanup;
4047}
4048
4049void vnc_display_add_client(const char *id, int csock, bool skipauth)
4050{
4051    VncDisplay *vd = vnc_display_find(id);
4052    QIOChannelSocket *sioc;
4053
4054    if (!vd) {
4055        return;
4056    }
4057
4058    sioc = qio_channel_socket_new_fd(csock, NULL);
4059    if (sioc) {
4060        qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-server");
4061        vnc_connect(vd, sioc, skipauth, false);
4062        object_unref(OBJECT(sioc));
4063    }
4064}
4065
4066static void vnc_auto_assign_id(QemuOptsList *olist, QemuOpts *opts)
4067{
4068    int i = 2;
4069    char *id;
4070
4071    id = g_strdup("default");
4072    while (qemu_opts_find(olist, id)) {
4073        g_free(id);
4074        id = g_strdup_printf("vnc%d", i++);
4075    }
4076    qemu_opts_set_id(opts, id);
4077}
4078
4079QemuOpts *vnc_parse(const char *str, Error **errp)
4080{
4081    QemuOptsList *olist = qemu_find_opts("vnc");
4082    QemuOpts *opts = qemu_opts_parse(olist, str, true, errp);
4083    const char *id;
4084
4085    if (!opts) {
4086        return NULL;
4087    }
4088
4089    id = qemu_opts_id(opts);
4090    if (!id) {
4091        /* auto-assign id if not present */
4092        vnc_auto_assign_id(olist, opts);
4093    }
4094    return opts;
4095}
4096
4097int vnc_init_func(void *opaque, QemuOpts *opts, Error **errp)
4098{
4099    Error *local_err = NULL;
4100    char *id = (char *)qemu_opts_id(opts);
4101
4102    assert(id);
4103    vnc_display_init(id, &local_err);
4104    if (local_err) {
4105        error_propagate(errp, local_err);
4106        return -1;
4107    }
4108    vnc_display_open(id, &local_err);
4109    if (local_err != NULL) {
4110        error_propagate(errp, local_err);
4111        return -1;
4112    }
4113    return 0;
4114}
4115
4116static void vnc_register_config(void)
4117{
4118    qemu_add_opts(&qemu_vnc_opts);
4119}
4120opts_init(vnc_register_config);
4121