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