qemu/nbd/server.c
<<
>>
Prefs
   1/*
   2 *  Copyright (C) 2016-2018 Red Hat, Inc.
   3 *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
   4 *
   5 *  Network Block Device Server Side
   6 *
   7 *  This program is free software; you can redistribute it and/or modify
   8 *  it under the terms of the GNU General Public License as published by
   9 *  the Free Software Foundation; under version 2 of the License.
  10 *
  11 *  This program is distributed in the hope that it will be useful,
  12 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14 *  GNU General Public License for more details.
  15 *
  16 *  You should have received a copy of the GNU General Public License
  17 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
  18 */
  19
  20#include "qemu/osdep.h"
  21#include "qapi/error.h"
  22#include "trace.h"
  23#include "nbd-internal.h"
  24
  25#define NBD_META_ID_BASE_ALLOCATION 0
  26#define NBD_META_ID_DIRTY_BITMAP 1
  27
  28/* NBD_MAX_BITMAP_EXTENTS: 1 mb of extents data. An empirical
  29 * constant. If an increase is needed, note that the NBD protocol
  30 * recommends no larger than 32 mb, so that the client won't consider
  31 * the reply as a denial of service attack. */
  32#define NBD_MAX_BITMAP_EXTENTS (0x100000 / 8)
  33
  34static int system_errno_to_nbd_errno(int err)
  35{
  36    switch (err) {
  37    case 0:
  38        return NBD_SUCCESS;
  39    case EPERM:
  40    case EROFS:
  41        return NBD_EPERM;
  42    case EIO:
  43        return NBD_EIO;
  44    case ENOMEM:
  45        return NBD_ENOMEM;
  46#ifdef EDQUOT
  47    case EDQUOT:
  48#endif
  49    case EFBIG:
  50    case ENOSPC:
  51        return NBD_ENOSPC;
  52    case EOVERFLOW:
  53        return NBD_EOVERFLOW;
  54    case ESHUTDOWN:
  55        return NBD_ESHUTDOWN;
  56    case EINVAL:
  57    default:
  58        return NBD_EINVAL;
  59    }
  60}
  61
  62/* Definitions for opaque data types */
  63
  64typedef struct NBDRequestData NBDRequestData;
  65
  66struct NBDRequestData {
  67    QSIMPLEQ_ENTRY(NBDRequestData) entry;
  68    NBDClient *client;
  69    uint8_t *data;
  70    bool complete;
  71};
  72
  73struct NBDExport {
  74    int refcount;
  75    void (*close)(NBDExport *exp);
  76
  77    BlockBackend *blk;
  78    char *name;
  79    char *description;
  80    off_t dev_offset;
  81    off_t size;
  82    uint16_t nbdflags;
  83    QTAILQ_HEAD(, NBDClient) clients;
  84    QTAILQ_ENTRY(NBDExport) next;
  85
  86    AioContext *ctx;
  87
  88    BlockBackend *eject_notifier_blk;
  89    Notifier eject_notifier;
  90
  91    BdrvDirtyBitmap *export_bitmap;
  92    char *export_bitmap_context;
  93};
  94
  95static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
  96
  97/* NBDExportMetaContexts represents a list of contexts to be exported,
  98 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
  99 * NBD_OPT_LIST_META_CONTEXT. */
 100typedef struct NBDExportMetaContexts {
 101    NBDExport *exp;
 102    bool valid; /* means that negotiation of the option finished without
 103                   errors */
 104    bool base_allocation; /* export base:allocation context (block status) */
 105    bool bitmap; /* export qemu:dirty-bitmap:<export bitmap name> */
 106} NBDExportMetaContexts;
 107
 108struct NBDClient {
 109    int refcount;
 110    void (*close_fn)(NBDClient *client, bool negotiated);
 111
 112    NBDExport *exp;
 113    QCryptoTLSCreds *tlscreds;
 114    char *tlsaclname;
 115    QIOChannelSocket *sioc; /* The underlying data channel */
 116    QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
 117
 118    Coroutine *recv_coroutine;
 119
 120    CoMutex send_lock;
 121    Coroutine *send_coroutine;
 122
 123    QTAILQ_ENTRY(NBDClient) next;
 124    int nb_requests;
 125    bool closing;
 126
 127    bool structured_reply;
 128    NBDExportMetaContexts export_meta;
 129
 130    uint32_t opt; /* Current option being negotiated */
 131    uint32_t optlen; /* remaining length of data in ioc for the option being
 132                        negotiated now */
 133};
 134
 135static void nbd_client_receive_next_request(NBDClient *client);
 136
 137/* Basic flow for negotiation
 138
 139   Server         Client
 140   Negotiate
 141
 142   or
 143
 144   Server         Client
 145   Negotiate #1
 146                  Option
 147   Negotiate #2
 148
 149   ----
 150
 151   followed by
 152
 153   Server         Client
 154                  Request
 155   Response
 156                  Request
 157   Response
 158                  ...
 159   ...
 160                  Request (type == 2)
 161
 162*/
 163
 164static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
 165                                     uint32_t type, uint32_t length)
 166{
 167    stq_be_p(&rep->magic, NBD_REP_MAGIC);
 168    stl_be_p(&rep->option, option);
 169    stl_be_p(&rep->type, type);
 170    stl_be_p(&rep->length, length);
 171}
 172
 173/* Send a reply header, including length, but no payload.
 174 * Return -errno on error, 0 on success. */
 175static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
 176                                      uint32_t len, Error **errp)
 177{
 178    NBDOptionReply rep;
 179
 180    trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
 181                                     type, nbd_rep_lookup(type), len);
 182
 183    assert(len < NBD_MAX_BUFFER_SIZE);
 184
 185    set_be_option_rep(&rep, client->opt, type, len);
 186    return nbd_write(client->ioc, &rep, sizeof(rep), errp);
 187}
 188
 189/* Send a reply header with default 0 length.
 190 * Return -errno on error, 0 on success. */
 191static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
 192                                  Error **errp)
 193{
 194    return nbd_negotiate_send_rep_len(client, type, 0, errp);
 195}
 196
 197/* Send an error reply.
 198 * Return -errno on error, 0 on success. */
 199static int GCC_FMT_ATTR(4, 0)
 200nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
 201                            Error **errp, const char *fmt, va_list va)
 202{
 203    char *msg;
 204    int ret;
 205    size_t len;
 206
 207    msg = g_strdup_vprintf(fmt, va);
 208    len = strlen(msg);
 209    assert(len < 4096);
 210    trace_nbd_negotiate_send_rep_err(msg);
 211    ret = nbd_negotiate_send_rep_len(client, type, len, errp);
 212    if (ret < 0) {
 213        goto out;
 214    }
 215    if (nbd_write(client->ioc, msg, len, errp) < 0) {
 216        error_prepend(errp, "write failed (error message): ");
 217        ret = -EIO;
 218    } else {
 219        ret = 0;
 220    }
 221
 222out:
 223    g_free(msg);
 224    return ret;
 225}
 226
 227/* Send an error reply.
 228 * Return -errno on error, 0 on success. */
 229static int GCC_FMT_ATTR(4, 5)
 230nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
 231                           Error **errp, const char *fmt, ...)
 232{
 233    va_list va;
 234    int ret;
 235
 236    va_start(va, fmt);
 237    ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
 238    va_end(va);
 239    return ret;
 240}
 241
 242/* Drop remainder of the current option, and send a reply with the
 243 * given error type and message. Return -errno on read or write
 244 * failure; or 0 if connection is still live. */
 245static int GCC_FMT_ATTR(4, 0)
 246nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
 247              const char *fmt, va_list va)
 248{
 249    int ret = nbd_drop(client->ioc, client->optlen, errp);
 250
 251    client->optlen = 0;
 252    if (!ret) {
 253        ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
 254    }
 255    return ret;
 256}
 257
 258static int GCC_FMT_ATTR(4, 5)
 259nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
 260             const char *fmt, ...)
 261{
 262    int ret;
 263    va_list va;
 264
 265    va_start(va, fmt);
 266    ret = nbd_opt_vdrop(client, type, errp, fmt, va);
 267    va_end(va);
 268
 269    return ret;
 270}
 271
 272static int GCC_FMT_ATTR(3, 4)
 273nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
 274{
 275    int ret;
 276    va_list va;
 277
 278    va_start(va, fmt);
 279    ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
 280    va_end(va);
 281
 282    return ret;
 283}
 284
 285/* Read size bytes from the unparsed payload of the current option.
 286 * Return -errno on I/O error, 0 if option was completely handled by
 287 * sending a reply about inconsistent lengths, or 1 on success. */
 288static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
 289                        Error **errp)
 290{
 291    if (size > client->optlen) {
 292        return nbd_opt_invalid(client, errp,
 293                               "Inconsistent lengths in option %s",
 294                               nbd_opt_lookup(client->opt));
 295    }
 296    client->optlen -= size;
 297    return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1;
 298}
 299
 300/* Drop size bytes from the unparsed payload of the current option.
 301 * Return -errno on I/O error, 0 if option was completely handled by
 302 * sending a reply about inconsistent lengths, or 1 on success. */
 303static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
 304{
 305    if (size > client->optlen) {
 306        return nbd_opt_invalid(client, errp,
 307                               "Inconsistent lengths in option %s",
 308                               nbd_opt_lookup(client->opt));
 309    }
 310    client->optlen -= size;
 311    return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
 312}
 313
 314/* nbd_opt_read_name
 315 *
 316 * Read a string with the format:
 317 *   uint32_t len     (<= NBD_MAX_NAME_SIZE)
 318 *   len bytes string (not 0-terminated)
 319 *
 320 * @name should be enough to store NBD_MAX_NAME_SIZE+1.
 321 * If @length is non-null, it will be set to the actual string length.
 322 *
 323 * Return -errno on I/O error, 0 if option was completely handled by
 324 * sending a reply about inconsistent lengths, or 1 on success.
 325 */
 326static int nbd_opt_read_name(NBDClient *client, char *name, uint32_t *length,
 327                             Error **errp)
 328{
 329    int ret;
 330    uint32_t len;
 331
 332    ret = nbd_opt_read(client, &len, sizeof(len), errp);
 333    if (ret <= 0) {
 334        return ret;
 335    }
 336    cpu_to_be32s(&len);
 337
 338    if (len > NBD_MAX_NAME_SIZE) {
 339        return nbd_opt_invalid(client, errp,
 340                               "Invalid name length: %" PRIu32, len);
 341    }
 342
 343    ret = nbd_opt_read(client, name, len, errp);
 344    if (ret <= 0) {
 345        return ret;
 346    }
 347    name[len] = '\0';
 348
 349    if (length) {
 350        *length = len;
 351    }
 352
 353    return 1;
 354}
 355
 356/* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
 357 * Return -errno on error, 0 on success. */
 358static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
 359                                       Error **errp)
 360{
 361    size_t name_len, desc_len;
 362    uint32_t len;
 363    const char *name = exp->name ? exp->name : "";
 364    const char *desc = exp->description ? exp->description : "";
 365    QIOChannel *ioc = client->ioc;
 366    int ret;
 367
 368    trace_nbd_negotiate_send_rep_list(name, desc);
 369    name_len = strlen(name);
 370    desc_len = strlen(desc);
 371    len = name_len + desc_len + sizeof(len);
 372    ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
 373    if (ret < 0) {
 374        return ret;
 375    }
 376
 377    len = cpu_to_be32(name_len);
 378    if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
 379        error_prepend(errp, "write failed (name length): ");
 380        return -EINVAL;
 381    }
 382
 383    if (nbd_write(ioc, name, name_len, errp) < 0) {
 384        error_prepend(errp, "write failed (name buffer): ");
 385        return -EINVAL;
 386    }
 387
 388    if (nbd_write(ioc, desc, desc_len, errp) < 0) {
 389        error_prepend(errp, "write failed (description buffer): ");
 390        return -EINVAL;
 391    }
 392
 393    return 0;
 394}
 395
 396/* Process the NBD_OPT_LIST command, with a potential series of replies.
 397 * Return -errno on error, 0 on success. */
 398static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
 399{
 400    NBDExport *exp;
 401    assert(client->opt == NBD_OPT_LIST);
 402
 403    /* For each export, send a NBD_REP_SERVER reply. */
 404    QTAILQ_FOREACH(exp, &exports, next) {
 405        if (nbd_negotiate_send_rep_list(client, exp, errp)) {
 406            return -EINVAL;
 407        }
 408    }
 409    /* Finish with a NBD_REP_ACK. */
 410    return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
 411}
 412
 413static void nbd_check_meta_export(NBDClient *client)
 414{
 415    client->export_meta.valid &= client->exp == client->export_meta.exp;
 416}
 417
 418/* Send a reply to NBD_OPT_EXPORT_NAME.
 419 * Return -errno on error, 0 on success. */
 420static int nbd_negotiate_handle_export_name(NBDClient *client,
 421                                            uint16_t myflags, bool no_zeroes,
 422                                            Error **errp)
 423{
 424    char name[NBD_MAX_NAME_SIZE + 1];
 425    char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
 426    size_t len;
 427    int ret;
 428
 429    /* Client sends:
 430        [20 ..  xx]   export name (length bytes)
 431       Server replies:
 432        [ 0 ..   7]   size
 433        [ 8 ..   9]   export flags
 434        [10 .. 133]   reserved     (0) [unless no_zeroes]
 435     */
 436    trace_nbd_negotiate_handle_export_name();
 437    if (client->optlen >= sizeof(name)) {
 438        error_setg(errp, "Bad length received");
 439        return -EINVAL;
 440    }
 441    if (nbd_read(client->ioc, name, client->optlen, errp) < 0) {
 442        error_prepend(errp, "read failed: ");
 443        return -EIO;
 444    }
 445    name[client->optlen] = '\0';
 446    client->optlen = 0;
 447
 448    trace_nbd_negotiate_handle_export_name_request(name);
 449
 450    client->exp = nbd_export_find(name);
 451    if (!client->exp) {
 452        error_setg(errp, "export not found");
 453        return -EINVAL;
 454    }
 455
 456    trace_nbd_negotiate_new_style_size_flags(client->exp->size,
 457                                             client->exp->nbdflags | myflags);
 458    stq_be_p(buf, client->exp->size);
 459    stw_be_p(buf + 8, client->exp->nbdflags | myflags);
 460    len = no_zeroes ? 10 : sizeof(buf);
 461    ret = nbd_write(client->ioc, buf, len, errp);
 462    if (ret < 0) {
 463        error_prepend(errp, "write failed: ");
 464        return ret;
 465    }
 466
 467    QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
 468    nbd_export_get(client->exp);
 469    nbd_check_meta_export(client);
 470
 471    return 0;
 472}
 473
 474/* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
 475 * The buffer does NOT include the info type prefix.
 476 * Return -errno on error, 0 if ready to send more. */
 477static int nbd_negotiate_send_info(NBDClient *client,
 478                                   uint16_t info, uint32_t length, void *buf,
 479                                   Error **errp)
 480{
 481    int rc;
 482
 483    trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
 484    rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
 485                                    sizeof(info) + length, errp);
 486    if (rc < 0) {
 487        return rc;
 488    }
 489    cpu_to_be16s(&info);
 490    if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
 491        return -EIO;
 492    }
 493    if (nbd_write(client->ioc, buf, length, errp) < 0) {
 494        return -EIO;
 495    }
 496    return 0;
 497}
 498
 499/* nbd_reject_length: Handle any unexpected payload.
 500 * @fatal requests that we quit talking to the client, even if we are able
 501 * to successfully send an error reply.
 502 * Return:
 503 * -errno  transmission error occurred or @fatal was requested, errp is set
 504 * 0       error message successfully sent to client, errp is not set
 505 */
 506static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
 507{
 508    int ret;
 509
 510    assert(client->optlen);
 511    ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
 512                          nbd_opt_lookup(client->opt));
 513    if (fatal && !ret) {
 514        error_setg(errp, "option '%s' has unexpected length",
 515                   nbd_opt_lookup(client->opt));
 516        return -EINVAL;
 517    }
 518    return ret;
 519}
 520
 521/* Handle NBD_OPT_INFO and NBD_OPT_GO.
 522 * Return -errno on error, 0 if ready for next option, and 1 to move
 523 * into transmission phase.  */
 524static int nbd_negotiate_handle_info(NBDClient *client, uint16_t myflags,
 525                                     Error **errp)
 526{
 527    int rc;
 528    char name[NBD_MAX_NAME_SIZE + 1];
 529    NBDExport *exp;
 530    uint16_t requests;
 531    uint16_t request;
 532    uint32_t namelen;
 533    bool sendname = false;
 534    bool blocksize = false;
 535    uint32_t sizes[3];
 536    char buf[sizeof(uint64_t) + sizeof(uint16_t)];
 537
 538    /* Client sends:
 539        4 bytes: L, name length (can be 0)
 540        L bytes: export name
 541        2 bytes: N, number of requests (can be 0)
 542        N * 2 bytes: N requests
 543    */
 544    rc = nbd_opt_read_name(client, name, &namelen, errp);
 545    if (rc <= 0) {
 546        return rc;
 547    }
 548    trace_nbd_negotiate_handle_export_name_request(name);
 549
 550    rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
 551    if (rc <= 0) {
 552        return rc;
 553    }
 554    be16_to_cpus(&requests);
 555    trace_nbd_negotiate_handle_info_requests(requests);
 556    while (requests--) {
 557        rc = nbd_opt_read(client, &request, sizeof(request), errp);
 558        if (rc <= 0) {
 559            return rc;
 560        }
 561        be16_to_cpus(&request);
 562        trace_nbd_negotiate_handle_info_request(request,
 563                                                nbd_info_lookup(request));
 564        /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
 565         * everything else is either a request we don't know or
 566         * something we send regardless of request */
 567        switch (request) {
 568        case NBD_INFO_NAME:
 569            sendname = true;
 570            break;
 571        case NBD_INFO_BLOCK_SIZE:
 572            blocksize = true;
 573            break;
 574        }
 575    }
 576    if (client->optlen) {
 577        return nbd_reject_length(client, false, errp);
 578    }
 579
 580    exp = nbd_export_find(name);
 581    if (!exp) {
 582        return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
 583                                          errp, "export '%s' not present",
 584                                          name);
 585    }
 586
 587    /* Don't bother sending NBD_INFO_NAME unless client requested it */
 588    if (sendname) {
 589        rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
 590                                     errp);
 591        if (rc < 0) {
 592            return rc;
 593        }
 594    }
 595
 596    /* Send NBD_INFO_DESCRIPTION only if available, regardless of
 597     * client request */
 598    if (exp->description) {
 599        size_t len = strlen(exp->description);
 600
 601        rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
 602                                     len, exp->description, errp);
 603        if (rc < 0) {
 604            return rc;
 605        }
 606    }
 607
 608    /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
 609     * according to whether the client requested it, and according to
 610     * whether this is OPT_INFO or OPT_GO. */
 611    /* minimum - 1 for back-compat, or 512 if client is new enough.
 612     * TODO: consult blk_bs(blk)->bl.request_alignment? */
 613    sizes[0] =
 614            (client->opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
 615    /* preferred - Hard-code to 4096 for now.
 616     * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
 617    sizes[1] = 4096;
 618    /* maximum - At most 32M, but smaller as appropriate. */
 619    sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
 620    trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
 621    cpu_to_be32s(&sizes[0]);
 622    cpu_to_be32s(&sizes[1]);
 623    cpu_to_be32s(&sizes[2]);
 624    rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
 625                                 sizeof(sizes), sizes, errp);
 626    if (rc < 0) {
 627        return rc;
 628    }
 629
 630    /* Send NBD_INFO_EXPORT always */
 631    trace_nbd_negotiate_new_style_size_flags(exp->size,
 632                                             exp->nbdflags | myflags);
 633    stq_be_p(buf, exp->size);
 634    stw_be_p(buf + 8, exp->nbdflags | myflags);
 635    rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
 636                                 sizeof(buf), buf, errp);
 637    if (rc < 0) {
 638        return rc;
 639    }
 640
 641    /* If the client is just asking for NBD_OPT_INFO, but forgot to
 642     * request block sizes, return an error.
 643     * TODO: consult blk_bs(blk)->request_align, and only error if it
 644     * is not 1? */
 645    if (client->opt == NBD_OPT_INFO && !blocksize) {
 646        return nbd_negotiate_send_rep_err(client,
 647                                          NBD_REP_ERR_BLOCK_SIZE_REQD,
 648                                          errp,
 649                                          "request NBD_INFO_BLOCK_SIZE to "
 650                                          "use this export");
 651    }
 652
 653    /* Final reply */
 654    rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
 655    if (rc < 0) {
 656        return rc;
 657    }
 658
 659    if (client->opt == NBD_OPT_GO) {
 660        client->exp = exp;
 661        QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
 662        nbd_export_get(client->exp);
 663        nbd_check_meta_export(client);
 664        rc = 1;
 665    }
 666    return rc;
 667}
 668
 669
 670/* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
 671 * new channel for all further (now-encrypted) communication. */
 672static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
 673                                                 Error **errp)
 674{
 675    QIOChannel *ioc;
 676    QIOChannelTLS *tioc;
 677    struct NBDTLSHandshakeData data = { 0 };
 678
 679    assert(client->opt == NBD_OPT_STARTTLS);
 680
 681    trace_nbd_negotiate_handle_starttls();
 682    ioc = client->ioc;
 683
 684    if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
 685        return NULL;
 686    }
 687
 688    tioc = qio_channel_tls_new_server(ioc,
 689                                      client->tlscreds,
 690                                      client->tlsaclname,
 691                                      errp);
 692    if (!tioc) {
 693        return NULL;
 694    }
 695
 696    qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
 697    trace_nbd_negotiate_handle_starttls_handshake();
 698    data.loop = g_main_loop_new(g_main_context_default(), FALSE);
 699    qio_channel_tls_handshake(tioc,
 700                              nbd_tls_handshake,
 701                              &data,
 702                              NULL,
 703                              NULL);
 704
 705    if (!data.complete) {
 706        g_main_loop_run(data.loop);
 707    }
 708    g_main_loop_unref(data.loop);
 709    if (data.error) {
 710        object_unref(OBJECT(tioc));
 711        error_propagate(errp, data.error);
 712        return NULL;
 713    }
 714
 715    return QIO_CHANNEL(tioc);
 716}
 717
 718/* nbd_negotiate_send_meta_context
 719 *
 720 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
 721 *
 722 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
 723 */
 724static int nbd_negotiate_send_meta_context(NBDClient *client,
 725                                           const char *context,
 726                                           uint32_t context_id,
 727                                           Error **errp)
 728{
 729    NBDOptionReplyMetaContext opt;
 730    struct iovec iov[] = {
 731        {.iov_base = &opt, .iov_len = sizeof(opt)},
 732        {.iov_base = (void *)context, .iov_len = strlen(context)}
 733    };
 734
 735    if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
 736        context_id = 0;
 737    }
 738
 739    trace_nbd_negotiate_meta_query_reply(context, context_id);
 740    set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
 741                      sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
 742    stl_be_p(&opt.context_id, context_id);
 743
 744    return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
 745}
 746
 747/* Read strlen(@pattern) bytes, and set @match to true if they match @pattern.
 748 * @match is never set to false.
 749 *
 750 * Return -errno on I/O error, 0 if option was completely handled by
 751 * sending a reply about inconsistent lengths, or 1 on success.
 752 *
 753 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
 754 * It only means that there are no errors.
 755 */
 756static int nbd_meta_pattern(NBDClient *client, const char *pattern, bool *match,
 757                            Error **errp)
 758{
 759    int ret;
 760    char *query;
 761    size_t len = strlen(pattern);
 762
 763    assert(len);
 764
 765    query = g_malloc(len);
 766    ret = nbd_opt_read(client, query, len, errp);
 767    if (ret <= 0) {
 768        g_free(query);
 769        return ret;
 770    }
 771
 772    if (strncmp(query, pattern, len) == 0) {
 773        trace_nbd_negotiate_meta_query_parse(pattern);
 774        *match = true;
 775    } else {
 776        trace_nbd_negotiate_meta_query_skip("pattern not matched");
 777    }
 778    g_free(query);
 779
 780    return 1;
 781}
 782
 783/*
 784 * Read @len bytes, and set @match to true if they match @pattern, or if @len
 785 * is 0 and the client is performing _LIST_. @match is never set to false.
 786 *
 787 * Return -errno on I/O error, 0 if option was completely handled by
 788 * sending a reply about inconsistent lengths, or 1 on success.
 789 *
 790 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
 791 * It only means that there are no errors.
 792 */
 793static int nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
 794                                     uint32_t len, bool *match, Error **errp)
 795{
 796    if (len == 0) {
 797        if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
 798            *match = true;
 799        }
 800        trace_nbd_negotiate_meta_query_parse("empty");
 801        return 1;
 802    }
 803
 804    if (len != strlen(pattern)) {
 805        trace_nbd_negotiate_meta_query_skip("different lengths");
 806        return nbd_opt_skip(client, len, errp);
 807    }
 808
 809    return nbd_meta_pattern(client, pattern, match, errp);
 810}
 811
 812/* nbd_meta_base_query
 813 *
 814 * Handle queries to 'base' namespace. For now, only the base:allocation
 815 * context is available.  'len' is the amount of text remaining to be read from
 816 * the current name, after the 'base:' portion has been stripped.
 817 *
 818 * Return -errno on I/O error, 0 if option was completely handled by
 819 * sending a reply about inconsistent lengths, or 1 on success.
 820 */
 821static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
 822                               uint32_t len, Error **errp)
 823{
 824    return nbd_meta_empty_or_pattern(client, "allocation", len,
 825                                     &meta->base_allocation, errp);
 826}
 827
 828/* nbd_meta_bitmap_query
 829 *
 830 * Handle query to 'qemu:' namespace.
 831 * @len is the amount of text remaining to be read from the current name, after
 832 * the 'qemu:' portion has been stripped.
 833 *
 834 * Return -errno on I/O error, 0 if option was completely handled by
 835 * sending a reply about inconsistent lengths, or 1 on success. */
 836static int nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
 837                               uint32_t len, Error **errp)
 838{
 839    bool dirty_bitmap = false;
 840    size_t dirty_bitmap_len = strlen("dirty-bitmap:");
 841    int ret;
 842
 843    if (!meta->exp->export_bitmap) {
 844        trace_nbd_negotiate_meta_query_skip("no dirty-bitmap exported");
 845        return nbd_opt_skip(client, len, errp);
 846    }
 847
 848    if (len == 0) {
 849        if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
 850            meta->bitmap = true;
 851        }
 852        trace_nbd_negotiate_meta_query_parse("empty");
 853        return 1;
 854    }
 855
 856    if (len < dirty_bitmap_len) {
 857        trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
 858        return nbd_opt_skip(client, len, errp);
 859    }
 860
 861    len -= dirty_bitmap_len;
 862    ret = nbd_meta_pattern(client, "dirty-bitmap:", &dirty_bitmap, errp);
 863    if (ret <= 0) {
 864        return ret;
 865    }
 866    if (!dirty_bitmap) {
 867        trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
 868        return nbd_opt_skip(client, len, errp);
 869    }
 870
 871    trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
 872
 873    return nbd_meta_empty_or_pattern(
 874            client, meta->exp->export_bitmap_context +
 875            strlen("qemu:dirty_bitmap:"), len, &meta->bitmap, errp);
 876}
 877
 878/* nbd_negotiate_meta_query
 879 *
 880 * Parse namespace name and call corresponding function to parse body of the
 881 * query.
 882 *
 883 * The only supported namespace now is 'base'.
 884 *
 885 * The function aims not wasting time and memory to read long unknown namespace
 886 * names.
 887 *
 888 * Return -errno on I/O error, 0 if option was completely handled by
 889 * sending a reply about inconsistent lengths, or 1 on success. */
 890static int nbd_negotiate_meta_query(NBDClient *client,
 891                                    NBDExportMetaContexts *meta, Error **errp)
 892{
 893    /*
 894     * Both 'qemu' and 'base' namespaces have length = 5 including a
 895     * colon. If another length namespace is later introduced, this
 896     * should certainly be refactored.
 897     */
 898    int ret;
 899    size_t ns_len = 5;
 900    char ns[5];
 901    uint32_t len;
 902
 903    ret = nbd_opt_read(client, &len, sizeof(len), errp);
 904    if (ret <= 0) {
 905        return ret;
 906    }
 907    cpu_to_be32s(&len);
 908
 909    if (len < ns_len) {
 910        trace_nbd_negotiate_meta_query_skip("length too short");
 911        return nbd_opt_skip(client, len, errp);
 912    }
 913
 914    len -= ns_len;
 915    ret = nbd_opt_read(client, ns, ns_len, errp);
 916    if (ret <= 0) {
 917        return ret;
 918    }
 919
 920    if (!strncmp(ns, "base:", ns_len)) {
 921        trace_nbd_negotiate_meta_query_parse("base:");
 922        return nbd_meta_base_query(client, meta, len, errp);
 923    } else if (!strncmp(ns, "qemu:", ns_len)) {
 924        trace_nbd_negotiate_meta_query_parse("qemu:");
 925        return nbd_meta_qemu_query(client, meta, len, errp);
 926    }
 927
 928    trace_nbd_negotiate_meta_query_skip("unknown namespace");
 929    return nbd_opt_skip(client, len, errp);
 930}
 931
 932/* nbd_negotiate_meta_queries
 933 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
 934 *
 935 * Return -errno on I/O error, or 0 if option was completely handled. */
 936static int nbd_negotiate_meta_queries(NBDClient *client,
 937                                      NBDExportMetaContexts *meta, Error **errp)
 938{
 939    int ret;
 940    char export_name[NBD_MAX_NAME_SIZE + 1];
 941    NBDExportMetaContexts local_meta;
 942    uint32_t nb_queries;
 943    int i;
 944
 945    if (!client->structured_reply) {
 946        return nbd_opt_invalid(client, errp,
 947                               "request option '%s' when structured reply "
 948                               "is not negotiated",
 949                               nbd_opt_lookup(client->opt));
 950    }
 951
 952    if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
 953        /* Only change the caller's meta on SET. */
 954        meta = &local_meta;
 955    }
 956
 957    memset(meta, 0, sizeof(*meta));
 958
 959    ret = nbd_opt_read_name(client, export_name, NULL, errp);
 960    if (ret <= 0) {
 961        return ret;
 962    }
 963
 964    meta->exp = nbd_export_find(export_name);
 965    if (meta->exp == NULL) {
 966        return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
 967                            "export '%s' not present", export_name);
 968    }
 969
 970    ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp);
 971    if (ret <= 0) {
 972        return ret;
 973    }
 974    cpu_to_be32s(&nb_queries);
 975    trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
 976                                     export_name, nb_queries);
 977
 978    if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
 979        /* enable all known contexts */
 980        meta->base_allocation = true;
 981        meta->bitmap = !!meta->exp->export_bitmap;
 982    } else {
 983        for (i = 0; i < nb_queries; ++i) {
 984            ret = nbd_negotiate_meta_query(client, meta, errp);
 985            if (ret <= 0) {
 986                return ret;
 987            }
 988        }
 989    }
 990
 991    if (meta->base_allocation) {
 992        ret = nbd_negotiate_send_meta_context(client, "base:allocation",
 993                                              NBD_META_ID_BASE_ALLOCATION,
 994                                              errp);
 995        if (ret < 0) {
 996            return ret;
 997        }
 998    }
 999
1000    if (meta->bitmap) {
1001        ret = nbd_negotiate_send_meta_context(client,
1002                                              meta->exp->export_bitmap_context,
1003                                              NBD_META_ID_DIRTY_BITMAP,
1004                                              errp);
1005        if (ret < 0) {
1006            return ret;
1007        }
1008    }
1009
1010    ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1011    if (ret == 0) {
1012        meta->valid = true;
1013    }
1014
1015    return ret;
1016}
1017
1018/* nbd_negotiate_options
1019 * Process all NBD_OPT_* client option commands, during fixed newstyle
1020 * negotiation.
1021 * Return:
1022 * -errno  on error, errp is set
1023 * 0       on successful negotiation, errp is not set
1024 * 1       if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1025 *         errp is not set
1026 */
1027static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
1028                                 Error **errp)
1029{
1030    uint32_t flags;
1031    bool fixedNewstyle = false;
1032    bool no_zeroes = false;
1033
1034    /* Client sends:
1035        [ 0 ..   3]   client flags
1036
1037       Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1038        [ 0 ..   7]   NBD_OPTS_MAGIC
1039        [ 8 ..  11]   NBD option
1040        [12 ..  15]   Data length
1041        ...           Rest of request
1042
1043        [ 0 ..   7]   NBD_OPTS_MAGIC
1044        [ 8 ..  11]   Second NBD option
1045        [12 ..  15]   Data length
1046        ...           Rest of request
1047    */
1048
1049    if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
1050        error_prepend(errp, "read failed: ");
1051        return -EIO;
1052    }
1053    be32_to_cpus(&flags);
1054    trace_nbd_negotiate_options_flags(flags);
1055    if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1056        fixedNewstyle = true;
1057        flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1058    }
1059    if (flags & NBD_FLAG_C_NO_ZEROES) {
1060        no_zeroes = true;
1061        flags &= ~NBD_FLAG_C_NO_ZEROES;
1062    }
1063    if (flags != 0) {
1064        error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1065        return -EINVAL;
1066    }
1067
1068    while (1) {
1069        int ret;
1070        uint32_t option, length;
1071        uint64_t magic;
1072
1073        if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
1074            error_prepend(errp, "read failed: ");
1075            return -EINVAL;
1076        }
1077        magic = be64_to_cpu(magic);
1078        trace_nbd_negotiate_options_check_magic(magic);
1079        if (magic != NBD_OPTS_MAGIC) {
1080            error_setg(errp, "Bad magic received");
1081            return -EINVAL;
1082        }
1083
1084        if (nbd_read(client->ioc, &option,
1085                     sizeof(option), errp) < 0) {
1086            error_prepend(errp, "read failed: ");
1087            return -EINVAL;
1088        }
1089        option = be32_to_cpu(option);
1090        client->opt = option;
1091
1092        if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
1093            error_prepend(errp, "read failed: ");
1094            return -EINVAL;
1095        }
1096        length = be32_to_cpu(length);
1097        assert(!client->optlen);
1098        client->optlen = length;
1099
1100        if (length > NBD_MAX_BUFFER_SIZE) {
1101            error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1102                       length, NBD_MAX_BUFFER_SIZE);
1103            return -EINVAL;
1104        }
1105
1106        trace_nbd_negotiate_options_check_option(option,
1107                                                 nbd_opt_lookup(option));
1108        if (client->tlscreds &&
1109            client->ioc == (QIOChannel *)client->sioc) {
1110            QIOChannel *tioc;
1111            if (!fixedNewstyle) {
1112                error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1113                return -EINVAL;
1114            }
1115            switch (option) {
1116            case NBD_OPT_STARTTLS:
1117                if (length) {
1118                    /* Unconditionally drop the connection if the client
1119                     * can't start a TLS negotiation correctly */
1120                    return nbd_reject_length(client, true, errp);
1121                }
1122                tioc = nbd_negotiate_handle_starttls(client, errp);
1123                if (!tioc) {
1124                    return -EIO;
1125                }
1126                ret = 0;
1127                object_unref(OBJECT(client->ioc));
1128                client->ioc = QIO_CHANNEL(tioc);
1129                break;
1130
1131            case NBD_OPT_EXPORT_NAME:
1132                /* No way to return an error to client, so drop connection */
1133                error_setg(errp, "Option 0x%x not permitted before TLS",
1134                           option);
1135                return -EINVAL;
1136
1137            default:
1138                ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD, errp,
1139                                   "Option 0x%" PRIx32
1140                                   "not permitted before TLS", option);
1141                /* Let the client keep trying, unless they asked to
1142                 * quit. In this mode, we've already sent an error, so
1143                 * we can't ack the abort.  */
1144                if (option == NBD_OPT_ABORT) {
1145                    return 1;
1146                }
1147                break;
1148            }
1149        } else if (fixedNewstyle) {
1150            switch (option) {
1151            case NBD_OPT_LIST:
1152                if (length) {
1153                    ret = nbd_reject_length(client, false, errp);
1154                } else {
1155                    ret = nbd_negotiate_handle_list(client, errp);
1156                }
1157                break;
1158
1159            case NBD_OPT_ABORT:
1160                /* NBD spec says we must try to reply before
1161                 * disconnecting, but that we must also tolerate
1162                 * guests that don't wait for our reply. */
1163                nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1164                return 1;
1165
1166            case NBD_OPT_EXPORT_NAME:
1167                return nbd_negotiate_handle_export_name(client,
1168                                                        myflags, no_zeroes,
1169                                                        errp);
1170
1171            case NBD_OPT_INFO:
1172            case NBD_OPT_GO:
1173                ret = nbd_negotiate_handle_info(client, myflags, errp);
1174                if (ret == 1) {
1175                    assert(option == NBD_OPT_GO);
1176                    return 0;
1177                }
1178                break;
1179
1180            case NBD_OPT_STARTTLS:
1181                if (length) {
1182                    ret = nbd_reject_length(client, false, errp);
1183                } else if (client->tlscreds) {
1184                    ret = nbd_negotiate_send_rep_err(client,
1185                                                     NBD_REP_ERR_INVALID, errp,
1186                                                     "TLS already enabled");
1187                } else {
1188                    ret = nbd_negotiate_send_rep_err(client,
1189                                                     NBD_REP_ERR_POLICY, errp,
1190                                                     "TLS not configured");
1191                }
1192                break;
1193
1194            case NBD_OPT_STRUCTURED_REPLY:
1195                if (length) {
1196                    ret = nbd_reject_length(client, false, errp);
1197                } else if (client->structured_reply) {
1198                    ret = nbd_negotiate_send_rep_err(
1199                        client, NBD_REP_ERR_INVALID, errp,
1200                        "structured reply already negotiated");
1201                } else {
1202                    ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1203                    client->structured_reply = true;
1204                    myflags |= NBD_FLAG_SEND_DF;
1205                }
1206                break;
1207
1208            case NBD_OPT_LIST_META_CONTEXT:
1209            case NBD_OPT_SET_META_CONTEXT:
1210                ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1211                                                 errp);
1212                break;
1213
1214            default:
1215                ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1216                                   "Unsupported option %" PRIu32 " (%s)",
1217                                   option, nbd_opt_lookup(option));
1218                break;
1219            }
1220        } else {
1221            /*
1222             * If broken new-style we should drop the connection
1223             * for anything except NBD_OPT_EXPORT_NAME
1224             */
1225            switch (option) {
1226            case NBD_OPT_EXPORT_NAME:
1227                return nbd_negotiate_handle_export_name(client,
1228                                                        myflags, no_zeroes,
1229                                                        errp);
1230
1231            default:
1232                error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1233                           option, nbd_opt_lookup(option));
1234                return -EINVAL;
1235            }
1236        }
1237        if (ret < 0) {
1238            return ret;
1239        }
1240    }
1241}
1242
1243/* nbd_negotiate
1244 * Return:
1245 * -errno  on error, errp is set
1246 * 0       on successful negotiation, errp is not set
1247 * 1       if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1248 *         errp is not set
1249 */
1250static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1251{
1252    char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1253    int ret;
1254    const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
1255                              NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
1256                              NBD_FLAG_SEND_WRITE_ZEROES | NBD_FLAG_SEND_CACHE);
1257    bool oldStyle;
1258
1259    /* Old style negotiation header, no room for options
1260        [ 0 ..   7]   passwd       ("NBDMAGIC")
1261        [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)
1262        [16 ..  23]   size
1263        [24 ..  27]   export flags (zero-extended)
1264        [28 .. 151]   reserved     (0)
1265
1266       New style negotiation header, client can send options
1267        [ 0 ..   7]   passwd       ("NBDMAGIC")
1268        [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)
1269        [16 ..  17]   server flags (0)
1270        ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1271     */
1272
1273    qio_channel_set_blocking(client->ioc, false, NULL);
1274
1275    trace_nbd_negotiate_begin();
1276    memcpy(buf, "NBDMAGIC", 8);
1277
1278    oldStyle = client->exp != NULL && !client->tlscreds;
1279    if (oldStyle) {
1280        trace_nbd_negotiate_old_style(client->exp->size,
1281                                      client->exp->nbdflags | myflags);
1282        stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
1283        stq_be_p(buf + 16, client->exp->size);
1284        stl_be_p(buf + 24, client->exp->nbdflags | myflags);
1285
1286        if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
1287            error_prepend(errp, "write failed: ");
1288            return -EINVAL;
1289        }
1290    } else {
1291        stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1292        stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1293
1294        if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1295            error_prepend(errp, "write failed: ");
1296            return -EINVAL;
1297        }
1298        ret = nbd_negotiate_options(client, myflags, errp);
1299        if (ret != 0) {
1300            if (ret < 0) {
1301                error_prepend(errp, "option negotiation failed: ");
1302            }
1303            return ret;
1304        }
1305    }
1306
1307    assert(!client->optlen);
1308    trace_nbd_negotiate_success();
1309
1310    return 0;
1311}
1312
1313static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1314                               Error **errp)
1315{
1316    uint8_t buf[NBD_REQUEST_SIZE];
1317    uint32_t magic;
1318    int ret;
1319
1320    ret = nbd_read(ioc, buf, sizeof(buf), errp);
1321    if (ret < 0) {
1322        return ret;
1323    }
1324
1325    /* Request
1326       [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)
1327       [ 4 ..  5]   flags   (NBD_CMD_FLAG_FUA, ...)
1328       [ 6 ..  7]   type    (NBD_CMD_READ, ...)
1329       [ 8 .. 15]   handle
1330       [16 .. 23]   from
1331       [24 .. 27]   len
1332     */
1333
1334    magic = ldl_be_p(buf);
1335    request->flags  = lduw_be_p(buf + 4);
1336    request->type   = lduw_be_p(buf + 6);
1337    request->handle = ldq_be_p(buf + 8);
1338    request->from   = ldq_be_p(buf + 16);
1339    request->len    = ldl_be_p(buf + 24);
1340
1341    trace_nbd_receive_request(magic, request->flags, request->type,
1342                              request->from, request->len);
1343
1344    if (magic != NBD_REQUEST_MAGIC) {
1345        error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1346        return -EINVAL;
1347    }
1348    return 0;
1349}
1350
1351#define MAX_NBD_REQUESTS 16
1352
1353void nbd_client_get(NBDClient *client)
1354{
1355    client->refcount++;
1356}
1357
1358void nbd_client_put(NBDClient *client)
1359{
1360    if (--client->refcount == 0) {
1361        /* The last reference should be dropped by client->close,
1362         * which is called by client_close.
1363         */
1364        assert(client->closing);
1365
1366        qio_channel_detach_aio_context(client->ioc);
1367        object_unref(OBJECT(client->sioc));
1368        object_unref(OBJECT(client->ioc));
1369        if (client->tlscreds) {
1370            object_unref(OBJECT(client->tlscreds));
1371        }
1372        g_free(client->tlsaclname);
1373        if (client->exp) {
1374            QTAILQ_REMOVE(&client->exp->clients, client, next);
1375            nbd_export_put(client->exp);
1376        }
1377        g_free(client);
1378    }
1379}
1380
1381static void client_close(NBDClient *client, bool negotiated)
1382{
1383    if (client->closing) {
1384        return;
1385    }
1386
1387    client->closing = true;
1388
1389    /* Force requests to finish.  They will drop their own references,
1390     * then we'll close the socket and free the NBDClient.
1391     */
1392    qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1393                         NULL);
1394
1395    /* Also tell the client, so that they release their reference.  */
1396    if (client->close_fn) {
1397        client->close_fn(client, negotiated);
1398    }
1399}
1400
1401static NBDRequestData *nbd_request_get(NBDClient *client)
1402{
1403    NBDRequestData *req;
1404
1405    assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1406    client->nb_requests++;
1407
1408    req = g_new0(NBDRequestData, 1);
1409    nbd_client_get(client);
1410    req->client = client;
1411    return req;
1412}
1413
1414static void nbd_request_put(NBDRequestData *req)
1415{
1416    NBDClient *client = req->client;
1417
1418    if (req->data) {
1419        qemu_vfree(req->data);
1420    }
1421    g_free(req);
1422
1423    client->nb_requests--;
1424    nbd_client_receive_next_request(client);
1425
1426    nbd_client_put(client);
1427}
1428
1429static void blk_aio_attached(AioContext *ctx, void *opaque)
1430{
1431    NBDExport *exp = opaque;
1432    NBDClient *client;
1433
1434    trace_nbd_blk_aio_attached(exp->name, ctx);
1435
1436    exp->ctx = ctx;
1437
1438    QTAILQ_FOREACH(client, &exp->clients, next) {
1439        qio_channel_attach_aio_context(client->ioc, ctx);
1440        if (client->recv_coroutine) {
1441            aio_co_schedule(ctx, client->recv_coroutine);
1442        }
1443        if (client->send_coroutine) {
1444            aio_co_schedule(ctx, client->send_coroutine);
1445        }
1446    }
1447}
1448
1449static void blk_aio_detach(void *opaque)
1450{
1451    NBDExport *exp = opaque;
1452    NBDClient *client;
1453
1454    trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1455
1456    QTAILQ_FOREACH(client, &exp->clients, next) {
1457        qio_channel_detach_aio_context(client->ioc);
1458    }
1459
1460    exp->ctx = NULL;
1461}
1462
1463static void nbd_eject_notifier(Notifier *n, void *data)
1464{
1465    NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1466    nbd_export_close(exp);
1467}
1468
1469NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
1470                          uint16_t nbdflags, void (*close)(NBDExport *),
1471                          bool writethrough, BlockBackend *on_eject_blk,
1472                          Error **errp)
1473{
1474    AioContext *ctx;
1475    BlockBackend *blk;
1476    NBDExport *exp = g_new0(NBDExport, 1);
1477    uint64_t perm;
1478    int ret;
1479
1480    /*
1481     * NBD exports are used for non-shared storage migration.  Make sure
1482     * that BDRV_O_INACTIVE is cleared and the image is ready for write
1483     * access since the export could be available before migration handover.
1484     */
1485    ctx = bdrv_get_aio_context(bs);
1486    aio_context_acquire(ctx);
1487    bdrv_invalidate_cache(bs, NULL);
1488    aio_context_release(ctx);
1489
1490    /* Don't allow resize while the NBD server is running, otherwise we don't
1491     * care what happens with the node. */
1492    perm = BLK_PERM_CONSISTENT_READ;
1493    if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1494        perm |= BLK_PERM_WRITE;
1495    }
1496    blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1497                        BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1498    ret = blk_insert_bs(blk, bs, errp);
1499    if (ret < 0) {
1500        goto fail;
1501    }
1502    blk_set_enable_write_cache(blk, !writethrough);
1503
1504    exp->refcount = 1;
1505    QTAILQ_INIT(&exp->clients);
1506    exp->blk = blk;
1507    exp->dev_offset = dev_offset;
1508    exp->nbdflags = nbdflags;
1509    exp->size = size < 0 ? blk_getlength(blk) : size;
1510    if (exp->size < 0) {
1511        error_setg_errno(errp, -exp->size,
1512                         "Failed to determine the NBD export's length");
1513        goto fail;
1514    }
1515    exp->size -= exp->size % BDRV_SECTOR_SIZE;
1516
1517    exp->close = close;
1518    exp->ctx = blk_get_aio_context(blk);
1519    blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1520
1521    if (on_eject_blk) {
1522        blk_ref(on_eject_blk);
1523        exp->eject_notifier_blk = on_eject_blk;
1524        exp->eject_notifier.notify = nbd_eject_notifier;
1525        blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1526    }
1527    return exp;
1528
1529fail:
1530    blk_unref(blk);
1531    g_free(exp);
1532    return NULL;
1533}
1534
1535NBDExport *nbd_export_find(const char *name)
1536{
1537    NBDExport *exp;
1538    QTAILQ_FOREACH(exp, &exports, next) {
1539        if (strcmp(name, exp->name) == 0) {
1540            return exp;
1541        }
1542    }
1543
1544    return NULL;
1545}
1546
1547void nbd_export_set_name(NBDExport *exp, const char *name)
1548{
1549    if (exp->name == name) {
1550        return;
1551    }
1552
1553    nbd_export_get(exp);
1554    if (exp->name != NULL) {
1555        g_free(exp->name);
1556        exp->name = NULL;
1557        QTAILQ_REMOVE(&exports, exp, next);
1558        nbd_export_put(exp);
1559    }
1560    if (name != NULL) {
1561        nbd_export_get(exp);
1562        exp->name = g_strdup(name);
1563        QTAILQ_INSERT_TAIL(&exports, exp, next);
1564    }
1565    nbd_export_put(exp);
1566}
1567
1568void nbd_export_set_description(NBDExport *exp, const char *description)
1569{
1570    g_free(exp->description);
1571    exp->description = g_strdup(description);
1572}
1573
1574void nbd_export_close(NBDExport *exp)
1575{
1576    NBDClient *client, *next;
1577
1578    nbd_export_get(exp);
1579    QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1580        client_close(client, true);
1581    }
1582    nbd_export_set_name(exp, NULL);
1583    nbd_export_set_description(exp, NULL);
1584    nbd_export_put(exp);
1585}
1586
1587void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1588{
1589    if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1590        nbd_export_close(exp);
1591        return;
1592    }
1593
1594    assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1595
1596    error_setg(errp, "export '%s' still in use", exp->name);
1597    error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1598}
1599
1600void nbd_export_get(NBDExport *exp)
1601{
1602    assert(exp->refcount > 0);
1603    exp->refcount++;
1604}
1605
1606void nbd_export_put(NBDExport *exp)
1607{
1608    assert(exp->refcount > 0);
1609    if (exp->refcount == 1) {
1610        nbd_export_close(exp);
1611    }
1612
1613    /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1614     * if someone calls nbd_export_put() on named export not through
1615     * nbd_export_set_name() when refcount is 1. So, let's assert that
1616     * it is > 0.
1617     */
1618    assert(exp->refcount > 0);
1619    if (--exp->refcount == 0) {
1620        assert(exp->name == NULL);
1621        assert(exp->description == NULL);
1622
1623        if (exp->close) {
1624            exp->close(exp);
1625        }
1626
1627        if (exp->blk) {
1628            if (exp->eject_notifier_blk) {
1629                notifier_remove(&exp->eject_notifier);
1630                blk_unref(exp->eject_notifier_blk);
1631            }
1632            blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1633                                            blk_aio_detach, exp);
1634            blk_unref(exp->blk);
1635            exp->blk = NULL;
1636        }
1637
1638        if (exp->export_bitmap) {
1639            bdrv_dirty_bitmap_set_qmp_locked(exp->export_bitmap, false);
1640            g_free(exp->export_bitmap_context);
1641        }
1642
1643        g_free(exp);
1644    }
1645}
1646
1647BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1648{
1649    return exp->blk;
1650}
1651
1652void nbd_export_close_all(void)
1653{
1654    NBDExport *exp, *next;
1655
1656    QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1657        nbd_export_close(exp);
1658    }
1659}
1660
1661static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1662                                        unsigned niov, Error **errp)
1663{
1664    int ret;
1665
1666    g_assert(qemu_in_coroutine());
1667    qemu_co_mutex_lock(&client->send_lock);
1668    client->send_coroutine = qemu_coroutine_self();
1669
1670    ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1671
1672    client->send_coroutine = NULL;
1673    qemu_co_mutex_unlock(&client->send_lock);
1674
1675    return ret;
1676}
1677
1678static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1679                                       uint64_t handle)
1680{
1681    stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1682    stl_be_p(&reply->error, error);
1683    stq_be_p(&reply->handle, handle);
1684}
1685
1686static int nbd_co_send_simple_reply(NBDClient *client,
1687                                    uint64_t handle,
1688                                    uint32_t error,
1689                                    void *data,
1690                                    size_t len,
1691                                    Error **errp)
1692{
1693    NBDSimpleReply reply;
1694    int nbd_err = system_errno_to_nbd_errno(error);
1695    struct iovec iov[] = {
1696        {.iov_base = &reply, .iov_len = sizeof(reply)},
1697        {.iov_base = data, .iov_len = len}
1698    };
1699
1700    trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1701                                   len);
1702    set_be_simple_reply(&reply, nbd_err, handle);
1703
1704    return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1705}
1706
1707static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1708                                uint16_t type, uint64_t handle, uint32_t length)
1709{
1710    stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1711    stw_be_p(&chunk->flags, flags);
1712    stw_be_p(&chunk->type, type);
1713    stq_be_p(&chunk->handle, handle);
1714    stl_be_p(&chunk->length, length);
1715}
1716
1717static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1718                                                    uint64_t handle,
1719                                                    Error **errp)
1720{
1721    NBDStructuredReplyChunk chunk;
1722    struct iovec iov[] = {
1723        {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1724    };
1725
1726    trace_nbd_co_send_structured_done(handle);
1727    set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1728
1729    return nbd_co_send_iov(client, iov, 1, errp);
1730}
1731
1732static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1733                                                    uint64_t handle,
1734                                                    uint64_t offset,
1735                                                    void *data,
1736                                                    size_t size,
1737                                                    bool final,
1738                                                    Error **errp)
1739{
1740    NBDStructuredReadData chunk;
1741    struct iovec iov[] = {
1742        {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1743        {.iov_base = data, .iov_len = size}
1744    };
1745
1746    assert(size);
1747    trace_nbd_co_send_structured_read(handle, offset, data, size);
1748    set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1749                 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1750                 sizeof(chunk) - sizeof(chunk.h) + size);
1751    stq_be_p(&chunk.offset, offset);
1752
1753    return nbd_co_send_iov(client, iov, 2, errp);
1754}
1755
1756static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1757                                                     uint64_t handle,
1758                                                     uint32_t error,
1759                                                     const char *msg,
1760                                                     Error **errp)
1761{
1762    NBDStructuredError chunk;
1763    int nbd_err = system_errno_to_nbd_errno(error);
1764    struct iovec iov[] = {
1765        {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1766        {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1767    };
1768
1769    assert(nbd_err);
1770    trace_nbd_co_send_structured_error(handle, nbd_err,
1771                                       nbd_err_lookup(nbd_err), msg ? msg : "");
1772    set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1773                 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1774    stl_be_p(&chunk.error, nbd_err);
1775    stw_be_p(&chunk.message_length, iov[1].iov_len);
1776
1777    return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1778}
1779
1780/* Do a sparse read and send the structured reply to the client.
1781 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1782 * reported to the client, at which point this function succeeds.
1783 */
1784static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1785                                                uint64_t handle,
1786                                                uint64_t offset,
1787                                                uint8_t *data,
1788                                                size_t size,
1789                                                Error **errp)
1790{
1791    int ret = 0;
1792    NBDExport *exp = client->exp;
1793    size_t progress = 0;
1794
1795    while (progress < size) {
1796        int64_t pnum;
1797        int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1798                                             offset + progress,
1799                                             size - progress, &pnum, NULL,
1800                                             NULL);
1801        bool final;
1802
1803        if (status < 0) {
1804            char *msg = g_strdup_printf("unable to check for holes: %s",
1805                                        strerror(-status));
1806
1807            ret = nbd_co_send_structured_error(client, handle, -status, msg,
1808                                               errp);
1809            g_free(msg);
1810            return ret;
1811        }
1812        assert(pnum && pnum <= size - progress);
1813        final = progress + pnum == size;
1814        if (status & BDRV_BLOCK_ZERO) {
1815            NBDStructuredReadHole chunk;
1816            struct iovec iov[] = {
1817                {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1818            };
1819
1820            trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1821                                                   pnum);
1822            set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1823                         NBD_REPLY_TYPE_OFFSET_HOLE,
1824                         handle, sizeof(chunk) - sizeof(chunk.h));
1825            stq_be_p(&chunk.offset, offset + progress);
1826            stl_be_p(&chunk.length, pnum);
1827            ret = nbd_co_send_iov(client, iov, 1, errp);
1828        } else {
1829            ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1830                            data + progress, pnum);
1831            if (ret < 0) {
1832                error_setg_errno(errp, -ret, "reading from file failed");
1833                break;
1834            }
1835            ret = nbd_co_send_structured_read(client, handle, offset + progress,
1836                                              data + progress, pnum, final,
1837                                              errp);
1838        }
1839
1840        if (ret < 0) {
1841            break;
1842        }
1843        progress += pnum;
1844    }
1845    return ret;
1846}
1847
1848static int blockstatus_to_extent_be(BlockDriverState *bs, uint64_t offset,
1849                                    uint64_t bytes, NBDExtent *extent)
1850{
1851    uint64_t remaining_bytes = bytes;
1852
1853    while (remaining_bytes) {
1854        uint32_t flags;
1855        int64_t num;
1856        int ret = bdrv_block_status_above(bs, NULL, offset, remaining_bytes,
1857                                          &num, NULL, NULL);
1858        if (ret < 0) {
1859            return ret;
1860        }
1861
1862        flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
1863                (ret & BDRV_BLOCK_ZERO      ? NBD_STATE_ZERO : 0);
1864
1865        if (remaining_bytes == bytes) {
1866            extent->flags = flags;
1867        }
1868
1869        if (flags != extent->flags) {
1870            break;
1871        }
1872
1873        offset += num;
1874        remaining_bytes -= num;
1875    }
1876
1877    cpu_to_be32s(&extent->flags);
1878    extent->length = cpu_to_be32(bytes - remaining_bytes);
1879
1880    return 0;
1881}
1882
1883/* nbd_co_send_extents
1884 *
1885 * @length is only for tracing purposes (and may be smaller or larger
1886 * than the client's original request). @last controls whether
1887 * NBD_REPLY_FLAG_DONE is sent. @extents should already be in
1888 * big-endian format.
1889 */
1890static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
1891                               NBDExtent *extents, unsigned int nb_extents,
1892                               uint64_t length, bool last,
1893                               uint32_t context_id, Error **errp)
1894{
1895    NBDStructuredMeta chunk;
1896
1897    struct iovec iov[] = {
1898        {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1899        {.iov_base = extents, .iov_len = nb_extents * sizeof(extents[0])}
1900    };
1901
1902    trace_nbd_co_send_extents(handle, nb_extents, context_id, length, last);
1903    set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
1904                 NBD_REPLY_TYPE_BLOCK_STATUS,
1905                 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1906    stl_be_p(&chunk.context_id, context_id);
1907
1908    return nbd_co_send_iov(client, iov, 2, errp);
1909}
1910
1911/* Get block status from the exported device and send it to the client */
1912static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
1913                                    BlockDriverState *bs, uint64_t offset,
1914                                    uint32_t length, bool last,
1915                                    uint32_t context_id, Error **errp)
1916{
1917    int ret;
1918    NBDExtent extent;
1919
1920    ret = blockstatus_to_extent_be(bs, offset, length, &extent);
1921    if (ret < 0) {
1922        return nbd_co_send_structured_error(
1923                client, handle, -ret, "can't get block status", errp);
1924    }
1925
1926    return nbd_co_send_extents(client, handle, &extent, 1,
1927                               be32_to_cpu(extent.length), last,
1928                               context_id, errp);
1929}
1930
1931/*
1932 * Populate @extents from a dirty bitmap. Unless @dont_fragment, the
1933 * final extent may exceed the original @length. Store in @length the
1934 * byte length encoded (which may be smaller or larger than the
1935 * original), and return the number of extents used.
1936 */
1937static unsigned int bitmap_to_extents(BdrvDirtyBitmap *bitmap, uint64_t offset,
1938                                      uint64_t *length, NBDExtent *extents,
1939                                      unsigned int nb_extents,
1940                                      bool dont_fragment)
1941{
1942    uint64_t begin = offset, end = offset;
1943    uint64_t overall_end = offset + *length;
1944    unsigned int i = 0;
1945    BdrvDirtyBitmapIter *it;
1946    bool dirty;
1947
1948    bdrv_dirty_bitmap_lock(bitmap);
1949
1950    it = bdrv_dirty_iter_new(bitmap);
1951    dirty = bdrv_get_dirty_locked(NULL, bitmap, offset);
1952
1953    assert(begin < overall_end && nb_extents);
1954    while (begin < overall_end && i < nb_extents) {
1955        bool next_dirty = !dirty;
1956
1957        if (dirty) {
1958            end = bdrv_dirty_bitmap_next_zero(bitmap, begin);
1959        } else {
1960            bdrv_set_dirty_iter(it, begin);
1961            end = bdrv_dirty_iter_next(it);
1962        }
1963        if (end == -1 || end - begin > UINT32_MAX) {
1964            /* Cap to an aligned value < 4G beyond begin. */
1965            end = MIN(bdrv_dirty_bitmap_size(bitmap),
1966                      begin + UINT32_MAX + 1 -
1967                      bdrv_dirty_bitmap_granularity(bitmap));
1968            next_dirty = dirty;
1969        }
1970        if (dont_fragment && end > overall_end) {
1971            end = overall_end;
1972        }
1973
1974        extents[i].length = cpu_to_be32(end - begin);
1975        extents[i].flags = cpu_to_be32(dirty ? NBD_STATE_DIRTY : 0);
1976        i++;
1977        begin = end;
1978        dirty = next_dirty;
1979    }
1980
1981    bdrv_dirty_iter_free(it);
1982
1983    bdrv_dirty_bitmap_unlock(bitmap);
1984
1985    assert(offset < end);
1986    *length = end - offset;
1987    return i;
1988}
1989
1990static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
1991                              BdrvDirtyBitmap *bitmap, uint64_t offset,
1992                              uint32_t length, bool dont_fragment, bool last,
1993                              uint32_t context_id, Error **errp)
1994{
1995    int ret;
1996    unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BITMAP_EXTENTS;
1997    NBDExtent *extents = g_new(NBDExtent, nb_extents);
1998    uint64_t final_length = length;
1999
2000    nb_extents = bitmap_to_extents(bitmap, offset, &final_length, extents,
2001                                   nb_extents, dont_fragment);
2002
2003    ret = nbd_co_send_extents(client, handle, extents, nb_extents,
2004                              final_length, last, context_id, errp);
2005
2006    g_free(extents);
2007
2008    return ret;
2009}
2010
2011/* nbd_co_receive_request
2012 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2013 * connection right away, and any other negative value to report an error to
2014 * the client (although the caller may still need to disconnect after reporting
2015 * the error).
2016 */
2017static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2018                                  Error **errp)
2019{
2020    NBDClient *client = req->client;
2021    int valid_flags;
2022
2023    g_assert(qemu_in_coroutine());
2024    assert(client->recv_coroutine == qemu_coroutine_self());
2025    if (nbd_receive_request(client->ioc, request, errp) < 0) {
2026        return -EIO;
2027    }
2028
2029    trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2030                                             nbd_cmd_lookup(request->type));
2031
2032    if (request->type != NBD_CMD_WRITE) {
2033        /* No payload, we are ready to read the next request.  */
2034        req->complete = true;
2035    }
2036
2037    if (request->type == NBD_CMD_DISC) {
2038        /* Special case: we're going to disconnect without a reply,
2039         * whether or not flags, from, or len are bogus */
2040        return -EIO;
2041    }
2042
2043    if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2044        request->type == NBD_CMD_CACHE)
2045    {
2046        if (request->len > NBD_MAX_BUFFER_SIZE) {
2047            error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2048                       request->len, NBD_MAX_BUFFER_SIZE);
2049            return -EINVAL;
2050        }
2051
2052        req->data = blk_try_blockalign(client->exp->blk, request->len);
2053        if (req->data == NULL) {
2054            error_setg(errp, "No memory");
2055            return -ENOMEM;
2056        }
2057    }
2058    if (request->type == NBD_CMD_WRITE) {
2059        if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
2060            error_prepend(errp, "reading from socket failed: ");
2061            return -EIO;
2062        }
2063        req->complete = true;
2064
2065        trace_nbd_co_receive_request_payload_received(request->handle,
2066                                                      request->len);
2067    }
2068
2069    /* Sanity checks. */
2070    if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2071        (request->type == NBD_CMD_WRITE ||
2072         request->type == NBD_CMD_WRITE_ZEROES ||
2073         request->type == NBD_CMD_TRIM)) {
2074        error_setg(errp, "Export is read-only");
2075        return -EROFS;
2076    }
2077    if (request->from > client->exp->size ||
2078        request->from + request->len > client->exp->size) {
2079        error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2080                   ", Size: %" PRIu64, request->from, request->len,
2081                   (uint64_t)client->exp->size);
2082        return (request->type == NBD_CMD_WRITE ||
2083                request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2084    }
2085    valid_flags = NBD_CMD_FLAG_FUA;
2086    if (request->type == NBD_CMD_READ && client->structured_reply) {
2087        valid_flags |= NBD_CMD_FLAG_DF;
2088    } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2089        valid_flags |= NBD_CMD_FLAG_NO_HOLE;
2090    } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2091        valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2092    }
2093    if (request->flags & ~valid_flags) {
2094        error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2095                   nbd_cmd_lookup(request->type), request->flags);
2096        return -EINVAL;
2097    }
2098
2099    return 0;
2100}
2101
2102/* Send simple reply without a payload, or a structured error
2103 * @error_msg is ignored if @ret >= 0
2104 * Returns 0 if connection is still live, -errno on failure to talk to client
2105 */
2106static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2107                                               uint64_t handle,
2108                                               int ret,
2109                                               const char *error_msg,
2110                                               Error **errp)
2111{
2112    if (client->structured_reply && ret < 0) {
2113        return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2114                                            errp);
2115    } else {
2116        return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2117                                        NULL, 0, errp);
2118    }
2119}
2120
2121/* Handle NBD_CMD_READ request.
2122 * Return -errno if sending fails. Other errors are reported directly to the
2123 * client as an error reply. */
2124static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2125                                        uint8_t *data, Error **errp)
2126{
2127    int ret;
2128    NBDExport *exp = client->exp;
2129
2130    assert(request->type == NBD_CMD_READ || request->type == NBD_CMD_CACHE);
2131
2132    /* XXX: NBD Protocol only documents use of FUA with WRITE */
2133    if (request->flags & NBD_CMD_FLAG_FUA) {
2134        ret = blk_co_flush(exp->blk);
2135        if (ret < 0) {
2136            return nbd_send_generic_reply(client, request->handle, ret,
2137                                          "flush failed", errp);
2138        }
2139    }
2140
2141    if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2142        request->len && request->type != NBD_CMD_CACHE)
2143    {
2144        return nbd_co_send_sparse_read(client, request->handle, request->from,
2145                                       data, request->len, errp);
2146    }
2147
2148    ret = blk_pread(exp->blk, request->from + exp->dev_offset, data,
2149                    request->len);
2150    if (ret < 0 || request->type == NBD_CMD_CACHE) {
2151        return nbd_send_generic_reply(client, request->handle, ret,
2152                                      "reading from file failed", errp);
2153    }
2154
2155    if (client->structured_reply) {
2156        if (request->len) {
2157            return nbd_co_send_structured_read(client, request->handle,
2158                                               request->from, data,
2159                                               request->len, true, errp);
2160        } else {
2161            return nbd_co_send_structured_done(client, request->handle, errp);
2162        }
2163    } else {
2164        return nbd_co_send_simple_reply(client, request->handle, 0,
2165                                        data, request->len, errp);
2166    }
2167}
2168
2169/* Handle NBD request.
2170 * Return -errno if sending fails. Other errors are reported directly to the
2171 * client as an error reply. */
2172static coroutine_fn int nbd_handle_request(NBDClient *client,
2173                                           NBDRequest *request,
2174                                           uint8_t *data, Error **errp)
2175{
2176    int ret;
2177    int flags;
2178    NBDExport *exp = client->exp;
2179    char *msg;
2180
2181    switch (request->type) {
2182    case NBD_CMD_READ:
2183    case NBD_CMD_CACHE:
2184        return nbd_do_cmd_read(client, request, data, errp);
2185
2186    case NBD_CMD_WRITE:
2187        flags = 0;
2188        if (request->flags & NBD_CMD_FLAG_FUA) {
2189            flags |= BDRV_REQ_FUA;
2190        }
2191        ret = blk_pwrite(exp->blk, request->from + exp->dev_offset,
2192                         data, request->len, flags);
2193        return nbd_send_generic_reply(client, request->handle, ret,
2194                                      "writing to file failed", errp);
2195
2196    case NBD_CMD_WRITE_ZEROES:
2197        flags = 0;
2198        if (request->flags & NBD_CMD_FLAG_FUA) {
2199            flags |= BDRV_REQ_FUA;
2200        }
2201        if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2202            flags |= BDRV_REQ_MAY_UNMAP;
2203        }
2204        ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset,
2205                                request->len, flags);
2206        return nbd_send_generic_reply(client, request->handle, ret,
2207                                      "writing to file failed", errp);
2208
2209    case NBD_CMD_DISC:
2210        /* unreachable, thanks to special case in nbd_co_receive_request() */
2211        abort();
2212
2213    case NBD_CMD_FLUSH:
2214        ret = blk_co_flush(exp->blk);
2215        return nbd_send_generic_reply(client, request->handle, ret,
2216                                      "flush failed", errp);
2217
2218    case NBD_CMD_TRIM:
2219        ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset,
2220                              request->len);
2221        if (ret == 0 && request->flags & NBD_CMD_FLAG_FUA) {
2222            ret = blk_co_flush(exp->blk);
2223        }
2224        return nbd_send_generic_reply(client, request->handle, ret,
2225                                      "discard failed", errp);
2226
2227    case NBD_CMD_BLOCK_STATUS:
2228        if (!request->len) {
2229            return nbd_send_generic_reply(client, request->handle, -EINVAL,
2230                                          "need non-zero length", errp);
2231        }
2232        if (client->export_meta.valid &&
2233            (client->export_meta.base_allocation ||
2234             client->export_meta.bitmap))
2235        {
2236            if (client->export_meta.base_allocation) {
2237                ret = nbd_co_send_block_status(client, request->handle,
2238                                               blk_bs(exp->blk), request->from,
2239                                               request->len,
2240                                               !client->export_meta.bitmap,
2241                                               NBD_META_ID_BASE_ALLOCATION,
2242                                               errp);
2243                if (ret < 0) {
2244                    return ret;
2245                }
2246            }
2247
2248            if (client->export_meta.bitmap) {
2249                ret = nbd_co_send_bitmap(client, request->handle,
2250                                         client->exp->export_bitmap,
2251                                         request->from, request->len,
2252                                         request->flags & NBD_CMD_FLAG_REQ_ONE,
2253                                         true, NBD_META_ID_DIRTY_BITMAP, errp);
2254                if (ret < 0) {
2255                    return ret;
2256                }
2257            }
2258
2259            return ret;
2260        } else {
2261            return nbd_send_generic_reply(client, request->handle, -EINVAL,
2262                                          "CMD_BLOCK_STATUS not negotiated",
2263                                          errp);
2264        }
2265
2266    default:
2267        msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2268                              request->type);
2269        ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2270                                     errp);
2271        g_free(msg);
2272        return ret;
2273    }
2274}
2275
2276/* Owns a reference to the NBDClient passed as opaque.  */
2277static coroutine_fn void nbd_trip(void *opaque)
2278{
2279    NBDClient *client = opaque;
2280    NBDRequestData *req;
2281    NBDRequest request = { 0 };    /* GCC thinks it can be used uninitialized */
2282    int ret;
2283    Error *local_err = NULL;
2284
2285    trace_nbd_trip();
2286    if (client->closing) {
2287        nbd_client_put(client);
2288        return;
2289    }
2290
2291    req = nbd_request_get(client);
2292    ret = nbd_co_receive_request(req, &request, &local_err);
2293    client->recv_coroutine = NULL;
2294
2295    if (client->closing) {
2296        /*
2297         * The client may be closed when we are blocked in
2298         * nbd_co_receive_request()
2299         */
2300        goto done;
2301    }
2302
2303    nbd_client_receive_next_request(client);
2304    if (ret == -EIO) {
2305        goto disconnect;
2306    }
2307
2308    if (ret < 0) {
2309        /* It wans't -EIO, so, according to nbd_co_receive_request()
2310         * semantics, we should return the error to the client. */
2311        Error *export_err = local_err;
2312
2313        local_err = NULL;
2314        ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2315                                     error_get_pretty(export_err), &local_err);
2316        error_free(export_err);
2317    } else {
2318        ret = nbd_handle_request(client, &request, req->data, &local_err);
2319    }
2320    if (ret < 0) {
2321        error_prepend(&local_err, "Failed to send reply: ");
2322        goto disconnect;
2323    }
2324
2325    /* We must disconnect after NBD_CMD_WRITE if we did not
2326     * read the payload.
2327     */
2328    if (!req->complete) {
2329        error_setg(&local_err, "Request handling failed in intermediate state");
2330        goto disconnect;
2331    }
2332
2333done:
2334    nbd_request_put(req);
2335    nbd_client_put(client);
2336    return;
2337
2338disconnect:
2339    if (local_err) {
2340        error_reportf_err(local_err, "Disconnect client, due to: ");
2341    }
2342    nbd_request_put(req);
2343    client_close(client, true);
2344    nbd_client_put(client);
2345}
2346
2347static void nbd_client_receive_next_request(NBDClient *client)
2348{
2349    if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2350        nbd_client_get(client);
2351        client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2352        aio_co_schedule(client->exp->ctx, client->recv_coroutine);
2353    }
2354}
2355
2356static coroutine_fn void nbd_co_client_start(void *opaque)
2357{
2358    NBDClient *client = opaque;
2359    NBDExport *exp = client->exp;
2360    Error *local_err = NULL;
2361
2362    if (exp) {
2363        nbd_export_get(exp);
2364        QTAILQ_INSERT_TAIL(&exp->clients, client, next);
2365    }
2366    qemu_co_mutex_init(&client->send_lock);
2367
2368    if (nbd_negotiate(client, &local_err)) {
2369        if (local_err) {
2370            error_report_err(local_err);
2371        }
2372        client_close(client, false);
2373        return;
2374    }
2375
2376    nbd_client_receive_next_request(client);
2377}
2378
2379/*
2380 * Create a new client listener on the given export @exp, using the
2381 * given channel @sioc.  Begin servicing it in a coroutine.  When the
2382 * connection closes, call @close_fn with an indication of whether the
2383 * client completed negotiation.
2384 */
2385void nbd_client_new(NBDExport *exp,
2386                    QIOChannelSocket *sioc,
2387                    QCryptoTLSCreds *tlscreds,
2388                    const char *tlsaclname,
2389                    void (*close_fn)(NBDClient *, bool))
2390{
2391    NBDClient *client;
2392    Coroutine *co;
2393
2394    client = g_new0(NBDClient, 1);
2395    client->refcount = 1;
2396    client->exp = exp;
2397    client->tlscreds = tlscreds;
2398    if (tlscreds) {
2399        object_ref(OBJECT(client->tlscreds));
2400    }
2401    client->tlsaclname = g_strdup(tlsaclname);
2402    client->sioc = sioc;
2403    object_ref(OBJECT(client->sioc));
2404    client->ioc = QIO_CHANNEL(sioc);
2405    object_ref(OBJECT(client->ioc));
2406    client->close_fn = close_fn;
2407
2408    co = qemu_coroutine_create(nbd_co_client_start, client);
2409    qemu_coroutine_enter(co);
2410}
2411
2412void nbd_export_bitmap(NBDExport *exp, const char *bitmap,
2413                       const char *bitmap_export_name, Error **errp)
2414{
2415    BdrvDirtyBitmap *bm = NULL;
2416    BlockDriverState *bs = blk_bs(exp->blk);
2417
2418    if (exp->export_bitmap) {
2419        error_setg(errp, "Export bitmap is already set");
2420        return;
2421    }
2422
2423    while (true) {
2424        bm = bdrv_find_dirty_bitmap(bs, bitmap);
2425        if (bm != NULL || bs->backing == NULL) {
2426            break;
2427        }
2428
2429        bs = bs->backing->bs;
2430    }
2431
2432    if (bm == NULL) {
2433        error_setg(errp, "Bitmap '%s' is not found", bitmap);
2434        return;
2435    }
2436
2437    if (bdrv_dirty_bitmap_enabled(bm)) {
2438        error_setg(errp, "Bitmap '%s' is enabled", bitmap);
2439        return;
2440    }
2441
2442    if (bdrv_dirty_bitmap_qmp_locked(bm)) {
2443        error_setg(errp, "Bitmap '%s' is locked", bitmap);
2444        return;
2445    }
2446
2447    bdrv_dirty_bitmap_set_qmp_locked(bm, true);
2448    exp->export_bitmap = bm;
2449    exp->export_bitmap_context =
2450            g_strdup_printf("qemu:dirty-bitmap:%s", bitmap_export_name);
2451}
2452