]> git.proxmox.com Git - mirror_qemu.git/blame - nbd/client.c
nbd: refactor tracing
[mirror_qemu.git] / nbd / client.c
CommitLineData
798bfe00 1/*
b626b51a 2 * Copyright (C) 2016 Red Hat, Inc.
798bfe00
FZ
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 *
5 * Network Block Device Client 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
d38ea87a 20#include "qemu/osdep.h"
da34e65c 21#include "qapi/error.h"
798bfe00
FZ
22#include "nbd-internal.h"
23
24static int nbd_errno_to_system_errno(int err)
25{
8b34a9db 26 int ret;
798bfe00
FZ
27 switch (err) {
28 case NBD_SUCCESS:
8b34a9db
EB
29 ret = 0;
30 break;
798bfe00 31 case NBD_EPERM:
8b34a9db
EB
32 ret = EPERM;
33 break;
798bfe00 34 case NBD_EIO:
8b34a9db
EB
35 ret = EIO;
36 break;
798bfe00 37 case NBD_ENOMEM:
8b34a9db
EB
38 ret = ENOMEM;
39 break;
798bfe00 40 case NBD_ENOSPC:
8b34a9db
EB
41 ret = ENOSPC;
42 break;
b6f5d3b5
EB
43 case NBD_ESHUTDOWN:
44 ret = ESHUTDOWN;
45 break;
798bfe00 46 default:
f3c32fce
EB
47 TRACE("Squashing unexpected error %d to EINVAL", err);
48 /* fallthrough */
49 case NBD_EINVAL:
8b34a9db
EB
50 ret = EINVAL;
51 break;
798bfe00 52 }
8b34a9db 53 return ret;
798bfe00
FZ
54}
55
56/* Definitions for opaque data types */
57
58static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
59
60/* That's all folks */
61
62/* Basic flow for negotiation
63
64 Server Client
65 Negotiate
66
67 or
68
69 Server Client
70 Negotiate #1
71 Option
72 Negotiate #2
73
74 ----
75
76 followed by
77
78 Server Client
79 Request
80 Response
81 Request
82 Response
83 ...
84 ...
85 Request (type == 2)
86
87*/
88
c8a3a1b6
EB
89/* Send an option request.
90 *
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
95 * continue. */
96static int nbd_send_option_request(QIOChannel *ioc, uint32_t opt,
97 uint32_t len, const char *data,
98 Error **errp)
99{
100 nbd_option req;
101 QEMU_BUILD_BUG_ON(sizeof(req) != 16);
102
103 if (len == -1) {
104 req.length = len = strlen(data);
105 }
106 TRACE("Sending option request %" PRIu32", len %" PRIu32, opt, len);
107
108 stq_be_p(&req.magic, NBD_OPTS_MAGIC);
109 stl_be_p(&req.option, opt);
110 stl_be_p(&req.length, len);
111
d1fdf257 112 if (nbd_write(ioc, &req, sizeof(req), errp) < 0) {
e44ed99d 113 error_prepend(errp, "Failed to send option request header");
c8a3a1b6
EB
114 return -1;
115 }
116
d1fdf257 117 if (len && nbd_write(ioc, (char *) data, len, errp) < 0) {
e44ed99d 118 error_prepend(errp, "Failed to send option request data");
c8a3a1b6
EB
119 return -1;
120 }
121
122 return 0;
123}
124
2cdbf413
EB
125/* Send NBD_OPT_ABORT as a courtesy to let the server know that we are
126 * not going to attempt further negotiation. */
127static void nbd_send_opt_abort(QIOChannel *ioc)
128{
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);
135}
136
137
c8a3a1b6
EB
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. */
142static int nbd_receive_option_reply(QIOChannel *ioc, uint32_t opt,
143 nbd_opt_reply *reply, Error **errp)
144{
145 QEMU_BUILD_BUG_ON(sizeof(*reply) != 20);
d1fdf257 146 if (nbd_read(ioc, reply, sizeof(*reply), errp) < 0) {
e44ed99d 147 error_prepend(errp, "failed to read option reply");
2cdbf413 148 nbd_send_opt_abort(ioc);
c8a3a1b6
EB
149 return -1;
150 }
151 be64_to_cpus(&reply->magic);
152 be32_to_cpus(&reply->option);
153 be32_to_cpus(&reply->type);
154 be32_to_cpus(&reply->length);
155
156 TRACE("Received option reply %" PRIx32", type %" PRIx32", len %" PRIu32,
157 reply->option, reply->type, reply->length);
9344e5f5 158
c8a3a1b6
EB
159 if (reply->magic != NBD_REP_MAGIC) {
160 error_setg(errp, "Unexpected option reply magic");
2cdbf413 161 nbd_send_opt_abort(ioc);
c8a3a1b6
EB
162 return -1;
163 }
164 if (reply->option != opt) {
165 error_setg(errp, "Unexpected option type %x expected %x",
166 reply->option, opt);
2cdbf413 167 nbd_send_opt_abort(ioc);
c8a3a1b6
EB
168 return -1;
169 }
170 return 0;
171}
172
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
177 * errors.
6ff58164 178 */
c8a3a1b6 179static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,
6ff58164 180 Error **errp)
9344e5f5 181{
6ff58164
AB
182 char *msg = NULL;
183 int result = -1;
184
c8a3a1b6 185 if (!(reply->type & (1 << 31))) {
6ff58164
AB
186 return 1;
187 }
188
c8a3a1b6
EB
189 if (reply->length) {
190 if (reply->length > NBD_MAX_BUFFER_SIZE) {
6ff58164
AB
191 error_setg(errp, "server's error message is too long");
192 goto cleanup;
193 }
c8a3a1b6 194 msg = g_malloc(reply->length + 1);
d1fdf257 195 if (nbd_read(ioc, msg, reply->length, errp) < 0) {
e44ed99d 196 error_prepend(errp, "failed to read option error message");
6ff58164
AB
197 goto cleanup;
198 }
c8a3a1b6 199 msg[reply->length] = '\0';
9344e5f5
DB
200 }
201
c8a3a1b6 202 switch (reply->type) {
9344e5f5 203 case NBD_REP_ERR_UNSUP:
2cb34749 204 TRACE("server doesn't understand request %" PRIx32
c8a3a1b6 205 ", attempting fallback", reply->option);
6ff58164
AB
206 result = 0;
207 goto cleanup;
9344e5f5 208
f95910fe 209 case NBD_REP_ERR_POLICY:
c8a3a1b6
EB
210 error_setg(errp, "Denied by server for option %" PRIx32,
211 reply->option);
f95910fe
DB
212 break;
213
9344e5f5 214 case NBD_REP_ERR_INVALID:
c8a3a1b6
EB
215 error_setg(errp, "Invalid data length for option %" PRIx32,
216 reply->option);
9344e5f5
DB
217 break;
218
b6f5d3b5
EB
219 case NBD_REP_ERR_PLATFORM:
220 error_setg(errp, "Server lacks support for option %" PRIx32,
221 reply->option);
222 break;
223
f95910fe 224 case NBD_REP_ERR_TLS_REQD:
2cb34749 225 error_setg(errp, "TLS negotiation required before option %" PRIx32,
c8a3a1b6 226 reply->option);
f95910fe
DB
227 break;
228
b6f5d3b5
EB
229 case NBD_REP_ERR_SHUTDOWN:
230 error_setg(errp, "Server shutting down before option %" PRIx32,
231 reply->option);
232 break;
233
9344e5f5 234 default:
2cb34749 235 error_setg(errp, "Unknown error code when asking for option %" PRIx32,
c8a3a1b6 236 reply->option);
9344e5f5
DB
237 break;
238 }
239
6ff58164
AB
240 if (msg) {
241 error_append_hint(errp, "%s\n", msg);
242 }
243
244 cleanup:
245 g_free(msg);
2cdbf413
EB
246 if (result < 0) {
247 nbd_send_opt_abort(ioc);
248 }
6ff58164 249 return result;
9344e5f5
DB
250}
251
75368aab
EB
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. */
257static int nbd_receive_list(QIOChannel *ioc, const char *want, bool *match,
258 Error **errp)
9344e5f5 259{
c8a3a1b6 260 nbd_opt_reply reply;
9344e5f5
DB
261 uint32_t len;
262 uint32_t namelen;
75368aab 263 char name[NBD_MAX_NAME_SIZE + 1];
6ff58164 264 int error;
9344e5f5 265
c8a3a1b6 266 if (nbd_receive_option_reply(ioc, NBD_OPT_LIST, &reply, errp) < 0) {
9344e5f5
DB
267 return -1;
268 }
c8a3a1b6 269 error = nbd_handle_reply_err(ioc, &reply, errp);
6ff58164 270 if (error <= 0) {
75368aab
EB
271 /* The server did not support NBD_OPT_LIST, so set *match on
272 * the assumption that any name will be accepted. */
273 *match = true;
6ff58164 274 return error;
9344e5f5 275 }
c8a3a1b6 276 len = reply.length;
9344e5f5 277
c8a3a1b6 278 if (reply.type == NBD_REP_ACK) {
9344e5f5
DB
279 if (len != 0) {
280 error_setg(errp, "length too long for option end");
2cdbf413 281 nbd_send_opt_abort(ioc);
9344e5f5
DB
282 return -1;
283 }
75368aab
EB
284 return 0;
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);
289 return -1;
290 }
9344e5f5 291
75368aab
EB
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);
295 return -1;
296 }
d1fdf257 297 if (nbd_read(ioc, &namelen, sizeof(namelen), errp) < 0) {
e44ed99d 298 error_prepend(errp, "failed to read option name length");
75368aab
EB
299 nbd_send_opt_abort(ioc);
300 return -1;
301 }
302 namelen = be32_to_cpu(namelen);
303 len -= sizeof(namelen);
304 if (len < namelen) {
305 error_setg(errp, "incorrect option name length");
306 nbd_send_opt_abort(ioc);
307 return -1;
308 }
309 if (namelen != strlen(want)) {
d1fdf257 310 if (nbd_drop(ioc, len, errp) < 0) {
e44ed99d 311 error_prepend(errp, "failed to skip export name with wrong length");
7d3123e1
EB
312 nbd_send_opt_abort(ioc);
313 return -1;
200650d4 314 }
75368aab
EB
315 return 1;
316 }
317
318 assert(namelen < sizeof(name));
d1fdf257 319 if (nbd_read(ioc, name, namelen, errp) < 0) {
e44ed99d 320 error_prepend(errp, "failed to read export name");
75368aab
EB
321 nbd_send_opt_abort(ioc);
322 return -1;
323 }
324 name[namelen] = '\0';
325 len -= namelen;
d1fdf257 326 if (nbd_drop(ioc, len, errp) < 0) {
e44ed99d 327 error_prepend(errp, "failed to read export description");
2cdbf413 328 nbd_send_opt_abort(ioc);
9344e5f5
DB
329 return -1;
330 }
75368aab
EB
331 if (!strcmp(name, want)) {
332 *match = true;
333 }
9344e5f5
DB
334 return 1;
335}
336
337
75368aab 338/* Return -1 on failure, 0 if wantname is an available export. */
9344e5f5
DB
339static int nbd_receive_query_exports(QIOChannel *ioc,
340 const char *wantname,
341 Error **errp)
342{
9344e5f5
DB
343 bool foundExport = false;
344
75368aab 345 TRACE("Querying export list for '%s'", wantname);
c8a3a1b6 346 if (nbd_send_option_request(ioc, NBD_OPT_LIST, 0, NULL, errp) < 0) {
9344e5f5
DB
347 return -1;
348 }
349
350 TRACE("Reading available export names");
351 while (1) {
75368aab 352 int ret = nbd_receive_list(ioc, wantname, &foundExport, errp);
9344e5f5
DB
353
354 if (ret < 0) {
75368aab 355 /* Server gave unexpected reply */
9344e5f5 356 return -1;
75368aab
EB
357 } else if (ret == 0) {
358 /* Done iterating. */
359 if (!foundExport) {
360 error_setg(errp, "No export with name '%s' available",
361 wantname);
362 nbd_send_opt_abort(ioc);
363 return -1;
364 }
365 TRACE("Found desired export name '%s'", wantname);
366 return 0;
9344e5f5 367 }
9344e5f5 368 }
9344e5f5
DB
369}
370
f95910fe
DB
371static QIOChannel *nbd_receive_starttls(QIOChannel *ioc,
372 QCryptoTLSCreds *tlscreds,
373 const char *hostname, Error **errp)
374{
c8a3a1b6 375 nbd_opt_reply reply;
f95910fe
DB
376 QIOChannelTLS *tioc;
377 struct NBDTLSHandshakeData data = { 0 };
378
379 TRACE("Requesting TLS from server");
c8a3a1b6 380 if (nbd_send_option_request(ioc, NBD_OPT_STARTTLS, 0, NULL, errp) < 0) {
f95910fe
DB
381 return NULL;
382 }
383
384 TRACE("Getting TLS reply from server");
c8a3a1b6 385 if (nbd_receive_option_reply(ioc, NBD_OPT_STARTTLS, &reply, errp) < 0) {
f95910fe
DB
386 return NULL;
387 }
c8a3a1b6
EB
388
389 if (reply.type != NBD_REP_ACK) {
2cb34749 390 error_setg(errp, "Server rejected request to start TLS %" PRIx32,
c8a3a1b6 391 reply.type);
2cdbf413 392 nbd_send_opt_abort(ioc);
f95910fe
DB
393 return NULL;
394 }
395
c8a3a1b6 396 if (reply.length != 0) {
2cb34749 397 error_setg(errp, "Start TLS response was not zero %" PRIu32,
c8a3a1b6 398 reply.length);
2cdbf413 399 nbd_send_opt_abort(ioc);
f95910fe
DB
400 return NULL;
401 }
402
403 TRACE("TLS request approved, setting up TLS");
404 tioc = qio_channel_tls_new_client(ioc, tlscreds, hostname, errp);
405 if (!tioc) {
406 return NULL;
407 }
0d73f725 408 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-client-tls");
f95910fe 409 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
2cb34749 410 TRACE("Starting TLS handshake");
f95910fe
DB
411 qio_channel_tls_handshake(tioc,
412 nbd_tls_handshake,
413 &data,
414 NULL);
415
416 if (!data.complete) {
417 g_main_loop_run(data.loop);
418 }
419 g_main_loop_unref(data.loop);
420 if (data.error) {
421 error_propagate(errp, data.error);
422 object_unref(OBJECT(tioc));
423 return NULL;
424 }
425
426 return QIO_CHANNEL(tioc);
427}
428
429
7423f417 430int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint16_t *flags,
f95910fe
DB
431 QCryptoTLSCreds *tlscreds, const char *hostname,
432 QIOChannel **outioc,
798bfe00
FZ
433 off_t *size, Error **errp)
434{
435 char buf[256];
436 uint64_t magic, s;
798bfe00 437 int rc;
c203c59a 438 bool zeroes = true;
798bfe00 439
f95910fe
DB
440 TRACE("Receiving negotiation tlscreds=%p hostname=%s.",
441 tlscreds, hostname ? hostname : "<null>");
798bfe00
FZ
442
443 rc = -EINVAL;
444
f95910fe
DB
445 if (outioc) {
446 *outioc = NULL;
447 }
448 if (tlscreds && !outioc) {
449 error_setg(errp, "Output I/O channel required for TLS");
450 goto fail;
451 }
452
d1fdf257 453 if (nbd_read(ioc, buf, 8, errp) < 0) {
e44ed99d 454 error_prepend(errp, "Failed to read data");
798bfe00
FZ
455 goto fail;
456 }
457
458 buf[8] = '\0';
459 if (strlen(buf) == 0) {
460 error_setg(errp, "Server connection closed unexpectedly");
461 goto fail;
462 }
463
458d7a69
VSO
464 magic = ldq_be_p(buf);
465 TRACE("Magic is 0x%" PRIx64, magic);
798bfe00
FZ
466
467 if (memcmp(buf, "NBDMAGIC", 8) != 0) {
468 error_setg(errp, "Invalid magic received");
469 goto fail;
470 }
471
d1fdf257 472 if (nbd_read(ioc, &magic, sizeof(magic), errp) < 0) {
e44ed99d 473 error_prepend(errp, "Failed to read magic");
798bfe00
FZ
474 goto fail;
475 }
476 magic = be64_to_cpu(magic);
477 TRACE("Magic is 0x%" PRIx64, magic);
478
f72d705f 479 if (magic == NBD_OPTS_MAGIC) {
e2a9d9a3 480 uint32_t clientflags = 0;
e2a9d9a3 481 uint16_t globalflags;
9344e5f5 482 bool fixedNewStyle = false;
798bfe00 483
d1fdf257 484 if (nbd_read(ioc, &globalflags, sizeof(globalflags), errp) < 0) {
e44ed99d 485 error_prepend(errp, "Failed to read server flags");
798bfe00
FZ
486 goto fail;
487 }
9344e5f5 488 globalflags = be16_to_cpu(globalflags);
2cb34749 489 TRACE("Global flags are %" PRIx32, globalflags);
e2a9d9a3 490 if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {
9344e5f5 491 fixedNewStyle = true;
e2a9d9a3
DB
492 clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;
493 }
c203c59a
EB
494 if (globalflags & NBD_FLAG_NO_ZEROES) {
495 zeroes = false;
c203c59a
EB
496 clientflags |= NBD_FLAG_C_NO_ZEROES;
497 }
e2a9d9a3 498 /* client requested flags */
9344e5f5 499 clientflags = cpu_to_be32(clientflags);
d1fdf257 500 if (nbd_write(ioc, &clientflags, sizeof(clientflags), errp) < 0) {
e44ed99d 501 error_prepend(errp, "Failed to send clientflags field");
798bfe00
FZ
502 goto fail;
503 }
f95910fe
DB
504 if (tlscreds) {
505 if (fixedNewStyle) {
506 *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);
507 if (!*outioc) {
508 goto fail;
509 }
510 ioc = *outioc;
511 } else {
512 error_setg(errp, "Server does not support STARTTLS");
513 goto fail;
514 }
515 }
f72d705f 516 if (!name) {
69b49502
DB
517 TRACE("Using default NBD export name \"\"");
518 name = "";
f72d705f 519 }
9344e5f5
DB
520 if (fixedNewStyle) {
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
526 */
527 if (nbd_receive_query_exports(ioc, name, errp) < 0) {
528 goto fail;
529 }
530 }
c8a3a1b6
EB
531 /* write the export name request */
532 if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,
533 errp) < 0) {
798bfe00
FZ
534 goto fail;
535 }
f72d705f 536
c8a3a1b6 537 /* Read the response */
d1fdf257 538 if (nbd_read(ioc, &s, sizeof(s), errp) < 0) {
e44ed99d 539 error_prepend(errp, "Failed to read export length");
798bfe00
FZ
540 goto fail;
541 }
f72d705f 542 *size = be64_to_cpu(s);
798bfe00 543
d1fdf257 544 if (nbd_read(ioc, flags, sizeof(*flags), errp) < 0) {
e44ed99d 545 error_prepend(errp, "Failed to read export flags");
f72d705f
DB
546 goto fail;
547 }
7423f417 548 be16_to_cpus(flags);
f72d705f 549 } else if (magic == NBD_CLIENT_MAGIC) {
7423f417
EB
550 uint32_t oldflags;
551
f72d705f
DB
552 if (name) {
553 error_setg(errp, "Server does not support export names");
554 goto fail;
555 }
f95910fe
DB
556 if (tlscreds) {
557 error_setg(errp, "Server does not support STARTTLS");
558 goto fail;
559 }
f72d705f 560
d1fdf257 561 if (nbd_read(ioc, &s, sizeof(s), errp) < 0) {
e44ed99d 562 error_prepend(errp, "Failed to read export length");
f72d705f
DB
563 goto fail;
564 }
565 *size = be64_to_cpu(s);
798bfe00 566
d1fdf257 567 if (nbd_read(ioc, &oldflags, sizeof(oldflags), errp) < 0) {
e44ed99d 568 error_prepend(errp, "Failed to read export flags");
798bfe00
FZ
569 goto fail;
570 }
7423f417
EB
571 be32_to_cpus(&oldflags);
572 if (oldflags & ~0xffff) {
573 error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);
574 goto fail;
575 }
576 *flags = oldflags;
798bfe00 577 } else {
f72d705f
DB
578 error_setg(errp, "Bad magic received");
579 goto fail;
798bfe00 580 }
f72d705f 581
7423f417 582 TRACE("Size is %" PRIu64 ", export flags %" PRIx16, *size, *flags);
d1fdf257 583 if (zeroes && nbd_drop(ioc, 124, errp) < 0) {
e44ed99d 584 error_prepend(errp, "Failed to read reserved block");
798bfe00
FZ
585 goto fail;
586 }
587 rc = 0;
588
589fail:
590 return rc;
591}
592
593#ifdef __linux__
be41c100
VSO
594int nbd_init(int fd, QIOChannelSocket *sioc, uint16_t flags, off_t size,
595 Error **errp)
798bfe00 596{
f57e2416
EB
597 unsigned long sectors = size / BDRV_SECTOR_SIZE;
598 if (size / BDRV_SECTOR_SIZE != sectors) {
be41c100
VSO
599 error_setg(errp, "Export size %lld too large for 32-bit kernel",
600 (long long) size);
f57e2416
EB
601 return -E2BIG;
602 }
603
798bfe00
FZ
604 TRACE("Setting NBD socket");
605
f57e2416 606 if (ioctl(fd, NBD_SET_SOCK, (unsigned long) sioc->fd) < 0) {
798bfe00 607 int serrno = errno;
be41c100 608 error_setg(errp, "Failed to set NBD socket");
798bfe00
FZ
609 return -serrno;
610 }
611
612 TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE);
613
f57e2416 614 if (ioctl(fd, NBD_SET_BLKSIZE, (unsigned long)BDRV_SECTOR_SIZE) < 0) {
798bfe00 615 int serrno = errno;
be41c100 616 error_setg(errp, "Failed setting NBD block size");
798bfe00
FZ
617 return -serrno;
618 }
619
f57e2416
EB
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));
624 }
798bfe00 625
f57e2416 626 if (ioctl(fd, NBD_SET_SIZE_BLOCKS, sectors) < 0) {
798bfe00 627 int serrno = errno;
be41c100 628 error_setg(errp, "Failed setting size (in blocks)");
798bfe00
FZ
629 return -serrno;
630 }
631
f57e2416 632 if (ioctl(fd, NBD_SET_FLAGS, (unsigned long) flags) < 0) {
798bfe00
FZ
633 if (errno == ENOTTY) {
634 int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;
635 TRACE("Setting readonly attribute");
636
637 if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
638 int serrno = errno;
be41c100 639 error_setg(errp, "Failed setting read-only attribute");
798bfe00
FZ
640 return -serrno;
641 }
642 } else {
643 int serrno = errno;
be41c100 644 error_setg(errp, "Failed setting flags");
798bfe00
FZ
645 return -serrno;
646 }
647 }
648
649 TRACE("Negotiation ended");
650
651 return 0;
652}
653
654int nbd_client(int fd)
655{
656 int ret;
657 int serrno;
658
659 TRACE("Doing NBD loop");
660
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
665 * that case.
666 */
667 ret = 0;
668 }
669 serrno = errno;
670
671 TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
672
673 TRACE("Clearing NBD queue");
674 ioctl(fd, NBD_CLEAR_QUE);
675
676 TRACE("Clearing NBD socket");
677 ioctl(fd, NBD_CLEAR_SOCK);
678
679 errno = serrno;
680 return ret;
681}
98494e3b
EB
682
683int nbd_disconnect(int fd)
684{
685 ioctl(fd, NBD_CLEAR_QUE);
686 ioctl(fd, NBD_DISCONNECT);
687 ioctl(fd, NBD_CLEAR_SOCK);
688 return 0;
689}
690
798bfe00 691#else
be41c100
VSO
692int nbd_init(int fd, QIOChannelSocket *ioc, uint16_t flags, off_t size,
693 Error **errp)
798bfe00 694{
be41c100 695 error_setg(errp, "nbd_init is only supported on Linux");
798bfe00
FZ
696 return -ENOTSUP;
697}
698
699int nbd_client(int fd)
700{
701 return -ENOTSUP;
702}
98494e3b
EB
703int nbd_disconnect(int fd)
704{
705 return -ENOTSUP;
706}
798bfe00
FZ
707#endif
708
ed2dd912 709ssize_t nbd_send_request(QIOChannel *ioc, NBDRequest *request)
798bfe00
FZ
710{
711 uint8_t buf[NBD_REQUEST_SIZE];
798bfe00 712
7548fe31 713 TRACE("Sending request to server: "
2cb34749 714 "{ .from = %" PRIu64", .len = %" PRIu32 ", .handle = %" PRIu64
b626b51a
EB
715 ", .flags = %" PRIx16 ", .type = %" PRIu16 " }",
716 request->from, request->len, request->handle,
717 request->flags, request->type);
7548fe31 718
f6be6720 719 stl_be_p(buf, NBD_REQUEST_MAGIC);
b626b51a
EB
720 stw_be_p(buf + 4, request->flags);
721 stw_be_p(buf + 6, request->type);
f6be6720
PM
722 stq_be_p(buf + 8, request->handle);
723 stq_be_p(buf + 16, request->from);
724 stl_be_p(buf + 24, request->len);
798bfe00 725
d1fdf257 726 return nbd_write(ioc, buf, sizeof(buf), NULL);
798bfe00
FZ
727}
728
be41c100 729ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
798bfe00
FZ
730{
731 uint8_t buf[NBD_REPLY_SIZE];
732 uint32_t magic;
733 ssize_t ret;
734
d1fdf257 735 ret = nbd_read_eof(ioc, buf, sizeof(buf), errp);
ff82911c 736 if (ret <= 0) {
798bfe00
FZ
737 return ret;
738 }
739
740 if (ret != sizeof(buf)) {
be41c100 741 error_setg(errp, "read failed");
798bfe00
FZ
742 return -EINVAL;
743 }
744
745 /* Reply
746 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
747 [ 4 .. 7] error (0 == no error)
748 [ 7 .. 15] handle
749 */
750
773dce3c
PM
751 magic = ldl_be_p(buf);
752 reply->error = ldl_be_p(buf + 4);
753 reply->handle = ldq_be_p(buf + 8);
798bfe00
FZ
754
755 reply->error = nbd_errno_to_system_errno(reply->error);
756
b6f5d3b5
EB
757 if (reply->error == ESHUTDOWN) {
758 /* This works even on mingw which lacks a native ESHUTDOWN */
be41c100 759 error_setg(errp, "server shutting down");
b6f5d3b5
EB
760 return -EINVAL;
761 }
2cb34749
EB
762 TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32
763 ", handle = %" PRIu64" }",
798bfe00
FZ
764 magic, reply->error, reply->handle);
765
766 if (magic != NBD_REPLY_MAGIC) {
be41c100 767 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
798bfe00
FZ
768 return -EINVAL;
769 }
a12a712a 770 return sizeof(buf);
798bfe00
FZ
771}
772