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
)
38 TRACE("Squashing unexpected error %d to EINVAL", err
);
45 /* Definitions for opaque data types */
47 static QTAILQ_HEAD(, NBDExport
) exports
= QTAILQ_HEAD_INITIALIZER(exports
);
49 /* That's all folks */
51 /* Basic flow for negotiation
78 /* Send an option request.
80 * The request is for option @opt, with @data containing @len bytes of
81 * additional payload for the request (@len may be -1 to treat @data as
82 * a C string; and @data may be NULL if @len is 0).
83 * Return 0 if successful, -1 with errp set if it is impossible to
85 static int nbd_send_option_request(QIOChannel
*ioc
, uint32_t opt
,
86 uint32_t len
, const char *data
,
90 QEMU_BUILD_BUG_ON(sizeof(req
) != 16);
93 req
.length
= len
= strlen(data
);
95 TRACE("Sending option request %" PRIu32
", len %" PRIu32
, opt
, len
);
97 stq_be_p(&req
.magic
, NBD_OPTS_MAGIC
);
98 stl_be_p(&req
.option
, opt
);
99 stl_be_p(&req
.length
, len
);
101 if (write_sync(ioc
, &req
, sizeof(req
)) != sizeof(req
)) {
102 error_setg(errp
, "Failed to send option request header");
106 if (len
&& write_sync(ioc
, (char *) data
, len
) != len
) {
107 error_setg(errp
, "Failed to send option request data");
114 /* Send NBD_OPT_ABORT as a courtesy to let the server know that we are
115 * not going to attempt further negotiation. */
116 static void nbd_send_opt_abort(QIOChannel
*ioc
)
118 /* Technically, a compliant server is supposed to reply to us; but
119 * older servers disconnected instead. At any rate, we're allowed
120 * to disconnect without waiting for the server reply, so we don't
121 * even care if the request makes it to the server, let alone
122 * waiting around for whether the server replies. */
123 nbd_send_option_request(ioc
, NBD_OPT_ABORT
, 0, NULL
, NULL
);
127 /* Receive the header of an option reply, which should match the given
128 * opt. Read through the length field, but NOT the length bytes of
129 * payload. Return 0 if successful, -1 with errp set if it is
130 * impossible to continue. */
131 static int nbd_receive_option_reply(QIOChannel
*ioc
, uint32_t opt
,
132 nbd_opt_reply
*reply
, Error
**errp
)
134 QEMU_BUILD_BUG_ON(sizeof(*reply
) != 20);
135 if (read_sync(ioc
, reply
, sizeof(*reply
)) != sizeof(*reply
)) {
136 error_setg(errp
, "failed to read option reply");
137 nbd_send_opt_abort(ioc
);
140 be64_to_cpus(&reply
->magic
);
141 be32_to_cpus(&reply
->option
);
142 be32_to_cpus(&reply
->type
);
143 be32_to_cpus(&reply
->length
);
145 TRACE("Received option reply %" PRIx32
", type %" PRIx32
", len %" PRIu32
,
146 reply
->option
, reply
->type
, reply
->length
);
148 if (reply
->magic
!= NBD_REP_MAGIC
) {
149 error_setg(errp
, "Unexpected option reply magic");
150 nbd_send_opt_abort(ioc
);
153 if (reply
->option
!= opt
) {
154 error_setg(errp
, "Unexpected option type %x expected %x",
156 nbd_send_opt_abort(ioc
);
162 /* If reply represents success, return 1 without further action.
163 * If reply represents an error, consume the optional payload of
164 * the packet on ioc. Then return 0 for unsupported (so the client
165 * can fall back to other approaches), or -1 with errp set for other
168 static int nbd_handle_reply_err(QIOChannel
*ioc
, nbd_opt_reply
*reply
,
174 if (!(reply
->type
& (1 << 31))) {
179 if (reply
->length
> NBD_MAX_BUFFER_SIZE
) {
180 error_setg(errp
, "server's error message is too long");
183 msg
= g_malloc(reply
->length
+ 1);
184 if (read_sync(ioc
, msg
, reply
->length
) != reply
->length
) {
185 error_setg(errp
, "failed to read option error message");
188 msg
[reply
->length
] = '\0';
191 switch (reply
->type
) {
192 case NBD_REP_ERR_UNSUP
:
193 TRACE("server doesn't understand request %" PRIx32
194 ", attempting fallback", reply
->option
);
198 case NBD_REP_ERR_POLICY
:
199 error_setg(errp
, "Denied by server for option %" PRIx32
,
203 case NBD_REP_ERR_INVALID
:
204 error_setg(errp
, "Invalid data length for option %" PRIx32
,
208 case NBD_REP_ERR_TLS_REQD
:
209 error_setg(errp
, "TLS negotiation required before option %" PRIx32
,
214 error_setg(errp
, "Unknown error code when asking for option %" PRIx32
,
220 error_append_hint(errp
, "%s\n", msg
);
226 nbd_send_opt_abort(ioc
);
231 static int nbd_receive_list(QIOChannel
*ioc
, char **name
, Error
**errp
)
239 if (nbd_receive_option_reply(ioc
, NBD_OPT_LIST
, &reply
, errp
) < 0) {
242 error
= nbd_handle_reply_err(ioc
, &reply
, errp
);
248 if (reply
.type
== NBD_REP_ACK
) {
250 error_setg(errp
, "length too long for option end");
251 nbd_send_opt_abort(ioc
);
254 } else if (reply
.type
== NBD_REP_SERVER
) {
255 if (len
< sizeof(namelen
) || len
> NBD_MAX_BUFFER_SIZE
) {
256 error_setg(errp
, "incorrect option length %" PRIu32
, len
);
257 nbd_send_opt_abort(ioc
);
260 if (read_sync(ioc
, &namelen
, sizeof(namelen
)) != sizeof(namelen
)) {
261 error_setg(errp
, "failed to read option name length");
262 nbd_send_opt_abort(ioc
);
265 namelen
= be32_to_cpu(namelen
);
266 len
-= sizeof(namelen
);
268 error_setg(errp
, "incorrect option name length");
269 nbd_send_opt_abort(ioc
);
272 if (namelen
> NBD_MAX_NAME_SIZE
) {
273 error_setg(errp
, "export name length too long %" PRIu32
, namelen
);
274 nbd_send_opt_abort(ioc
);
278 *name
= g_new0(char, namelen
+ 1);
279 if (read_sync(ioc
, *name
, namelen
) != namelen
) {
280 error_setg(errp
, "failed to read export name");
283 nbd_send_opt_abort(ioc
);
286 (*name
)[namelen
] = '\0';
289 char *buf
= g_malloc(len
+ 1);
290 if (read_sync(ioc
, buf
, len
) != len
) {
291 error_setg(errp
, "failed to read export description");
295 nbd_send_opt_abort(ioc
);
299 TRACE("Ignoring export description: %s", buf
);
303 error_setg(errp
, "Unexpected reply type %" PRIx32
" expected %x",
304 reply
.type
, NBD_REP_SERVER
);
305 nbd_send_opt_abort(ioc
);
312 static int nbd_receive_query_exports(QIOChannel
*ioc
,
313 const char *wantname
,
316 bool foundExport
= false;
318 TRACE("Querying export list");
319 if (nbd_send_option_request(ioc
, NBD_OPT_LIST
, 0, NULL
, errp
) < 0) {
323 TRACE("Reading available export names");
326 int ret
= nbd_receive_list(ioc
, &name
, errp
);
334 /* Server doesn't support export listing, so
335 * we will just assume an export with our
336 * wanted name exists */
341 TRACE("End of export name list");
344 if (g_str_equal(name
, wantname
)) {
346 TRACE("Found desired export name '%s'", name
);
348 TRACE("Ignored export name '%s'", name
);
354 error_setg(errp
, "No export with name '%s' available", wantname
);
355 nbd_send_opt_abort(ioc
);
362 static QIOChannel
*nbd_receive_starttls(QIOChannel
*ioc
,
363 QCryptoTLSCreds
*tlscreds
,
364 const char *hostname
, Error
**errp
)
368 struct NBDTLSHandshakeData data
= { 0 };
370 TRACE("Requesting TLS from server");
371 if (nbd_send_option_request(ioc
, NBD_OPT_STARTTLS
, 0, NULL
, errp
) < 0) {
375 TRACE("Getting TLS reply from server");
376 if (nbd_receive_option_reply(ioc
, NBD_OPT_STARTTLS
, &reply
, errp
) < 0) {
380 if (reply
.type
!= NBD_REP_ACK
) {
381 error_setg(errp
, "Server rejected request to start TLS %" PRIx32
,
383 nbd_send_opt_abort(ioc
);
387 if (reply
.length
!= 0) {
388 error_setg(errp
, "Start TLS response was not zero %" PRIu32
,
390 nbd_send_opt_abort(ioc
);
394 TRACE("TLS request approved, setting up TLS");
395 tioc
= qio_channel_tls_new_client(ioc
, tlscreds
, hostname
, errp
);
399 qio_channel_set_name(QIO_CHANNEL(tioc
), "nbd-client-tls");
400 data
.loop
= g_main_loop_new(g_main_context_default(), FALSE
);
401 TRACE("Starting TLS handshake");
402 qio_channel_tls_handshake(tioc
,
407 if (!data
.complete
) {
408 g_main_loop_run(data
.loop
);
410 g_main_loop_unref(data
.loop
);
412 error_propagate(errp
, data
.error
);
413 object_unref(OBJECT(tioc
));
417 return QIO_CHANNEL(tioc
);
421 int nbd_receive_negotiate(QIOChannel
*ioc
, const char *name
, uint16_t *flags
,
422 QCryptoTLSCreds
*tlscreds
, const char *hostname
,
424 off_t
*size
, Error
**errp
)
430 TRACE("Receiving negotiation tlscreds=%p hostname=%s.",
431 tlscreds
, hostname
? hostname
: "<null>");
438 if (tlscreds
&& !outioc
) {
439 error_setg(errp
, "Output I/O channel required for TLS");
443 if (read_sync(ioc
, buf
, 8) != 8) {
444 error_setg(errp
, "Failed to read data");
449 if (strlen(buf
) == 0) {
450 error_setg(errp
, "Server connection closed unexpectedly");
454 TRACE("Magic is %c%c%c%c%c%c%c%c",
455 qemu_isprint(buf
[0]) ? buf
[0] : '.',
456 qemu_isprint(buf
[1]) ? buf
[1] : '.',
457 qemu_isprint(buf
[2]) ? buf
[2] : '.',
458 qemu_isprint(buf
[3]) ? buf
[3] : '.',
459 qemu_isprint(buf
[4]) ? buf
[4] : '.',
460 qemu_isprint(buf
[5]) ? buf
[5] : '.',
461 qemu_isprint(buf
[6]) ? buf
[6] : '.',
462 qemu_isprint(buf
[7]) ? buf
[7] : '.');
464 if (memcmp(buf
, "NBDMAGIC", 8) != 0) {
465 error_setg(errp
, "Invalid magic received");
469 if (read_sync(ioc
, &magic
, sizeof(magic
)) != sizeof(magic
)) {
470 error_setg(errp
, "Failed to read magic");
473 magic
= be64_to_cpu(magic
);
474 TRACE("Magic is 0x%" PRIx64
, magic
);
476 if (magic
== NBD_OPTS_MAGIC
) {
477 uint32_t clientflags
= 0;
478 uint16_t globalflags
;
479 bool fixedNewStyle
= false;
481 if (read_sync(ioc
, &globalflags
, sizeof(globalflags
)) !=
482 sizeof(globalflags
)) {
483 error_setg(errp
, "Failed to read server flags");
486 globalflags
= be16_to_cpu(globalflags
);
487 TRACE("Global flags are %" PRIx32
, globalflags
);
488 if (globalflags
& NBD_FLAG_FIXED_NEWSTYLE
) {
489 fixedNewStyle
= true;
490 TRACE("Server supports fixed new style");
491 clientflags
|= NBD_FLAG_C_FIXED_NEWSTYLE
;
493 /* client requested flags */
494 clientflags
= cpu_to_be32(clientflags
);
495 if (write_sync(ioc
, &clientflags
, sizeof(clientflags
)) !=
496 sizeof(clientflags
)) {
497 error_setg(errp
, "Failed to send clientflags field");
502 *outioc
= nbd_receive_starttls(ioc
, tlscreds
, hostname
, errp
);
508 error_setg(errp
, "Server does not support STARTTLS");
513 TRACE("Using default NBD export name \"\"");
517 /* Check our desired export is present in the
518 * server export list. Since NBD_OPT_EXPORT_NAME
519 * cannot return an error message, running this
520 * query gives us good error reporting if the
521 * server required TLS
523 if (nbd_receive_query_exports(ioc
, name
, errp
) < 0) {
527 /* write the export name request */
528 if (nbd_send_option_request(ioc
, NBD_OPT_EXPORT_NAME
, -1, name
,
533 /* Read the response */
534 if (read_sync(ioc
, &s
, sizeof(s
)) != sizeof(s
)) {
535 error_setg(errp
, "Failed to read export length");
538 *size
= be64_to_cpu(s
);
540 if (read_sync(ioc
, flags
, sizeof(*flags
)) != sizeof(*flags
)) {
541 error_setg(errp
, "Failed to read export flags");
545 } else if (magic
== NBD_CLIENT_MAGIC
) {
549 error_setg(errp
, "Server does not support export names");
553 error_setg(errp
, "Server does not support STARTTLS");
557 if (read_sync(ioc
, &s
, sizeof(s
)) != sizeof(s
)) {
558 error_setg(errp
, "Failed to read export length");
561 *size
= be64_to_cpu(s
);
562 TRACE("Size is %" PRIu64
, *size
);
564 if (read_sync(ioc
, &oldflags
, sizeof(oldflags
)) != sizeof(oldflags
)) {
565 error_setg(errp
, "Failed to read export flags");
568 be32_to_cpus(&oldflags
);
569 if (oldflags
& ~0xffff) {
570 error_setg(errp
, "Unexpected export flags %0x" PRIx32
, oldflags
);
575 error_setg(errp
, "Bad magic received");
579 TRACE("Size is %" PRIu64
", export flags %" PRIx16
, *size
, *flags
);
580 if (read_sync(ioc
, &buf
, 124) != 124) {
581 error_setg(errp
, "Failed to read reserved block");
591 int nbd_init(int fd
, QIOChannelSocket
*sioc
, uint16_t flags
, off_t size
)
593 unsigned long sectors
= size
/ BDRV_SECTOR_SIZE
;
594 if (size
/ BDRV_SECTOR_SIZE
!= sectors
) {
595 LOG("Export size %lld too large for 32-bit kernel", (long long) size
);
599 TRACE("Setting NBD socket");
601 if (ioctl(fd
, NBD_SET_SOCK
, (unsigned long) sioc
->fd
) < 0) {
603 LOG("Failed to set NBD socket");
607 TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE
);
609 if (ioctl(fd
, NBD_SET_BLKSIZE
, (unsigned long)BDRV_SECTOR_SIZE
) < 0) {
611 LOG("Failed setting NBD block size");
615 TRACE("Setting size to %lu block(s)", sectors
);
616 if (size
% BDRV_SECTOR_SIZE
) {
617 TRACE("Ignoring trailing %d bytes of export",
618 (int) (size
% BDRV_SECTOR_SIZE
));
621 if (ioctl(fd
, NBD_SET_SIZE_BLOCKS
, sectors
) < 0) {
623 LOG("Failed setting size (in blocks)");
627 if (ioctl(fd
, NBD_SET_FLAGS
, (unsigned long) flags
) < 0) {
628 if (errno
== ENOTTY
) {
629 int read_only
= (flags
& NBD_FLAG_READ_ONLY
) != 0;
630 TRACE("Setting readonly attribute");
632 if (ioctl(fd
, BLKROSET
, (unsigned long) &read_only
) < 0) {
634 LOG("Failed setting read-only attribute");
639 LOG("Failed setting flags");
644 TRACE("Negotiation ended");
649 int nbd_client(int fd
)
654 TRACE("Doing NBD loop");
656 ret
= ioctl(fd
, NBD_DO_IT
);
657 if (ret
< 0 && errno
== EPIPE
) {
658 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
659 * the socket via NBD_DISCONNECT. We do not want to return 1 in
666 TRACE("NBD loop returned %d: %s", ret
, strerror(serrno
));
668 TRACE("Clearing NBD queue");
669 ioctl(fd
, NBD_CLEAR_QUE
);
671 TRACE("Clearing NBD socket");
672 ioctl(fd
, NBD_CLEAR_SOCK
);
678 int nbd_disconnect(int fd
)
680 ioctl(fd
, NBD_CLEAR_QUE
);
681 ioctl(fd
, NBD_DISCONNECT
);
682 ioctl(fd
, NBD_CLEAR_SOCK
);
687 int nbd_init(int fd
, QIOChannelSocket
*ioc
, uint16_t flags
, off_t size
)
692 int nbd_client(int fd
)
696 int nbd_disconnect(int fd
)
702 ssize_t
nbd_send_request(QIOChannel
*ioc
, NBDRequest
*request
)
704 uint8_t buf
[NBD_REQUEST_SIZE
];
707 TRACE("Sending request to server: "
708 "{ .from = %" PRIu64
", .len = %" PRIu32
", .handle = %" PRIu64
709 ", .flags = %" PRIx16
", .type = %" PRIu16
" }",
710 request
->from
, request
->len
, request
->handle
,
711 request
->flags
, request
->type
);
713 stl_be_p(buf
, NBD_REQUEST_MAGIC
);
714 stw_be_p(buf
+ 4, request
->flags
);
715 stw_be_p(buf
+ 6, request
->type
);
716 stq_be_p(buf
+ 8, request
->handle
);
717 stq_be_p(buf
+ 16, request
->from
);
718 stl_be_p(buf
+ 24, request
->len
);
720 ret
= write_sync(ioc
, buf
, sizeof(buf
));
725 if (ret
!= sizeof(buf
)) {
726 LOG("writing to socket failed");
732 ssize_t
nbd_receive_reply(QIOChannel
*ioc
, NBDReply
*reply
)
734 uint8_t buf
[NBD_REPLY_SIZE
];
738 ret
= read_sync(ioc
, buf
, sizeof(buf
));
743 if (ret
!= sizeof(buf
)) {
749 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
750 [ 4 .. 7] error (0 == no error)
754 magic
= ldl_be_p(buf
);
755 reply
->error
= ldl_be_p(buf
+ 4);
756 reply
->handle
= ldq_be_p(buf
+ 8);
758 reply
->error
= nbd_errno_to_system_errno(reply
->error
);
760 TRACE("Got reply: { magic = 0x%" PRIx32
", .error = % " PRId32
761 ", handle = %" PRIu64
" }",
762 magic
, reply
->error
, reply
->handle
);
764 if (magic
!= NBD_REPLY_MAGIC
) {
765 LOG("invalid magic (got 0x%" PRIx32
")", magic
);