]> git.proxmox.com Git - mirror_qemu.git/blame - nbd/client.c
trace: fix tcg tracing build breakage
[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
7d3123e1
EB
89/* Discard length bytes from channel. Return -errno on failure, or
90 * the amount of bytes consumed. */
91static ssize_t drop_sync(QIOChannel *ioc, size_t size)
92{
a5068244 93 ssize_t ret = 0;
7d3123e1
EB
94 char small[1024];
95 char *buffer;
96
2563c9c6 97 buffer = sizeof(small) >= size ? small : g_malloc(MIN(65536, size));
7d3123e1 98 while (size > 0) {
a5068244
EB
99 ssize_t count = read_sync(ioc, buffer, MIN(65536, size));
100
101 if (count <= 0) {
7d3123e1
EB
102 goto cleanup;
103 }
a5068244
EB
104 assert(count <= size);
105 size -= count;
106 ret += count;
7d3123e1 107 }
7d3123e1
EB
108
109 cleanup:
110 if (buffer != small) {
111 g_free(buffer);
112 }
113 return ret;
114}
115
c8a3a1b6
EB
116/* Send an option request.
117 *
118 * The request is for option @opt, with @data containing @len bytes of
119 * additional payload for the request (@len may be -1 to treat @data as
120 * a C string; and @data may be NULL if @len is 0).
121 * Return 0 if successful, -1 with errp set if it is impossible to
122 * continue. */
123static int nbd_send_option_request(QIOChannel *ioc, uint32_t opt,
124 uint32_t len, const char *data,
125 Error **errp)
126{
127 nbd_option req;
128 QEMU_BUILD_BUG_ON(sizeof(req) != 16);
129
130 if (len == -1) {
131 req.length = len = strlen(data);
132 }
133 TRACE("Sending option request %" PRIu32", len %" PRIu32, opt, len);
134
135 stq_be_p(&req.magic, NBD_OPTS_MAGIC);
136 stl_be_p(&req.option, opt);
137 stl_be_p(&req.length, len);
138
139 if (write_sync(ioc, &req, sizeof(req)) != sizeof(req)) {
140 error_setg(errp, "Failed to send option request header");
141 return -1;
142 }
143
144 if (len && write_sync(ioc, (char *) data, len) != len) {
145 error_setg(errp, "Failed to send option request data");
146 return -1;
147 }
148
149 return 0;
150}
151
2cdbf413
EB
152/* Send NBD_OPT_ABORT as a courtesy to let the server know that we are
153 * not going to attempt further negotiation. */
154static void nbd_send_opt_abort(QIOChannel *ioc)
155{
156 /* Technically, a compliant server is supposed to reply to us; but
157 * older servers disconnected instead. At any rate, we're allowed
158 * to disconnect without waiting for the server reply, so we don't
159 * even care if the request makes it to the server, let alone
160 * waiting around for whether the server replies. */
161 nbd_send_option_request(ioc, NBD_OPT_ABORT, 0, NULL, NULL);
162}
163
164
c8a3a1b6
EB
165/* Receive the header of an option reply, which should match the given
166 * opt. Read through the length field, but NOT the length bytes of
167 * payload. Return 0 if successful, -1 with errp set if it is
168 * impossible to continue. */
169static int nbd_receive_option_reply(QIOChannel *ioc, uint32_t opt,
170 nbd_opt_reply *reply, Error **errp)
171{
172 QEMU_BUILD_BUG_ON(sizeof(*reply) != 20);
173 if (read_sync(ioc, reply, sizeof(*reply)) != sizeof(*reply)) {
174 error_setg(errp, "failed to read option reply");
2cdbf413 175 nbd_send_opt_abort(ioc);
c8a3a1b6
EB
176 return -1;
177 }
178 be64_to_cpus(&reply->magic);
179 be32_to_cpus(&reply->option);
180 be32_to_cpus(&reply->type);
181 be32_to_cpus(&reply->length);
182
183 TRACE("Received option reply %" PRIx32", type %" PRIx32", len %" PRIu32,
184 reply->option, reply->type, reply->length);
9344e5f5 185
c8a3a1b6
EB
186 if (reply->magic != NBD_REP_MAGIC) {
187 error_setg(errp, "Unexpected option reply magic");
2cdbf413 188 nbd_send_opt_abort(ioc);
c8a3a1b6
EB
189 return -1;
190 }
191 if (reply->option != opt) {
192 error_setg(errp, "Unexpected option type %x expected %x",
193 reply->option, opt);
2cdbf413 194 nbd_send_opt_abort(ioc);
c8a3a1b6
EB
195 return -1;
196 }
197 return 0;
198}
199
200/* If reply represents success, return 1 without further action.
201 * If reply represents an error, consume the optional payload of
202 * the packet on ioc. Then return 0 for unsupported (so the client
203 * can fall back to other approaches), or -1 with errp set for other
204 * errors.
6ff58164 205 */
c8a3a1b6 206static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,
6ff58164 207 Error **errp)
9344e5f5 208{
6ff58164
AB
209 char *msg = NULL;
210 int result = -1;
211
c8a3a1b6 212 if (!(reply->type & (1 << 31))) {
6ff58164
AB
213 return 1;
214 }
215
c8a3a1b6
EB
216 if (reply->length) {
217 if (reply->length > NBD_MAX_BUFFER_SIZE) {
6ff58164
AB
218 error_setg(errp, "server's error message is too long");
219 goto cleanup;
220 }
c8a3a1b6
EB
221 msg = g_malloc(reply->length + 1);
222 if (read_sync(ioc, msg, reply->length) != reply->length) {
6ff58164
AB
223 error_setg(errp, "failed to read option error message");
224 goto cleanup;
225 }
c8a3a1b6 226 msg[reply->length] = '\0';
9344e5f5
DB
227 }
228
c8a3a1b6 229 switch (reply->type) {
9344e5f5 230 case NBD_REP_ERR_UNSUP:
2cb34749 231 TRACE("server doesn't understand request %" PRIx32
c8a3a1b6 232 ", attempting fallback", reply->option);
6ff58164
AB
233 result = 0;
234 goto cleanup;
9344e5f5 235
f95910fe 236 case NBD_REP_ERR_POLICY:
c8a3a1b6
EB
237 error_setg(errp, "Denied by server for option %" PRIx32,
238 reply->option);
f95910fe
DB
239 break;
240
9344e5f5 241 case NBD_REP_ERR_INVALID:
c8a3a1b6
EB
242 error_setg(errp, "Invalid data length for option %" PRIx32,
243 reply->option);
9344e5f5
DB
244 break;
245
b6f5d3b5
EB
246 case NBD_REP_ERR_PLATFORM:
247 error_setg(errp, "Server lacks support for option %" PRIx32,
248 reply->option);
249 break;
250
f95910fe 251 case NBD_REP_ERR_TLS_REQD:
2cb34749 252 error_setg(errp, "TLS negotiation required before option %" PRIx32,
c8a3a1b6 253 reply->option);
f95910fe
DB
254 break;
255
b6f5d3b5
EB
256 case NBD_REP_ERR_SHUTDOWN:
257 error_setg(errp, "Server shutting down before option %" PRIx32,
258 reply->option);
259 break;
260
9344e5f5 261 default:
2cb34749 262 error_setg(errp, "Unknown error code when asking for option %" PRIx32,
c8a3a1b6 263 reply->option);
9344e5f5
DB
264 break;
265 }
266
6ff58164
AB
267 if (msg) {
268 error_append_hint(errp, "%s\n", msg);
269 }
270
271 cleanup:
272 g_free(msg);
2cdbf413
EB
273 if (result < 0) {
274 nbd_send_opt_abort(ioc);
275 }
6ff58164 276 return result;
9344e5f5
DB
277}
278
75368aab
EB
279/* Process another portion of the NBD_OPT_LIST reply. Set *@match if
280 * the current reply matches @want or if the server does not support
281 * NBD_OPT_LIST, otherwise leave @match alone. Return 0 if iteration
282 * is complete, positive if more replies are expected, or negative
283 * with @errp set if an unrecoverable error occurred. */
284static int nbd_receive_list(QIOChannel *ioc, const char *want, bool *match,
285 Error **errp)
9344e5f5 286{
c8a3a1b6 287 nbd_opt_reply reply;
9344e5f5
DB
288 uint32_t len;
289 uint32_t namelen;
75368aab 290 char name[NBD_MAX_NAME_SIZE + 1];
6ff58164 291 int error;
9344e5f5 292
c8a3a1b6 293 if (nbd_receive_option_reply(ioc, NBD_OPT_LIST, &reply, errp) < 0) {
9344e5f5
DB
294 return -1;
295 }
c8a3a1b6 296 error = nbd_handle_reply_err(ioc, &reply, errp);
6ff58164 297 if (error <= 0) {
75368aab
EB
298 /* The server did not support NBD_OPT_LIST, so set *match on
299 * the assumption that any name will be accepted. */
300 *match = true;
6ff58164 301 return error;
9344e5f5 302 }
c8a3a1b6 303 len = reply.length;
9344e5f5 304
c8a3a1b6 305 if (reply.type == NBD_REP_ACK) {
9344e5f5
DB
306 if (len != 0) {
307 error_setg(errp, "length too long for option end");
2cdbf413 308 nbd_send_opt_abort(ioc);
9344e5f5
DB
309 return -1;
310 }
75368aab
EB
311 return 0;
312 } else if (reply.type != NBD_REP_SERVER) {
313 error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",
314 reply.type, NBD_REP_SERVER);
315 nbd_send_opt_abort(ioc);
316 return -1;
317 }
9344e5f5 318
75368aab
EB
319 if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {
320 error_setg(errp, "incorrect option length %" PRIu32, len);
321 nbd_send_opt_abort(ioc);
322 return -1;
323 }
324 if (read_sync(ioc, &namelen, sizeof(namelen)) != sizeof(namelen)) {
325 error_setg(errp, "failed to read option name length");
326 nbd_send_opt_abort(ioc);
327 return -1;
328 }
329 namelen = be32_to_cpu(namelen);
330 len -= sizeof(namelen);
331 if (len < namelen) {
332 error_setg(errp, "incorrect option name length");
333 nbd_send_opt_abort(ioc);
334 return -1;
335 }
336 if (namelen != strlen(want)) {
7d3123e1 337 if (drop_sync(ioc, len) != len) {
75368aab 338 error_setg(errp, "failed to skip export name with wrong length");
7d3123e1
EB
339 nbd_send_opt_abort(ioc);
340 return -1;
200650d4 341 }
75368aab
EB
342 return 1;
343 }
344
345 assert(namelen < sizeof(name));
346 if (read_sync(ioc, name, namelen) != namelen) {
347 error_setg(errp, "failed to read export name");
348 nbd_send_opt_abort(ioc);
349 return -1;
350 }
351 name[namelen] = '\0';
352 len -= namelen;
353 if (drop_sync(ioc, len) != len) {
354 error_setg(errp, "failed to read export description");
2cdbf413 355 nbd_send_opt_abort(ioc);
9344e5f5
DB
356 return -1;
357 }
75368aab
EB
358 if (!strcmp(name, want)) {
359 *match = true;
360 }
9344e5f5
DB
361 return 1;
362}
363
364
75368aab 365/* Return -1 on failure, 0 if wantname is an available export. */
9344e5f5
DB
366static int nbd_receive_query_exports(QIOChannel *ioc,
367 const char *wantname,
368 Error **errp)
369{
9344e5f5
DB
370 bool foundExport = false;
371
75368aab 372 TRACE("Querying export list for '%s'", wantname);
c8a3a1b6 373 if (nbd_send_option_request(ioc, NBD_OPT_LIST, 0, NULL, errp) < 0) {
9344e5f5
DB
374 return -1;
375 }
376
377 TRACE("Reading available export names");
378 while (1) {
75368aab 379 int ret = nbd_receive_list(ioc, wantname, &foundExport, errp);
9344e5f5
DB
380
381 if (ret < 0) {
75368aab 382 /* Server gave unexpected reply */
9344e5f5 383 return -1;
75368aab
EB
384 } else if (ret == 0) {
385 /* Done iterating. */
386 if (!foundExport) {
387 error_setg(errp, "No export with name '%s' available",
388 wantname);
389 nbd_send_opt_abort(ioc);
390 return -1;
391 }
392 TRACE("Found desired export name '%s'", wantname);
393 return 0;
9344e5f5 394 }
9344e5f5 395 }
9344e5f5
DB
396}
397
f95910fe
DB
398static QIOChannel *nbd_receive_starttls(QIOChannel *ioc,
399 QCryptoTLSCreds *tlscreds,
400 const char *hostname, Error **errp)
401{
c8a3a1b6 402 nbd_opt_reply reply;
f95910fe
DB
403 QIOChannelTLS *tioc;
404 struct NBDTLSHandshakeData data = { 0 };
405
406 TRACE("Requesting TLS from server");
c8a3a1b6 407 if (nbd_send_option_request(ioc, NBD_OPT_STARTTLS, 0, NULL, errp) < 0) {
f95910fe
DB
408 return NULL;
409 }
410
411 TRACE("Getting TLS reply from server");
c8a3a1b6 412 if (nbd_receive_option_reply(ioc, NBD_OPT_STARTTLS, &reply, errp) < 0) {
f95910fe
DB
413 return NULL;
414 }
c8a3a1b6
EB
415
416 if (reply.type != NBD_REP_ACK) {
2cb34749 417 error_setg(errp, "Server rejected request to start TLS %" PRIx32,
c8a3a1b6 418 reply.type);
2cdbf413 419 nbd_send_opt_abort(ioc);
f95910fe
DB
420 return NULL;
421 }
422
c8a3a1b6 423 if (reply.length != 0) {
2cb34749 424 error_setg(errp, "Start TLS response was not zero %" PRIu32,
c8a3a1b6 425 reply.length);
2cdbf413 426 nbd_send_opt_abort(ioc);
f95910fe
DB
427 return NULL;
428 }
429
430 TRACE("TLS request approved, setting up TLS");
431 tioc = qio_channel_tls_new_client(ioc, tlscreds, hostname, errp);
432 if (!tioc) {
433 return NULL;
434 }
0d73f725 435 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-client-tls");
f95910fe 436 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
2cb34749 437 TRACE("Starting TLS handshake");
f95910fe
DB
438 qio_channel_tls_handshake(tioc,
439 nbd_tls_handshake,
440 &data,
441 NULL);
442
443 if (!data.complete) {
444 g_main_loop_run(data.loop);
445 }
446 g_main_loop_unref(data.loop);
447 if (data.error) {
448 error_propagate(errp, data.error);
449 object_unref(OBJECT(tioc));
450 return NULL;
451 }
452
453 return QIO_CHANNEL(tioc);
454}
455
456
7423f417 457int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint16_t *flags,
f95910fe
DB
458 QCryptoTLSCreds *tlscreds, const char *hostname,
459 QIOChannel **outioc,
798bfe00
FZ
460 off_t *size, Error **errp)
461{
462 char buf[256];
463 uint64_t magic, s;
798bfe00 464 int rc;
c203c59a 465 bool zeroes = true;
798bfe00 466
f95910fe
DB
467 TRACE("Receiving negotiation tlscreds=%p hostname=%s.",
468 tlscreds, hostname ? hostname : "<null>");
798bfe00
FZ
469
470 rc = -EINVAL;
471
f95910fe
DB
472 if (outioc) {
473 *outioc = NULL;
474 }
475 if (tlscreds && !outioc) {
476 error_setg(errp, "Output I/O channel required for TLS");
477 goto fail;
478 }
479
1c778ef7 480 if (read_sync(ioc, buf, 8) != 8) {
798bfe00
FZ
481 error_setg(errp, "Failed to read data");
482 goto fail;
483 }
484
485 buf[8] = '\0';
486 if (strlen(buf) == 0) {
487 error_setg(errp, "Server connection closed unexpectedly");
488 goto fail;
489 }
490
491 TRACE("Magic is %c%c%c%c%c%c%c%c",
492 qemu_isprint(buf[0]) ? buf[0] : '.',
493 qemu_isprint(buf[1]) ? buf[1] : '.',
494 qemu_isprint(buf[2]) ? buf[2] : '.',
495 qemu_isprint(buf[3]) ? buf[3] : '.',
496 qemu_isprint(buf[4]) ? buf[4] : '.',
497 qemu_isprint(buf[5]) ? buf[5] : '.',
498 qemu_isprint(buf[6]) ? buf[6] : '.',
499 qemu_isprint(buf[7]) ? buf[7] : '.');
500
501 if (memcmp(buf, "NBDMAGIC", 8) != 0) {
502 error_setg(errp, "Invalid magic received");
503 goto fail;
504 }
505
1c778ef7 506 if (read_sync(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
798bfe00
FZ
507 error_setg(errp, "Failed to read magic");
508 goto fail;
509 }
510 magic = be64_to_cpu(magic);
511 TRACE("Magic is 0x%" PRIx64, magic);
512
f72d705f 513 if (magic == NBD_OPTS_MAGIC) {
e2a9d9a3 514 uint32_t clientflags = 0;
e2a9d9a3 515 uint16_t globalflags;
9344e5f5 516 bool fixedNewStyle = false;
798bfe00 517
e2a9d9a3
DB
518 if (read_sync(ioc, &globalflags, sizeof(globalflags)) !=
519 sizeof(globalflags)) {
798bfe00
FZ
520 error_setg(errp, "Failed to read server flags");
521 goto fail;
522 }
9344e5f5 523 globalflags = be16_to_cpu(globalflags);
2cb34749 524 TRACE("Global flags are %" PRIx32, globalflags);
e2a9d9a3 525 if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {
9344e5f5 526 fixedNewStyle = true;
e2a9d9a3
DB
527 TRACE("Server supports fixed new style");
528 clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;
529 }
c203c59a
EB
530 if (globalflags & NBD_FLAG_NO_ZEROES) {
531 zeroes = false;
532 TRACE("Server supports no zeroes");
533 clientflags |= NBD_FLAG_C_NO_ZEROES;
534 }
e2a9d9a3 535 /* client requested flags */
9344e5f5 536 clientflags = cpu_to_be32(clientflags);
e2a9d9a3
DB
537 if (write_sync(ioc, &clientflags, sizeof(clientflags)) !=
538 sizeof(clientflags)) {
539 error_setg(errp, "Failed to send clientflags field");
798bfe00
FZ
540 goto fail;
541 }
f95910fe
DB
542 if (tlscreds) {
543 if (fixedNewStyle) {
544 *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);
545 if (!*outioc) {
546 goto fail;
547 }
548 ioc = *outioc;
549 } else {
550 error_setg(errp, "Server does not support STARTTLS");
551 goto fail;
552 }
553 }
f72d705f 554 if (!name) {
69b49502
DB
555 TRACE("Using default NBD export name \"\"");
556 name = "";
f72d705f 557 }
9344e5f5
DB
558 if (fixedNewStyle) {
559 /* Check our desired export is present in the
560 * server export list. Since NBD_OPT_EXPORT_NAME
561 * cannot return an error message, running this
562 * query gives us good error reporting if the
563 * server required TLS
564 */
565 if (nbd_receive_query_exports(ioc, name, errp) < 0) {
566 goto fail;
567 }
568 }
c8a3a1b6
EB
569 /* write the export name request */
570 if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,
571 errp) < 0) {
798bfe00
FZ
572 goto fail;
573 }
f72d705f 574
c8a3a1b6 575 /* Read the response */
f72d705f
DB
576 if (read_sync(ioc, &s, sizeof(s)) != sizeof(s)) {
577 error_setg(errp, "Failed to read export length");
798bfe00
FZ
578 goto fail;
579 }
f72d705f 580 *size = be64_to_cpu(s);
798bfe00 581
7423f417 582 if (read_sync(ioc, flags, sizeof(*flags)) != sizeof(*flags)) {
f72d705f
DB
583 error_setg(errp, "Failed to read export flags");
584 goto fail;
585 }
7423f417 586 be16_to_cpus(flags);
f72d705f 587 } else if (magic == NBD_CLIENT_MAGIC) {
7423f417
EB
588 uint32_t oldflags;
589
f72d705f
DB
590 if (name) {
591 error_setg(errp, "Server does not support export names");
592 goto fail;
593 }
f95910fe
DB
594 if (tlscreds) {
595 error_setg(errp, "Server does not support STARTTLS");
596 goto fail;
597 }
f72d705f
DB
598
599 if (read_sync(ioc, &s, sizeof(s)) != sizeof(s)) {
600 error_setg(errp, "Failed to read export length");
601 goto fail;
602 }
603 *size = be64_to_cpu(s);
604 TRACE("Size is %" PRIu64, *size);
798bfe00 605
7423f417 606 if (read_sync(ioc, &oldflags, sizeof(oldflags)) != sizeof(oldflags)) {
798bfe00
FZ
607 error_setg(errp, "Failed to read export flags");
608 goto fail;
609 }
7423f417
EB
610 be32_to_cpus(&oldflags);
611 if (oldflags & ~0xffff) {
612 error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);
613 goto fail;
614 }
615 *flags = oldflags;
798bfe00 616 } else {
f72d705f
DB
617 error_setg(errp, "Bad magic received");
618 goto fail;
798bfe00 619 }
f72d705f 620
7423f417 621 TRACE("Size is %" PRIu64 ", export flags %" PRIx16, *size, *flags);
c203c59a 622 if (zeroes && drop_sync(ioc, 124) != 124) {
798bfe00
FZ
623 error_setg(errp, "Failed to read reserved block");
624 goto fail;
625 }
626 rc = 0;
627
628fail:
629 return rc;
630}
631
632#ifdef __linux__
7423f417 633int nbd_init(int fd, QIOChannelSocket *sioc, uint16_t flags, off_t size)
798bfe00 634{
f57e2416
EB
635 unsigned long sectors = size / BDRV_SECTOR_SIZE;
636 if (size / BDRV_SECTOR_SIZE != sectors) {
637 LOG("Export size %lld too large for 32-bit kernel", (long long) size);
638 return -E2BIG;
639 }
640
798bfe00
FZ
641 TRACE("Setting NBD socket");
642
f57e2416 643 if (ioctl(fd, NBD_SET_SOCK, (unsigned long) sioc->fd) < 0) {
798bfe00
FZ
644 int serrno = errno;
645 LOG("Failed to set NBD socket");
646 return -serrno;
647 }
648
649 TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE);
650
f57e2416 651 if (ioctl(fd, NBD_SET_BLKSIZE, (unsigned long)BDRV_SECTOR_SIZE) < 0) {
798bfe00
FZ
652 int serrno = errno;
653 LOG("Failed setting NBD block size");
654 return -serrno;
655 }
656
f57e2416
EB
657 TRACE("Setting size to %lu block(s)", sectors);
658 if (size % BDRV_SECTOR_SIZE) {
659 TRACE("Ignoring trailing %d bytes of export",
660 (int) (size % BDRV_SECTOR_SIZE));
661 }
798bfe00 662
f57e2416 663 if (ioctl(fd, NBD_SET_SIZE_BLOCKS, sectors) < 0) {
798bfe00
FZ
664 int serrno = errno;
665 LOG("Failed setting size (in blocks)");
666 return -serrno;
667 }
668
f57e2416 669 if (ioctl(fd, NBD_SET_FLAGS, (unsigned long) flags) < 0) {
798bfe00
FZ
670 if (errno == ENOTTY) {
671 int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;
672 TRACE("Setting readonly attribute");
673
674 if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
675 int serrno = errno;
676 LOG("Failed setting read-only attribute");
677 return -serrno;
678 }
679 } else {
680 int serrno = errno;
681 LOG("Failed setting flags");
682 return -serrno;
683 }
684 }
685
686 TRACE("Negotiation ended");
687
688 return 0;
689}
690
691int nbd_client(int fd)
692{
693 int ret;
694 int serrno;
695
696 TRACE("Doing NBD loop");
697
698 ret = ioctl(fd, NBD_DO_IT);
699 if (ret < 0 && errno == EPIPE) {
700 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
701 * the socket via NBD_DISCONNECT. We do not want to return 1 in
702 * that case.
703 */
704 ret = 0;
705 }
706 serrno = errno;
707
708 TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
709
710 TRACE("Clearing NBD queue");
711 ioctl(fd, NBD_CLEAR_QUE);
712
713 TRACE("Clearing NBD socket");
714 ioctl(fd, NBD_CLEAR_SOCK);
715
716 errno = serrno;
717 return ret;
718}
98494e3b
EB
719
720int nbd_disconnect(int fd)
721{
722 ioctl(fd, NBD_CLEAR_QUE);
723 ioctl(fd, NBD_DISCONNECT);
724 ioctl(fd, NBD_CLEAR_SOCK);
725 return 0;
726}
727
798bfe00 728#else
7423f417 729int nbd_init(int fd, QIOChannelSocket *ioc, uint16_t flags, off_t size)
798bfe00
FZ
730{
731 return -ENOTSUP;
732}
733
734int nbd_client(int fd)
735{
736 return -ENOTSUP;
737}
98494e3b
EB
738int nbd_disconnect(int fd)
739{
740 return -ENOTSUP;
741}
798bfe00
FZ
742#endif
743
ed2dd912 744ssize_t nbd_send_request(QIOChannel *ioc, NBDRequest *request)
798bfe00
FZ
745{
746 uint8_t buf[NBD_REQUEST_SIZE];
747 ssize_t ret;
748
7548fe31 749 TRACE("Sending request to server: "
2cb34749 750 "{ .from = %" PRIu64", .len = %" PRIu32 ", .handle = %" PRIu64
b626b51a
EB
751 ", .flags = %" PRIx16 ", .type = %" PRIu16 " }",
752 request->from, request->len, request->handle,
753 request->flags, request->type);
7548fe31 754
f6be6720 755 stl_be_p(buf, NBD_REQUEST_MAGIC);
b626b51a
EB
756 stw_be_p(buf + 4, request->flags);
757 stw_be_p(buf + 6, request->type);
f6be6720
PM
758 stq_be_p(buf + 8, request->handle);
759 stq_be_p(buf + 16, request->from);
760 stl_be_p(buf + 24, request->len);
798bfe00 761
1c778ef7 762 ret = write_sync(ioc, buf, sizeof(buf));
798bfe00
FZ
763 if (ret < 0) {
764 return ret;
765 }
766
767 if (ret != sizeof(buf)) {
768 LOG("writing to socket failed");
769 return -EINVAL;
770 }
771 return 0;
772}
773
ed2dd912 774ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply)
798bfe00
FZ
775{
776 uint8_t buf[NBD_REPLY_SIZE];
777 uint32_t magic;
778 ssize_t ret;
779
1c778ef7 780 ret = read_sync(ioc, buf, sizeof(buf));
ff82911c 781 if (ret <= 0) {
798bfe00
FZ
782 return ret;
783 }
784
785 if (ret != sizeof(buf)) {
786 LOG("read failed");
787 return -EINVAL;
788 }
789
790 /* Reply
791 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
792 [ 4 .. 7] error (0 == no error)
793 [ 7 .. 15] handle
794 */
795
773dce3c
PM
796 magic = ldl_be_p(buf);
797 reply->error = ldl_be_p(buf + 4);
798 reply->handle = ldq_be_p(buf + 8);
798bfe00
FZ
799
800 reply->error = nbd_errno_to_system_errno(reply->error);
801
b6f5d3b5
EB
802 if (reply->error == ESHUTDOWN) {
803 /* This works even on mingw which lacks a native ESHUTDOWN */
804 LOG("server shutting down");
805 return -EINVAL;
806 }
2cb34749
EB
807 TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32
808 ", handle = %" PRIu64" }",
798bfe00
FZ
809 magic, reply->error, reply->handle);
810
811 if (magic != NBD_REPLY_MAGIC) {
2cb34749 812 LOG("invalid magic (got 0x%" PRIx32 ")", magic);
798bfe00
FZ
813 return -EINVAL;
814 }
a12a712a 815 return sizeof(buf);
798bfe00
FZ
816}
817