client.c 21.9 KB
Newer Older
F
Fam Zheng 已提交
1
/*
2
 *  Copyright (C) 2016 Red Hat, Inc.
F
Fam Zheng 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
 *
 *  Network Block Device Client Side
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; under version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

P
Peter Maydell 已提交
20
#include "qemu/osdep.h"
21
#include "qapi/error.h"
F
Fam Zheng 已提交
22 23 24 25
#include "nbd-internal.h"

static int nbd_errno_to_system_errno(int err)
{
26
    int ret;
F
Fam Zheng 已提交
27 28
    switch (err) {
    case NBD_SUCCESS:
29 30
        ret = 0;
        break;
F
Fam Zheng 已提交
31
    case NBD_EPERM:
32 33
        ret = EPERM;
        break;
F
Fam Zheng 已提交
34
    case NBD_EIO:
35 36
        ret = EIO;
        break;
F
Fam Zheng 已提交
37
    case NBD_ENOMEM:
38 39
        ret = ENOMEM;
        break;
F
Fam Zheng 已提交
40
    case NBD_ENOSPC:
41 42
        ret = ENOSPC;
        break;
43 44 45
    case NBD_ESHUTDOWN:
        ret = ESHUTDOWN;
        break;
F
Fam Zheng 已提交
46
    default:
47 48 49
        TRACE("Squashing unexpected error %d to EINVAL", err);
        /* fallthrough */
    case NBD_EINVAL:
50 51
        ret = EINVAL;
        break;
F
Fam Zheng 已提交
52
    }
53
    return ret;
F
Fam Zheng 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
}

/* Definitions for opaque data types */

static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);

/* That's all folks */

/* Basic flow for negotiation

   Server         Client
   Negotiate

   or

   Server         Client
   Negotiate #1
                  Option
   Negotiate #2

   ----

   followed by

   Server         Client
                  Request
   Response
                  Request
   Response
                  ...
   ...
                  Request (type == 2)

*/

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
/* Send an option request.
 *
 * The request is for option @opt, with @data containing @len bytes of
 * additional payload for the request (@len may be -1 to treat @data as
 * a C string; and @data may be NULL if @len is 0).
 * Return 0 if successful, -1 with errp set if it is impossible to
 * continue. */
static int nbd_send_option_request(QIOChannel *ioc, uint32_t opt,
                                   uint32_t len, const char *data,
                                   Error **errp)
{
    nbd_option req;
    QEMU_BUILD_BUG_ON(sizeof(req) != 16);

    if (len == -1) {
        req.length = len = strlen(data);
    }
    TRACE("Sending option request %" PRIu32", len %" PRIu32, opt, len);

    stq_be_p(&req.magic, NBD_OPTS_MAGIC);
    stl_be_p(&req.option, opt);
    stl_be_p(&req.length, len);

112
    if (nbd_write(ioc, &req, sizeof(req), errp) < 0) {
113
        error_prepend(errp, "Failed to send option request header");
114 115 116
        return -1;
    }

117
    if (len && nbd_write(ioc, (char *) data, len, errp) < 0) {
118
        error_prepend(errp, "Failed to send option request data");
119 120 121 122 123 124
        return -1;
    }

    return 0;
}

125 126 127 128 129 130 131 132 133 134 135 136 137
/* Send NBD_OPT_ABORT as a courtesy to let the server know that we are
 * not going to attempt further negotiation. */
static void nbd_send_opt_abort(QIOChannel *ioc)
{
    /* Technically, a compliant server is supposed to reply to us; but
     * older servers disconnected instead. At any rate, we're allowed
     * to disconnect without waiting for the server reply, so we don't
     * even care if the request makes it to the server, let alone
     * waiting around for whether the server replies. */
    nbd_send_option_request(ioc, NBD_OPT_ABORT, 0, NULL, NULL);
}


138 139 140 141 142 143 144 145
/* Receive the header of an option reply, which should match the given
 * opt.  Read through the length field, but NOT the length bytes of
 * payload. Return 0 if successful, -1 with errp set if it is
 * impossible to continue. */
static int nbd_receive_option_reply(QIOChannel *ioc, uint32_t opt,
                                    nbd_opt_reply *reply, Error **errp)
{
    QEMU_BUILD_BUG_ON(sizeof(*reply) != 20);
146
    if (nbd_read(ioc, reply, sizeof(*reply), errp) < 0) {
147
        error_prepend(errp, "failed to read option reply");
148
        nbd_send_opt_abort(ioc);
149 150 151 152 153 154 155 156 157
        return -1;
    }
    be64_to_cpus(&reply->magic);
    be32_to_cpus(&reply->option);
    be32_to_cpus(&reply->type);
    be32_to_cpus(&reply->length);

    TRACE("Received option reply %" PRIx32", type %" PRIx32", len %" PRIu32,
          reply->option, reply->type, reply->length);
158

159 160
    if (reply->magic != NBD_REP_MAGIC) {
        error_setg(errp, "Unexpected option reply magic");
161
        nbd_send_opt_abort(ioc);
162 163 164 165 166
        return -1;
    }
    if (reply->option != opt) {
        error_setg(errp, "Unexpected option type %x expected %x",
                   reply->option, opt);
167
        nbd_send_opt_abort(ioc);
168 169 170 171 172 173 174 175 176 177
        return -1;
    }
    return 0;
}

/* If reply represents success, return 1 without further action.
 * If reply represents an error, consume the optional payload of
 * the packet on ioc.  Then return 0 for unsupported (so the client
 * can fall back to other approaches), or -1 with errp set for other
 * errors.
A
Alex Bligh 已提交
178
 */
179
static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,
A
Alex Bligh 已提交
180
                                Error **errp)
181
{
A
Alex Bligh 已提交
182 183 184
    char *msg = NULL;
    int result = -1;

185
    if (!(reply->type & (1 << 31))) {
A
Alex Bligh 已提交
186 187 188
        return 1;
    }

189 190
    if (reply->length) {
        if (reply->length > NBD_MAX_BUFFER_SIZE) {
A
Alex Bligh 已提交
191 192 193
            error_setg(errp, "server's error message is too long");
            goto cleanup;
        }
194
        msg = g_malloc(reply->length + 1);
195
        if (nbd_read(ioc, msg, reply->length, errp) < 0) {
196
            error_prepend(errp, "failed to read option error message");
A
Alex Bligh 已提交
197 198
            goto cleanup;
        }
199
        msg[reply->length] = '\0';
200 201
    }

202
    switch (reply->type) {
203
    case NBD_REP_ERR_UNSUP:
204
        TRACE("server doesn't understand request %" PRIx32
205
              ", attempting fallback", reply->option);
A
Alex Bligh 已提交
206 207
        result = 0;
        goto cleanup;
208

209
    case NBD_REP_ERR_POLICY:
210 211
        error_setg(errp, "Denied by server for option %" PRIx32,
                   reply->option);
212 213
        break;

214
    case NBD_REP_ERR_INVALID:
215 216
        error_setg(errp, "Invalid data length for option %" PRIx32,
                   reply->option);
217 218
        break;

219 220 221 222 223
    case NBD_REP_ERR_PLATFORM:
        error_setg(errp, "Server lacks support for option %" PRIx32,
                   reply->option);
        break;

224
    case NBD_REP_ERR_TLS_REQD:
225
        error_setg(errp, "TLS negotiation required before option %" PRIx32,
226
                   reply->option);
227 228
        break;

229 230 231 232 233
    case NBD_REP_ERR_SHUTDOWN:
        error_setg(errp, "Server shutting down before option %" PRIx32,
                   reply->option);
        break;

234
    default:
235
        error_setg(errp, "Unknown error code when asking for option %" PRIx32,
236
                   reply->option);
237 238 239
        break;
    }

A
Alex Bligh 已提交
240 241 242 243 244 245
    if (msg) {
        error_append_hint(errp, "%s\n", msg);
    }

 cleanup:
    g_free(msg);
246 247 248
    if (result < 0) {
        nbd_send_opt_abort(ioc);
    }
A
Alex Bligh 已提交
249
    return result;
250 251
}

252 253 254 255 256 257 258
/* Process another portion of the NBD_OPT_LIST reply.  Set *@match if
 * the current reply matches @want or if the server does not support
 * NBD_OPT_LIST, otherwise leave @match alone.  Return 0 if iteration
 * is complete, positive if more replies are expected, or negative
 * with @errp set if an unrecoverable error occurred. */
static int nbd_receive_list(QIOChannel *ioc, const char *want, bool *match,
                            Error **errp)
259
{
260
    nbd_opt_reply reply;
261 262
    uint32_t len;
    uint32_t namelen;
263
    char name[NBD_MAX_NAME_SIZE + 1];
A
Alex Bligh 已提交
264
    int error;
265

266
    if (nbd_receive_option_reply(ioc, NBD_OPT_LIST, &reply, errp) < 0) {
267 268
        return -1;
    }
269
    error = nbd_handle_reply_err(ioc, &reply, errp);
A
Alex Bligh 已提交
270
    if (error <= 0) {
271 272 273
        /* The server did not support NBD_OPT_LIST, so set *match on
         * the assumption that any name will be accepted.  */
        *match = true;
A
Alex Bligh 已提交
274
        return error;
275
    }
276
    len = reply.length;
277

278
    if (reply.type == NBD_REP_ACK) {
279 280
        if (len != 0) {
            error_setg(errp, "length too long for option end");
281
            nbd_send_opt_abort(ioc);
282 283
            return -1;
        }
284 285 286 287 288 289 290
        return 0;
    } else if (reply.type != NBD_REP_SERVER) {
        error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",
                   reply.type, NBD_REP_SERVER);
        nbd_send_opt_abort(ioc);
        return -1;
    }
291

292 293 294 295 296
    if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {
        error_setg(errp, "incorrect option length %" PRIu32, len);
        nbd_send_opt_abort(ioc);
        return -1;
    }
297
    if (nbd_read(ioc, &namelen, sizeof(namelen), errp) < 0) {
298
        error_prepend(errp, "failed to read option name length");
299 300 301 302 303 304 305 306 307 308 309
        nbd_send_opt_abort(ioc);
        return -1;
    }
    namelen = be32_to_cpu(namelen);
    len -= sizeof(namelen);
    if (len < namelen) {
        error_setg(errp, "incorrect option name length");
        nbd_send_opt_abort(ioc);
        return -1;
    }
    if (namelen != strlen(want)) {
310
        if (nbd_drop(ioc, len, errp) < 0) {
311
            error_prepend(errp, "failed to skip export name with wrong length");
312 313
            nbd_send_opt_abort(ioc);
            return -1;
314
        }
315 316 317 318
        return 1;
    }

    assert(namelen < sizeof(name));
319
    if (nbd_read(ioc, name, namelen, errp) < 0) {
320
        error_prepend(errp, "failed to read export name");
321 322 323 324 325
        nbd_send_opt_abort(ioc);
        return -1;
    }
    name[namelen] = '\0';
    len -= namelen;
326
    if (nbd_drop(ioc, len, errp) < 0) {
327
        error_prepend(errp, "failed to read export description");
328
        nbd_send_opt_abort(ioc);
329 330
        return -1;
    }
331 332 333
    if (!strcmp(name, want)) {
        *match = true;
    }
334 335 336 337
    return 1;
}


338
/* Return -1 on failure, 0 if wantname is an available export. */
339 340 341 342 343 344
static int nbd_receive_query_exports(QIOChannel *ioc,
                                     const char *wantname,
                                     Error **errp)
{
    bool foundExport = false;

345
    TRACE("Querying export list for '%s'", wantname);
346
    if (nbd_send_option_request(ioc, NBD_OPT_LIST, 0, NULL, errp) < 0) {
347 348 349 350 351
        return -1;
    }

    TRACE("Reading available export names");
    while (1) {
352
        int ret = nbd_receive_list(ioc, wantname, &foundExport, errp);
353 354

        if (ret < 0) {
355
            /* Server gave unexpected reply */
356
            return -1;
357 358 359 360 361 362 363 364 365 366
        } else if (ret == 0) {
            /* Done iterating. */
            if (!foundExport) {
                error_setg(errp, "No export with name '%s' available",
                           wantname);
                nbd_send_opt_abort(ioc);
                return -1;
            }
            TRACE("Found desired export name '%s'", wantname);
            return 0;
367 368 369 370
        }
    }
}

371 372 373 374
static QIOChannel *nbd_receive_starttls(QIOChannel *ioc,
                                        QCryptoTLSCreds *tlscreds,
                                        const char *hostname, Error **errp)
{
375
    nbd_opt_reply reply;
376 377 378 379
    QIOChannelTLS *tioc;
    struct NBDTLSHandshakeData data = { 0 };

    TRACE("Requesting TLS from server");
380
    if (nbd_send_option_request(ioc, NBD_OPT_STARTTLS, 0, NULL, errp) < 0) {
381 382 383 384
        return NULL;
    }

    TRACE("Getting TLS reply from server");
385
    if (nbd_receive_option_reply(ioc, NBD_OPT_STARTTLS, &reply, errp) < 0) {
386 387
        return NULL;
    }
388 389

    if (reply.type != NBD_REP_ACK) {
390
        error_setg(errp, "Server rejected request to start TLS %" PRIx32,
391
                   reply.type);
392
        nbd_send_opt_abort(ioc);
393 394 395
        return NULL;
    }

396
    if (reply.length != 0) {
397
        error_setg(errp, "Start TLS response was not zero %" PRIu32,
398
                   reply.length);
399
        nbd_send_opt_abort(ioc);
400 401 402 403 404 405 406 407
        return NULL;
    }

    TRACE("TLS request approved, setting up TLS");
    tioc = qio_channel_tls_new_client(ioc, tlscreds, hostname, errp);
    if (!tioc) {
        return NULL;
    }
408
    qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-client-tls");
409
    data.loop = g_main_loop_new(g_main_context_default(), FALSE);
410
    TRACE("Starting TLS handshake");
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    qio_channel_tls_handshake(tioc,
                              nbd_tls_handshake,
                              &data,
                              NULL);

    if (!data.complete) {
        g_main_loop_run(data.loop);
    }
    g_main_loop_unref(data.loop);
    if (data.error) {
        error_propagate(errp, data.error);
        object_unref(OBJECT(tioc));
        return NULL;
    }

    return QIO_CHANNEL(tioc);
}


E
Eric Blake 已提交
430
int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint16_t *flags,
431 432
                          QCryptoTLSCreds *tlscreds, const char *hostname,
                          QIOChannel **outioc,
F
Fam Zheng 已提交
433 434 435 436 437
                          off_t *size, Error **errp)
{
    char buf[256];
    uint64_t magic, s;
    int rc;
E
Eric Blake 已提交
438
    bool zeroes = true;
F
Fam Zheng 已提交
439

440 441
    TRACE("Receiving negotiation tlscreds=%p hostname=%s.",
          tlscreds, hostname ? hostname : "<null>");
F
Fam Zheng 已提交
442 443 444

    rc = -EINVAL;

445 446 447 448 449 450 451 452
    if (outioc) {
        *outioc = NULL;
    }
    if (tlscreds && !outioc) {
        error_setg(errp, "Output I/O channel required for TLS");
        goto fail;
    }

453
    if (nbd_read(ioc, buf, 8, errp) < 0) {
454
        error_prepend(errp, "Failed to read data");
F
Fam Zheng 已提交
455 456 457 458 459 460 461 462 463
        goto fail;
    }

    buf[8] = '\0';
    if (strlen(buf) == 0) {
        error_setg(errp, "Server connection closed unexpectedly");
        goto fail;
    }

464 465
    magic = ldq_be_p(buf);
    TRACE("Magic is 0x%" PRIx64, magic);
F
Fam Zheng 已提交
466 467 468 469 470 471

    if (memcmp(buf, "NBDMAGIC", 8) != 0) {
        error_setg(errp, "Invalid magic received");
        goto fail;
    }

472
    if (nbd_read(ioc, &magic, sizeof(magic), errp) < 0) {
473
        error_prepend(errp, "Failed to read magic");
F
Fam Zheng 已提交
474 475 476 477 478
        goto fail;
    }
    magic = be64_to_cpu(magic);
    TRACE("Magic is 0x%" PRIx64, magic);

479
    if (magic == NBD_OPTS_MAGIC) {
480 481
        uint32_t clientflags = 0;
        uint16_t globalflags;
482
        bool fixedNewStyle = false;
F
Fam Zheng 已提交
483

484
        if (nbd_read(ioc, &globalflags, sizeof(globalflags), errp) < 0) {
485
            error_prepend(errp, "Failed to read server flags");
F
Fam Zheng 已提交
486 487
            goto fail;
        }
488
        globalflags = be16_to_cpu(globalflags);
489
        TRACE("Global flags are %" PRIx32, globalflags);
490
        if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {
491
            fixedNewStyle = true;
492 493 494
            TRACE("Server supports fixed new style");
            clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;
        }
E
Eric Blake 已提交
495 496 497 498 499
        if (globalflags & NBD_FLAG_NO_ZEROES) {
            zeroes = false;
            TRACE("Server supports no zeroes");
            clientflags |= NBD_FLAG_C_NO_ZEROES;
        }
500
        /* client requested flags */
501
        clientflags = cpu_to_be32(clientflags);
502
        if (nbd_write(ioc, &clientflags, sizeof(clientflags), errp) < 0) {
503
            error_prepend(errp, "Failed to send clientflags field");
F
Fam Zheng 已提交
504 505
            goto fail;
        }
506 507 508 509 510 511 512 513 514 515 516 517
        if (tlscreds) {
            if (fixedNewStyle) {
                *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);
                if (!*outioc) {
                    goto fail;
                }
                ioc = *outioc;
            } else {
                error_setg(errp, "Server does not support STARTTLS");
                goto fail;
            }
        }
518
        if (!name) {
519 520
            TRACE("Using default NBD export name \"\"");
            name = "";
521
        }
522 523 524 525 526 527 528 529 530 531 532
        if (fixedNewStyle) {
            /* Check our desired export is present in the
             * server export list. Since NBD_OPT_EXPORT_NAME
             * cannot return an error message, running this
             * query gives us good error reporting if the
             * server required TLS
             */
            if (nbd_receive_query_exports(ioc, name, errp) < 0) {
                goto fail;
            }
        }
533 534 535
        /* write the export name request */
        if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,
                                    errp) < 0) {
F
Fam Zheng 已提交
536 537
            goto fail;
        }
538

539
        /* Read the response */
540
        if (nbd_read(ioc, &s, sizeof(s), errp) < 0) {
541
            error_prepend(errp, "Failed to read export length");
F
Fam Zheng 已提交
542 543
            goto fail;
        }
544
        *size = be64_to_cpu(s);
F
Fam Zheng 已提交
545

546
        if (nbd_read(ioc, flags, sizeof(*flags), errp) < 0) {
547
            error_prepend(errp, "Failed to read export flags");
548 549
            goto fail;
        }
E
Eric Blake 已提交
550
        be16_to_cpus(flags);
551
    } else if (magic == NBD_CLIENT_MAGIC) {
E
Eric Blake 已提交
552 553
        uint32_t oldflags;

554 555 556 557
        if (name) {
            error_setg(errp, "Server does not support export names");
            goto fail;
        }
558 559 560 561
        if (tlscreds) {
            error_setg(errp, "Server does not support STARTTLS");
            goto fail;
        }
562

563
        if (nbd_read(ioc, &s, sizeof(s), errp) < 0) {
564
            error_prepend(errp, "Failed to read export length");
565 566 567 568
            goto fail;
        }
        *size = be64_to_cpu(s);
        TRACE("Size is %" PRIu64, *size);
F
Fam Zheng 已提交
569

570
        if (nbd_read(ioc, &oldflags, sizeof(oldflags), errp) < 0) {
571
            error_prepend(errp, "Failed to read export flags");
F
Fam Zheng 已提交
572 573
            goto fail;
        }
E
Eric Blake 已提交
574 575 576 577 578 579
        be32_to_cpus(&oldflags);
        if (oldflags & ~0xffff) {
            error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);
            goto fail;
        }
        *flags = oldflags;
F
Fam Zheng 已提交
580
    } else {
581 582
        error_setg(errp, "Bad magic received");
        goto fail;
F
Fam Zheng 已提交
583
    }
584

E
Eric Blake 已提交
585
    TRACE("Size is %" PRIu64 ", export flags %" PRIx16, *size, *flags);
586
    if (zeroes && nbd_drop(ioc, 124, errp) < 0) {
587
        error_prepend(errp, "Failed to read reserved block");
F
Fam Zheng 已提交
588 589 590 591 592 593 594 595 596
        goto fail;
    }
    rc = 0;

fail:
    return rc;
}

#ifdef __linux__
597 598
int nbd_init(int fd, QIOChannelSocket *sioc, uint16_t flags, off_t size,
             Error **errp)
F
Fam Zheng 已提交
599
{
600 601
    unsigned long sectors = size / BDRV_SECTOR_SIZE;
    if (size / BDRV_SECTOR_SIZE != sectors) {
602 603
        error_setg(errp, "Export size %lld too large for 32-bit kernel",
                   (long long) size);
604 605 606
        return -E2BIG;
    }

F
Fam Zheng 已提交
607 608
    TRACE("Setting NBD socket");

609
    if (ioctl(fd, NBD_SET_SOCK, (unsigned long) sioc->fd) < 0) {
F
Fam Zheng 已提交
610
        int serrno = errno;
611
        error_setg(errp, "Failed to set NBD socket");
F
Fam Zheng 已提交
612 613 614 615 616
        return -serrno;
    }

    TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE);

617
    if (ioctl(fd, NBD_SET_BLKSIZE, (unsigned long)BDRV_SECTOR_SIZE) < 0) {
F
Fam Zheng 已提交
618
        int serrno = errno;
619
        error_setg(errp, "Failed setting NBD block size");
F
Fam Zheng 已提交
620 621 622
        return -serrno;
    }

623 624 625 626 627
    TRACE("Setting size to %lu block(s)", sectors);
    if (size % BDRV_SECTOR_SIZE) {
        TRACE("Ignoring trailing %d bytes of export",
              (int) (size % BDRV_SECTOR_SIZE));
    }
F
Fam Zheng 已提交
628

629
    if (ioctl(fd, NBD_SET_SIZE_BLOCKS, sectors) < 0) {
F
Fam Zheng 已提交
630
        int serrno = errno;
631
        error_setg(errp, "Failed setting size (in blocks)");
F
Fam Zheng 已提交
632 633 634
        return -serrno;
    }

635
    if (ioctl(fd, NBD_SET_FLAGS, (unsigned long) flags) < 0) {
F
Fam Zheng 已提交
636 637 638 639 640 641
        if (errno == ENOTTY) {
            int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;
            TRACE("Setting readonly attribute");

            if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
                int serrno = errno;
642
                error_setg(errp, "Failed setting read-only attribute");
F
Fam Zheng 已提交
643 644 645 646
                return -serrno;
            }
        } else {
            int serrno = errno;
647
            error_setg(errp, "Failed setting flags");
F
Fam Zheng 已提交
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
            return -serrno;
        }
    }

    TRACE("Negotiation ended");

    return 0;
}

int nbd_client(int fd)
{
    int ret;
    int serrno;

    TRACE("Doing NBD loop");

    ret = ioctl(fd, NBD_DO_IT);
    if (ret < 0 && errno == EPIPE) {
        /* NBD_DO_IT normally returns EPIPE when someone has disconnected
         * the socket via NBD_DISCONNECT.  We do not want to return 1 in
         * that case.
         */
        ret = 0;
    }
    serrno = errno;

    TRACE("NBD loop returned %d: %s", ret, strerror(serrno));

    TRACE("Clearing NBD queue");
    ioctl(fd, NBD_CLEAR_QUE);

    TRACE("Clearing NBD socket");
    ioctl(fd, NBD_CLEAR_SOCK);

    errno = serrno;
    return ret;
}
685 686 687 688 689 690 691 692 693

int nbd_disconnect(int fd)
{
    ioctl(fd, NBD_CLEAR_QUE);
    ioctl(fd, NBD_DISCONNECT);
    ioctl(fd, NBD_CLEAR_SOCK);
    return 0;
}

F
Fam Zheng 已提交
694
#else
695 696
int nbd_init(int fd, QIOChannelSocket *ioc, uint16_t flags, off_t size,
	     Error **errp)
F
Fam Zheng 已提交
697
{
698
    error_setg(errp, "nbd_init is only supported on Linux");
F
Fam Zheng 已提交
699 700 701 702 703 704 705
    return -ENOTSUP;
}

int nbd_client(int fd)
{
    return -ENOTSUP;
}
706 707 708 709
int nbd_disconnect(int fd)
{
    return -ENOTSUP;
}
F
Fam Zheng 已提交
710 711
#endif

712
ssize_t nbd_send_request(QIOChannel *ioc, NBDRequest *request)
F
Fam Zheng 已提交
713 714 715
{
    uint8_t buf[NBD_REQUEST_SIZE];

716
    TRACE("Sending request to server: "
717
          "{ .from = %" PRIu64", .len = %" PRIu32 ", .handle = %" PRIu64
718 719 720
          ", .flags = %" PRIx16 ", .type = %" PRIu16 " }",
          request->from, request->len, request->handle,
          request->flags, request->type);
721

722
    stl_be_p(buf, NBD_REQUEST_MAGIC);
723 724
    stw_be_p(buf + 4, request->flags);
    stw_be_p(buf + 6, request->type);
725 726 727
    stq_be_p(buf + 8, request->handle);
    stq_be_p(buf + 16, request->from);
    stl_be_p(buf + 24, request->len);
F
Fam Zheng 已提交
728

729
    return nbd_write(ioc, buf, sizeof(buf), NULL);
F
Fam Zheng 已提交
730 731
}

732
ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
F
Fam Zheng 已提交
733 734 735 736 737
{
    uint8_t buf[NBD_REPLY_SIZE];
    uint32_t magic;
    ssize_t ret;

738
    ret = nbd_read_eof(ioc, buf, sizeof(buf), errp);
739
    if (ret <= 0) {
F
Fam Zheng 已提交
740 741 742 743
        return ret;
    }

    if (ret != sizeof(buf)) {
744
        error_setg(errp, "read failed");
F
Fam Zheng 已提交
745 746 747 748 749 750 751 752 753
        return -EINVAL;
    }

    /* Reply
       [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
       [ 4 ..  7]    error   (0 == no error)
       [ 7 .. 15]    handle
     */

754 755 756
    magic = ldl_be_p(buf);
    reply->error  = ldl_be_p(buf + 4);
    reply->handle = ldq_be_p(buf + 8);
F
Fam Zheng 已提交
757 758 759

    reply->error = nbd_errno_to_system_errno(reply->error);

760 761
    if (reply->error == ESHUTDOWN) {
        /* This works even on mingw which lacks a native ESHUTDOWN */
762
        error_setg(errp, "server shutting down");
763 764
        return -EINVAL;
    }
765 766
    TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32
          ", handle = %" PRIu64" }",
F
Fam Zheng 已提交
767 768 769
          magic, reply->error, reply->handle);

    if (magic != NBD_REPLY_MAGIC) {
770
        error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
F
Fam Zheng 已提交
771 772
        return -EINVAL;
    }
773
    return sizeof(buf);
F
Fam Zheng 已提交
774 775
}