2 * Copyright (C) 2016 Red Hat, Inc.
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
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 TRACE("Magic is %c%c%c%c%c%c%c%c",
465 qemu_isprint(buf
[0]) ? buf
[0] : '.',
466 qemu_isprint(buf
[1]) ? buf
[1] : '.',
467 qemu_isprint(buf
[2]) ? buf
[2] : '.',
468 qemu_isprint(buf
[3]) ? buf
[3] : '.',
469 qemu_isprint(buf
[4]) ? buf
[4] : '.',
470 qemu_isprint(buf
[5]) ? buf
[5] : '.',
471 qemu_isprint(buf
[6]) ? buf
[6] : '.',
472 qemu_isprint(buf
[7]) ? buf
[7] : '.');
474 if (memcmp(buf
, "NBDMAGIC", 8) != 0) {
475 error_setg(errp
, "Invalid magic received");
479 if (nbd_read(ioc
, &magic
, sizeof(magic
), errp
) < 0) {
480 error_prepend(errp
, "Failed to read magic");
483 magic
= be64_to_cpu(magic
);
484 TRACE("Magic is 0x%" PRIx64
, magic
);
486 if (magic
== NBD_OPTS_MAGIC
) {
487 uint32_t clientflags
= 0;
488 uint16_t globalflags
;
489 bool fixedNewStyle
= false;
491 if (nbd_read(ioc
, &globalflags
, sizeof(globalflags
), errp
) < 0) {
492 error_prepend(errp
, "Failed to read server flags");
495 globalflags
= be16_to_cpu(globalflags
);
496 TRACE("Global flags are %" PRIx32
, globalflags
);
497 if (globalflags
& NBD_FLAG_FIXED_NEWSTYLE
) {
498 fixedNewStyle
= true;
499 TRACE("Server supports fixed new style");
500 clientflags
|= NBD_FLAG_C_FIXED_NEWSTYLE
;
502 if (globalflags
& NBD_FLAG_NO_ZEROES
) {
504 TRACE("Server supports no zeroes");
505 clientflags
|= NBD_FLAG_C_NO_ZEROES
;
507 /* client requested flags */
508 clientflags
= cpu_to_be32(clientflags
);
509 if (nbd_write(ioc
, &clientflags
, sizeof(clientflags
), errp
) < 0) {
510 error_prepend(errp
, "Failed to send clientflags field");
515 *outioc
= nbd_receive_starttls(ioc
, tlscreds
, hostname
, errp
);
521 error_setg(errp
, "Server does not support STARTTLS");
526 TRACE("Using default NBD export name \"\"");
530 /* Check our desired export is present in the
531 * server export list. Since NBD_OPT_EXPORT_NAME
532 * cannot return an error message, running this
533 * query gives us good error reporting if the
534 * server required TLS
536 if (nbd_receive_query_exports(ioc
, name
, errp
) < 0) {
540 /* write the export name request */
541 if (nbd_send_option_request(ioc
, NBD_OPT_EXPORT_NAME
, -1, name
,
546 /* Read the response */
547 if (nbd_read(ioc
, &s
, sizeof(s
), errp
) < 0) {
548 error_prepend(errp
, "Failed to read export length");
551 *size
= be64_to_cpu(s
);
553 if (nbd_read(ioc
, flags
, sizeof(*flags
), errp
) < 0) {
554 error_prepend(errp
, "Failed to read export flags");
558 } else if (magic
== NBD_CLIENT_MAGIC
) {
562 error_setg(errp
, "Server does not support export names");
566 error_setg(errp
, "Server does not support STARTTLS");
570 if (nbd_read(ioc
, &s
, sizeof(s
), errp
) < 0) {
571 error_prepend(errp
, "Failed to read export length");
574 *size
= be64_to_cpu(s
);
575 TRACE("Size is %" PRIu64
, *size
);
577 if (nbd_read(ioc
, &oldflags
, sizeof(oldflags
), errp
) < 0) {
578 error_prepend(errp
, "Failed to read export flags");
581 be32_to_cpus(&oldflags
);
582 if (oldflags
& ~0xffff) {
583 error_setg(errp
, "Unexpected export flags %0x" PRIx32
, oldflags
);
588 error_setg(errp
, "Bad magic received");
592 TRACE("Size is %" PRIu64
", export flags %" PRIx16
, *size
, *flags
);
593 if (zeroes
&& nbd_drop(ioc
, 124, errp
) < 0) {
594 error_prepend(errp
, "Failed to read reserved block");
604 int nbd_init(int fd
, QIOChannelSocket
*sioc
, uint16_t flags
, off_t size
,
607 unsigned long sectors
= size
/ BDRV_SECTOR_SIZE
;
608 if (size
/ BDRV_SECTOR_SIZE
!= sectors
) {
609 error_setg(errp
, "Export size %lld too large for 32-bit kernel",
614 TRACE("Setting NBD socket");
616 if (ioctl(fd
, NBD_SET_SOCK
, (unsigned long) sioc
->fd
) < 0) {
618 error_setg(errp
, "Failed to set NBD socket");
622 TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE
);
624 if (ioctl(fd
, NBD_SET_BLKSIZE
, (unsigned long)BDRV_SECTOR_SIZE
) < 0) {
626 error_setg(errp
, "Failed setting NBD block size");
630 TRACE("Setting size to %lu block(s)", sectors
);
631 if (size
% BDRV_SECTOR_SIZE
) {
632 TRACE("Ignoring trailing %d bytes of export",
633 (int) (size
% BDRV_SECTOR_SIZE
));
636 if (ioctl(fd
, NBD_SET_SIZE_BLOCKS
, sectors
) < 0) {
638 error_setg(errp
, "Failed setting size (in blocks)");
642 if (ioctl(fd
, NBD_SET_FLAGS
, (unsigned long) flags
) < 0) {
643 if (errno
== ENOTTY
) {
644 int read_only
= (flags
& NBD_FLAG_READ_ONLY
) != 0;
645 TRACE("Setting readonly attribute");
647 if (ioctl(fd
, BLKROSET
, (unsigned long) &read_only
) < 0) {
649 error_setg(errp
, "Failed setting read-only attribute");
654 error_setg(errp
, "Failed setting flags");
659 TRACE("Negotiation ended");
664 int nbd_client(int fd
)
669 TRACE("Doing NBD loop");
671 ret
= ioctl(fd
, NBD_DO_IT
);
672 if (ret
< 0 && errno
== EPIPE
) {
673 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
674 * the socket via NBD_DISCONNECT. We do not want to return 1 in
681 TRACE("NBD loop returned %d: %s", ret
, strerror(serrno
));
683 TRACE("Clearing NBD queue");
684 ioctl(fd
, NBD_CLEAR_QUE
);
686 TRACE("Clearing NBD socket");
687 ioctl(fd
, NBD_CLEAR_SOCK
);
693 int nbd_disconnect(int fd
)
695 ioctl(fd
, NBD_CLEAR_QUE
);
696 ioctl(fd
, NBD_DISCONNECT
);
697 ioctl(fd
, NBD_CLEAR_SOCK
);
702 int nbd_init(int fd
, QIOChannelSocket
*ioc
, uint16_t flags
, off_t size
,
705 error_setg(errp
, "nbd_init is only supported on Linux");
709 int nbd_client(int fd
)
713 int nbd_disconnect(int fd
)
719 ssize_t
nbd_send_request(QIOChannel
*ioc
, NBDRequest
*request
)
721 uint8_t buf
[NBD_REQUEST_SIZE
];
723 TRACE("Sending request to server: "
724 "{ .from = %" PRIu64
", .len = %" PRIu32
", .handle = %" PRIu64
725 ", .flags = %" PRIx16
", .type = %" PRIu16
" }",
726 request
->from
, request
->len
, request
->handle
,
727 request
->flags
, request
->type
);
729 stl_be_p(buf
, NBD_REQUEST_MAGIC
);
730 stw_be_p(buf
+ 4, request
->flags
);
731 stw_be_p(buf
+ 6, request
->type
);
732 stq_be_p(buf
+ 8, request
->handle
);
733 stq_be_p(buf
+ 16, request
->from
);
734 stl_be_p(buf
+ 24, request
->len
);
736 return nbd_write(ioc
, buf
, sizeof(buf
), NULL
);
739 ssize_t
nbd_receive_reply(QIOChannel
*ioc
, NBDReply
*reply
, Error
**errp
)
741 uint8_t buf
[NBD_REPLY_SIZE
];
745 ret
= nbd_read_eof(ioc
, buf
, sizeof(buf
), errp
);
750 if (ret
!= sizeof(buf
)) {
751 error_setg(errp
, "read failed");
756 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
757 [ 4 .. 7] error (0 == no error)
761 magic
= ldl_be_p(buf
);
762 reply
->error
= ldl_be_p(buf
+ 4);
763 reply
->handle
= ldq_be_p(buf
+ 8);
765 reply
->error
= nbd_errno_to_system_errno(reply
->error
);
767 if (reply
->error
== ESHUTDOWN
) {
768 /* This works even on mingw which lacks a native ESHUTDOWN */
769 error_setg(errp
, "server shutting down");
772 TRACE("Got reply: { magic = 0x%" PRIx32
", .error = % " PRId32
773 ", handle = %" PRIu64
" }",
774 magic
, reply
->error
, reply
->handle
);
776 if (magic
!= NBD_REPLY_MAGIC
) {
777 error_setg(errp
, "invalid magic (got 0x%" PRIx32
")", magic
);