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