2 * Copyright (C) 2016 Red Hat, Inc.
5 * Network Block Device Client Side
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.
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.
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/>.
20 #include "qemu/osdep.h"
21 #include "qapi/error.h"
22 #include "nbd-internal.h"
24 static int nbd_errno_to_system_errno(int err)
47 TRACE("Squashing unexpected error %d to EINVAL", err);
56 /* Definitions for opaque data types */
58 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
60 /* That's all folks */
62 /* Basic flow for negotiation
89 /* Send an option request.
91 * The request is for option @opt, with @data containing @len bytes of
92 * additional payload for the request (@len may be -1 to treat @data as
93 * a C string; and @data may be NULL if @len is 0).
94 * Return 0 if successful, -1 with errp set if it is impossible to
96 static int nbd_send_option_request(QIOChannel *ioc, uint32_t opt,
97 uint32_t len, const char *data,
101 QEMU_BUILD_BUG_ON(sizeof(req) != 16);
104 req.length = len = strlen(data);
106 TRACE("Sending option request %" PRIu32", len %" PRIu32, opt, len);
108 stq_be_p(&req.magic, NBD_OPTS_MAGIC);
109 stl_be_p(&req.option, opt);
110 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");
117 if (len && nbd_write(ioc, (char *) data, len, errp) < 0) {
118 error_prepend(errp, "Failed to send option request data");
125 /* Send NBD_OPT_ABORT as a courtesy to let the server know that we are
126 * not going to attempt further negotiation. */
127 static void nbd_send_opt_abort(QIOChannel *ioc)
129 /* Technically, a compliant server is supposed to reply to us; but
130 * older servers disconnected instead. At any rate, we're allowed
131 * to disconnect without waiting for the server reply, so we don't
132 * even care if the request makes it to the server, let alone
133 * waiting around for whether the server replies. */
134 nbd_send_option_request(ioc, NBD_OPT_ABORT, 0, NULL, NULL);
138 /* Receive the header of an option reply, which should match the given
139 * opt. Read through the length field, but NOT the length bytes of
140 * payload. Return 0 if successful, -1 with errp set if it is
141 * impossible to continue. */
142 static int nbd_receive_option_reply(QIOChannel *ioc, uint32_t opt,
143 nbd_opt_reply *reply, Error **errp)
145 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);
151 be64_to_cpus(&reply->magic);
152 be32_to_cpus(&reply->option);
153 be32_to_cpus(&reply->type);
154 be32_to_cpus(&reply->length);
156 TRACE("Received option reply %" PRIx32", type %" PRIx32", len %" PRIu32,
157 reply->option, reply->type, reply->length);
159 if (reply->magic != NBD_REP_MAGIC) {
160 error_setg(errp, "Unexpected option reply magic");
161 nbd_send_opt_abort(ioc);
164 if (reply->option != opt) {
165 error_setg(errp, "Unexpected option type %x expected %x",
167 nbd_send_opt_abort(ioc);
173 /* If reply represents success, return 1 without further action.
174 * If reply represents an error, consume the optional payload of
175 * the packet on ioc. Then return 0 for unsupported (so the client
176 * can fall back to other approaches), or -1 with errp set for other
179 static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,
185 if (!(reply->type & (1 << 31))) {
190 if (reply->length > NBD_MAX_BUFFER_SIZE) {
191 error_setg(errp, "server's error message is too long");
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");
199 msg[reply->length] = '\0';
202 switch (reply->type) {
203 case NBD_REP_ERR_UNSUP:
204 TRACE("server doesn't understand request %" PRIx32
205 ", attempting fallback", reply->option);
209 case NBD_REP_ERR_POLICY:
210 error_setg(errp, "Denied by server for option %" PRIx32,
214 case NBD_REP_ERR_INVALID:
215 error_setg(errp, "Invalid data length for option %" PRIx32,
219 case NBD_REP_ERR_PLATFORM:
220 error_setg(errp, "Server lacks support for option %" PRIx32,
224 case NBD_REP_ERR_TLS_REQD:
225 error_setg(errp, "TLS negotiation required before option %" PRIx32,
229 case NBD_REP_ERR_SHUTDOWN:
230 error_setg(errp, "Server shutting down before option %" PRIx32,
235 error_setg(errp, "Unknown error code when asking for option %" PRIx32,
241 error_append_hint(errp, "%s\n", msg);
247 nbd_send_opt_abort(ioc);
252 /* Process another portion of the NBD_OPT_LIST reply. Set *@match if
253 * the current reply matches @want or if the server does not support
254 * NBD_OPT_LIST, otherwise leave @match alone. Return 0 if iteration
255 * is complete, positive if more replies are expected, or negative
256 * with @errp set if an unrecoverable error occurred. */
257 static int nbd_receive_list(QIOChannel *ioc, const char *want, bool *match,
263 char name[NBD_MAX_NAME_SIZE + 1];
266 if (nbd_receive_option_reply(ioc, NBD_OPT_LIST, &reply, errp) < 0) {
269 error = nbd_handle_reply_err(ioc, &reply, errp);
271 /* The server did not support NBD_OPT_LIST, so set *match on
272 * the assumption that any name will be accepted. */
278 if (reply.type == NBD_REP_ACK) {
280 error_setg(errp, "length too long for option end");
281 nbd_send_opt_abort(ioc);
285 } else if (reply.type != NBD_REP_SERVER) {
286 error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",
287 reply.type, NBD_REP_SERVER);
288 nbd_send_opt_abort(ioc);
292 if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {
293 error_setg(errp, "incorrect option length %" PRIu32, len);
294 nbd_send_opt_abort(ioc);
297 if (nbd_read(ioc, &namelen, sizeof(namelen), errp) < 0) {
298 error_prepend(errp, "failed to read option name length");
299 nbd_send_opt_abort(ioc);
302 namelen = be32_to_cpu(namelen);
303 len -= sizeof(namelen);
305 error_setg(errp, "incorrect option name length");
306 nbd_send_opt_abort(ioc);
309 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 nbd_send_opt_abort(ioc);
318 assert(namelen < sizeof(name));
319 if (nbd_read(ioc, name, namelen, errp) < 0) {
320 error_prepend(errp, "failed to read export name");
321 nbd_send_opt_abort(ioc);
324 name[namelen] = '\0';
326 if (nbd_drop(ioc, len, errp) < 0) {
327 error_prepend(errp, "failed to read export description");
328 nbd_send_opt_abort(ioc);
331 if (!strcmp(name, want)) {
338 /* Return -1 on failure, 0 if wantname is an available export. */
339 static int nbd_receive_query_exports(QIOChannel *ioc,
340 const char *wantname,
343 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) {
350 TRACE("Reading available export names");
352 int ret = nbd_receive_list(ioc, wantname, &foundExport, errp);
355 /* Server gave unexpected reply */
357 } else if (ret == 0) {
358 /* Done iterating. */
360 error_setg(errp, "No export with name '%s' available",
362 nbd_send_opt_abort(ioc);
365 TRACE("Found desired export name '%s'", wantname);
371 static QIOChannel *nbd_receive_starttls(QIOChannel *ioc,
372 QCryptoTLSCreds *tlscreds,
373 const char *hostname, Error **errp)
377 struct NBDTLSHandshakeData data = { 0 };
379 TRACE("Requesting TLS from server");
380 if (nbd_send_option_request(ioc, NBD_OPT_STARTTLS, 0, NULL, errp) < 0) {
384 TRACE("Getting TLS reply from server");
385 if (nbd_receive_option_reply(ioc, NBD_OPT_STARTTLS, &reply, errp) < 0) {
389 if (reply.type != NBD_REP_ACK) {
390 error_setg(errp, "Server rejected request to start TLS %" PRIx32,
392 nbd_send_opt_abort(ioc);
396 if (reply.length != 0) {
397 error_setg(errp, "Start TLS response was not zero %" PRIu32,
399 nbd_send_opt_abort(ioc);
403 TRACE("TLS request approved, setting up TLS");
404 tioc = qio_channel_tls_new_client(ioc, tlscreds, hostname, errp);
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 qio_channel_tls_handshake(tioc,
416 if (!data.complete) {
417 g_main_loop_run(data.loop);
419 g_main_loop_unref(data.loop);
421 error_propagate(errp, data.error);
422 object_unref(OBJECT(tioc));
426 return QIO_CHANNEL(tioc);
430 int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint16_t *flags,
431 QCryptoTLSCreds *tlscreds, const char *hostname,
433 off_t *size, Error **errp)
440 TRACE("Receiving negotiation tlscreds=%p hostname=%s.",
441 tlscreds, hostname ? hostname : "<null>");
448 if (tlscreds && !outioc) {
449 error_setg(errp, "Output I/O channel required for TLS");
453 if (nbd_read(ioc, buf, 8, errp) < 0) {
454 error_prepend(errp, "Failed to read data");
459 if (strlen(buf) == 0) {
460 error_setg(errp, "Server connection closed unexpectedly");
464 magic = ldq_be_p(buf);
465 TRACE("Magic is 0x%" PRIx64, magic);
467 if (memcmp(buf, "NBDMAGIC", 8) != 0) {
468 error_setg(errp, "Invalid magic received");
472 if (nbd_read(ioc, &magic, sizeof(magic), errp) < 0) {
473 error_prepend(errp, "Failed to read magic");
476 magic = be64_to_cpu(magic);
477 TRACE("Magic is 0x%" PRIx64, magic);
479 if (magic == NBD_OPTS_MAGIC) {
480 uint32_t clientflags = 0;
481 uint16_t globalflags;
482 bool fixedNewStyle = false;
484 if (nbd_read(ioc, &globalflags, sizeof(globalflags), errp) < 0) {
485 error_prepend(errp, "Failed to read server flags");
488 globalflags = be16_to_cpu(globalflags);
489 TRACE("Global flags are %" PRIx32, globalflags);
490 if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {
491 fixedNewStyle = true;
492 clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;
494 if (globalflags & NBD_FLAG_NO_ZEROES) {
496 clientflags |= NBD_FLAG_C_NO_ZEROES;
498 /* client requested flags */
499 clientflags = cpu_to_be32(clientflags);
500 if (nbd_write(ioc, &clientflags, sizeof(clientflags), errp) < 0) {
501 error_prepend(errp, "Failed to send clientflags field");
506 *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);
512 error_setg(errp, "Server does not support STARTTLS");
517 TRACE("Using default NBD export name \"\"");
521 /* Check our desired export is present in the
522 * server export list. Since NBD_OPT_EXPORT_NAME
523 * cannot return an error message, running this
524 * query gives us good error reporting if the
525 * server required TLS
527 if (nbd_receive_query_exports(ioc, name, errp) < 0) {
531 /* write the export name request */
532 if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,
537 /* Read the response */
538 if (nbd_read(ioc, &s, sizeof(s), errp) < 0) {
539 error_prepend(errp, "Failed to read export length");
542 *size = be64_to_cpu(s);
544 if (nbd_read(ioc, flags, sizeof(*flags), errp) < 0) {
545 error_prepend(errp, "Failed to read export flags");
549 } else if (magic == NBD_CLIENT_MAGIC) {
553 error_setg(errp, "Server does not support export names");
557 error_setg(errp, "Server does not support STARTTLS");
561 if (nbd_read(ioc, &s, sizeof(s), errp) < 0) {
562 error_prepend(errp, "Failed to read export length");
565 *size = be64_to_cpu(s);
567 if (nbd_read(ioc, &oldflags, sizeof(oldflags), errp) < 0) {
568 error_prepend(errp, "Failed to read export flags");
571 be32_to_cpus(&oldflags);
572 if (oldflags & ~0xffff) {
573 error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);
578 error_setg(errp, "Bad magic received");
582 TRACE("Size is %" PRIu64 ", export flags %" PRIx16, *size, *flags);
583 if (zeroes && nbd_drop(ioc, 124, errp) < 0) {
584 error_prepend(errp, "Failed to read reserved block");
594 int nbd_init(int fd, QIOChannelSocket *sioc, uint16_t flags, off_t size,
597 unsigned long sectors = size / BDRV_SECTOR_SIZE;
598 if (size / BDRV_SECTOR_SIZE != sectors) {
599 error_setg(errp, "Export size %lld too large for 32-bit kernel",
604 TRACE("Setting NBD socket");
606 if (ioctl(fd, NBD_SET_SOCK, (unsigned long) sioc->fd) < 0) {
608 error_setg(errp, "Failed to set NBD socket");
612 TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE);
614 if (ioctl(fd, NBD_SET_BLKSIZE, (unsigned long)BDRV_SECTOR_SIZE) < 0) {
616 error_setg(errp, "Failed setting NBD block size");
620 TRACE("Setting size to %lu block(s)", sectors);
621 if (size % BDRV_SECTOR_SIZE) {
622 TRACE("Ignoring trailing %d bytes of export",
623 (int) (size % BDRV_SECTOR_SIZE));
626 if (ioctl(fd, NBD_SET_SIZE_BLOCKS, sectors) < 0) {
628 error_setg(errp, "Failed setting size (in blocks)");
632 if (ioctl(fd, NBD_SET_FLAGS, (unsigned long) flags) < 0) {
633 if (errno == ENOTTY) {
634 int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;
635 TRACE("Setting readonly attribute");
637 if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
639 error_setg(errp, "Failed setting read-only attribute");
644 error_setg(errp, "Failed setting flags");
649 TRACE("Negotiation ended");
654 int nbd_client(int fd)
659 TRACE("Doing NBD loop");
661 ret = ioctl(fd, NBD_DO_IT);
662 if (ret < 0 && errno == EPIPE) {
663 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
664 * the socket via NBD_DISCONNECT. We do not want to return 1 in
671 TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
673 TRACE("Clearing NBD queue");
674 ioctl(fd, NBD_CLEAR_QUE);
676 TRACE("Clearing NBD socket");
677 ioctl(fd, NBD_CLEAR_SOCK);
683 int nbd_disconnect(int fd)
685 ioctl(fd, NBD_CLEAR_QUE);
686 ioctl(fd, NBD_DISCONNECT);
687 ioctl(fd, NBD_CLEAR_SOCK);
692 int nbd_init(int fd, QIOChannelSocket *ioc, uint16_t flags, off_t size,
695 error_setg(errp, "nbd_init is only supported on Linux");
699 int nbd_client(int fd)
703 int nbd_disconnect(int fd)
709 ssize_t nbd_send_request(QIOChannel *ioc, NBDRequest *request)
711 uint8_t buf[NBD_REQUEST_SIZE];
713 TRACE("Sending request to server: "
714 "{ .from = %" PRIu64", .len = %" PRIu32 ", .handle = %" PRIu64
715 ", .flags = %" PRIx16 ", .type = %" PRIu16 " }",
716 request->from, request->len, request->handle,
717 request->flags, request->type);
719 stl_be_p(buf, NBD_REQUEST_MAGIC);
720 stw_be_p(buf + 4, request->flags);
721 stw_be_p(buf + 6, request->type);
722 stq_be_p(buf + 8, request->handle);
723 stq_be_p(buf + 16, request->from);
724 stl_be_p(buf + 24, request->len);
726 return nbd_write(ioc, buf, sizeof(buf), NULL);
729 ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
731 uint8_t buf[NBD_REPLY_SIZE];
735 ret = nbd_read_eof(ioc, buf, sizeof(buf), errp);
740 if (ret != sizeof(buf)) {
741 error_setg(errp, "read failed");
746 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
747 [ 4 .. 7] error (0 == no error)
751 magic = ldl_be_p(buf);
752 reply->error = ldl_be_p(buf + 4);
753 reply->handle = ldq_be_p(buf + 8);
755 reply->error = nbd_errno_to_system_errno(reply->error);
757 if (reply->error == ESHUTDOWN) {
758 /* This works even on mingw which lacks a native ESHUTDOWN */
759 error_setg(errp, "server shutting down");
762 TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32
763 ", handle = %" PRIu64" }",
764 magic, reply->error, reply->handle);
766 if (magic != NBD_REPLY_MAGIC) {
767 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);