]> git.proxmox.com Git - mirror_qemu.git/blame - nbd/server.c
nbd/server: refactor NBDExportMetaContexts
[mirror_qemu.git] / nbd / server.c
CommitLineData
75818250 1/*
a16a7907 2 * Copyright (C) 2016-2018 Red Hat, Inc.
7a5ca864
FB
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 *
798bfe00 5 * Network Block Device Server Side
7a5ca864
FB
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
8167ee88 17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
75818250 18 */
7a5ca864 19
d38ea87a 20#include "qemu/osdep.h"
da34e65c 21#include "qapi/error.h"
9588463e 22#include "trace.h"
798bfe00 23#include "nbd-internal.h"
ca441480 24
e7b1948d
VSO
25#define NBD_META_ID_BASE_ALLOCATION 0
26
ca441480
PB
27static int system_errno_to_nbd_errno(int err)
28{
29 switch (err) {
30 case 0:
31 return NBD_SUCCESS;
32 case EPERM:
c0301fcc 33 case EROFS:
ca441480
PB
34 return NBD_EPERM;
35 case EIO:
36 return NBD_EIO;
37 case ENOMEM:
38 return NBD_ENOMEM;
39#ifdef EDQUOT
40 case EDQUOT:
41#endif
42 case EFBIG:
43 case ENOSPC:
44 return NBD_ENOSPC;
bae245d1
EB
45 case EOVERFLOW:
46 return NBD_EOVERFLOW;
b6f5d3b5
EB
47 case ESHUTDOWN:
48 return NBD_ESHUTDOWN;
ca441480
PB
49 case EINVAL:
50 default:
51 return NBD_EINVAL;
52 }
53}
54
9a304d29
PB
55/* Definitions for opaque data types */
56
315f78ab 57typedef struct NBDRequestData NBDRequestData;
9a304d29 58
315f78ab
EB
59struct NBDRequestData {
60 QSIMPLEQ_ENTRY(NBDRequestData) entry;
9a304d29
PB
61 NBDClient *client;
62 uint8_t *data;
29b6c3b3 63 bool complete;
9a304d29
PB
64};
65
66struct NBDExport {
2c8d9f06 67 int refcount;
0ddf08db
PB
68 void (*close)(NBDExport *exp);
69
aadf99a7 70 BlockBackend *blk;
ee0a19ec 71 char *name;
b1a75b33 72 char *description;
9a304d29
PB
73 off_t dev_offset;
74 off_t size;
7423f417 75 uint16_t nbdflags;
4b9441f6 76 QTAILQ_HEAD(, NBDClient) clients;
ee0a19ec 77 QTAILQ_ENTRY(NBDExport) next;
958c717d
HR
78
79 AioContext *ctx;
741cc431 80
cd7fca95 81 BlockBackend *eject_notifier_blk;
741cc431 82 Notifier eject_notifier;
9a304d29
PB
83};
84
ee0a19ec
PB
85static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
86
e7b1948d
VSO
87/* NBDExportMetaContexts represents a list of contexts to be exported,
88 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
89 * NBD_OPT_LIST_META_CONTEXT. */
90typedef struct NBDExportMetaContexts {
af736e54 91 NBDExport *exp;
e7b1948d
VSO
92 bool valid; /* means that negotiation of the option finished without
93 errors */
94 bool base_allocation; /* export base:allocation context (block status) */
95} NBDExportMetaContexts;
96
9a304d29
PB
97struct NBDClient {
98 int refcount;
0c9390d9 99 void (*close_fn)(NBDClient *client, bool negotiated);
9a304d29
PB
100
101 NBDExport *exp;
f95910fe
DB
102 QCryptoTLSCreds *tlscreds;
103 char *tlsaclname;
1c778ef7
DB
104 QIOChannelSocket *sioc; /* The underlying data channel */
105 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
9a304d29
PB
106
107 Coroutine *recv_coroutine;
108
109 CoMutex send_lock;
110 Coroutine *send_coroutine;
111
4b9441f6 112 QTAILQ_ENTRY(NBDClient) next;
9a304d29 113 int nb_requests;
ff2b68aa 114 bool closing;
5c54e7fa
VSO
115
116 bool structured_reply;
e7b1948d 117 NBDExportMetaContexts export_meta;
9a304d29 118
0cfae925
VSO
119 uint32_t opt; /* Current option being negotiated */
120 uint32_t optlen; /* remaining length of data in ioc for the option being
121 negotiated now */
122};
7a5ca864 123
ff82911c 124static void nbd_client_receive_next_request(NBDClient *client);
958c717d 125
6b8c01e7 126/* Basic flow for negotiation
7a5ca864
FB
127
128 Server Client
7a5ca864 129 Negotiate
6b8c01e7
PB
130
131 or
132
133 Server Client
134 Negotiate #1
135 Option
136 Negotiate #2
137
138 ----
139
140 followed by
141
142 Server Client
7a5ca864
FB
143 Request
144 Response
145 Request
146 Response
147 ...
148 ...
149 Request (type == 2)
6b8c01e7 150
7a5ca864
FB
151*/
152
1d17922a
VSO
153static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
154 uint32_t type, uint32_t length)
155{
156 stq_be_p(&rep->magic, NBD_REP_MAGIC);
157 stl_be_p(&rep->option, option);
158 stl_be_p(&rep->type, type);
159 stl_be_p(&rep->length, length);
160}
161
526e5c65
EB
162/* Send a reply header, including length, but no payload.
163 * Return -errno on error, 0 on success. */
0cfae925
VSO
164static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
165 uint32_t len, Error **errp)
6b8c01e7 166{
1d17922a 167 NBDOptionReply rep;
6b8c01e7 168
1d17922a 169 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
3736cc5b 170 type, nbd_rep_lookup(type), len);
f95910fe 171
f37708f6 172 assert(len < NBD_MAX_BUFFER_SIZE);
2fd2c840 173
1d17922a
VSO
174 set_be_option_rep(&rep, client->opt, type, len);
175 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
f5076b5a 176}
6b8c01e7 177
526e5c65
EB
178/* Send a reply header with default 0 length.
179 * Return -errno on error, 0 on success. */
0cfae925 180static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
2fd2c840 181 Error **errp)
526e5c65 182{
0cfae925 183 return nbd_negotiate_send_rep_len(client, type, 0, errp);
526e5c65
EB
184}
185
36683283
EB
186/* Send an error reply.
187 * Return -errno on error, 0 on success. */
41f5dfaf
EB
188static int GCC_FMT_ATTR(4, 0)
189nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
190 Error **errp, const char *fmt, va_list va)
36683283 191{
36683283
EB
192 char *msg;
193 int ret;
194 size_t len;
195
36683283 196 msg = g_strdup_vprintf(fmt, va);
36683283
EB
197 len = strlen(msg);
198 assert(len < 4096);
9588463e 199 trace_nbd_negotiate_send_rep_err(msg);
0cfae925 200 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
36683283
EB
201 if (ret < 0) {
202 goto out;
203 }
0cfae925 204 if (nbd_write(client->ioc, msg, len, errp) < 0) {
2fd2c840 205 error_prepend(errp, "write failed (error message): ");
36683283
EB
206 ret = -EIO;
207 } else {
208 ret = 0;
209 }
2fd2c840 210
36683283
EB
211out:
212 g_free(msg);
213 return ret;
214}
215
41f5dfaf
EB
216/* Send an error reply.
217 * Return -errno on error, 0 on success. */
218static int GCC_FMT_ATTR(4, 5)
219nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
220 Error **errp, const char *fmt, ...)
221{
222 va_list va;
223 int ret;
224
225 va_start(va, fmt);
226 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
227 va_end(va);
228 return ret;
229}
230
894e0280
EB
231/* Drop remainder of the current option, and send a reply with the
232 * given error type and message. Return -errno on read or write
233 * failure; or 0 if connection is still live. */
2e425fd5
VSO
234static int GCC_FMT_ATTR(4, 0)
235nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
236 const char *fmt, va_list va)
894e0280
EB
237{
238 int ret = nbd_drop(client->ioc, client->optlen, errp);
894e0280
EB
239
240 client->optlen = 0;
241 if (!ret) {
894e0280 242 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
894e0280
EB
243 }
244 return ret;
245}
246
2e425fd5
VSO
247static int GCC_FMT_ATTR(4, 5)
248nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
249 const char *fmt, ...)
250{
251 int ret;
252 va_list va;
253
254 va_start(va, fmt);
255 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
256 va_end(va);
257
258 return ret;
259}
260
261static int GCC_FMT_ATTR(3, 4)
262nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
263{
264 int ret;
265 va_list va;
266
267 va_start(va, fmt);
268 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
269 va_end(va);
270
271 return ret;
272}
273
894e0280
EB
274/* Read size bytes from the unparsed payload of the current option.
275 * Return -errno on I/O error, 0 if option was completely handled by
276 * sending a reply about inconsistent lengths, or 1 on success. */
277static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
278 Error **errp)
279{
280 if (size > client->optlen) {
2e425fd5
VSO
281 return nbd_opt_invalid(client, errp,
282 "Inconsistent lengths in option %s",
283 nbd_opt_lookup(client->opt));
894e0280
EB
284 }
285 client->optlen -= size;
286 return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1;
287}
288
e7b1948d
VSO
289/* Drop size bytes from the unparsed payload of the current option.
290 * Return -errno on I/O error, 0 if option was completely handled by
291 * sending a reply about inconsistent lengths, or 1 on success. */
292static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
293{
294 if (size > client->optlen) {
295 return nbd_opt_invalid(client, errp,
296 "Inconsistent lengths in option %s",
297 nbd_opt_lookup(client->opt));
298 }
299 client->optlen -= size;
300 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
301}
302
12296459
VSO
303/* nbd_opt_read_name
304 *
305 * Read a string with the format:
306 * uint32_t len (<= NBD_MAX_NAME_SIZE)
307 * len bytes string (not 0-terminated)
308 *
309 * @name should be enough to store NBD_MAX_NAME_SIZE+1.
310 * If @length is non-null, it will be set to the actual string length.
311 *
312 * Return -errno on I/O error, 0 if option was completely handled by
313 * sending a reply about inconsistent lengths, or 1 on success.
314 */
315static int nbd_opt_read_name(NBDClient *client, char *name, uint32_t *length,
316 Error **errp)
317{
318 int ret;
319 uint32_t len;
320
321 ret = nbd_opt_read(client, &len, sizeof(len), errp);
322 if (ret <= 0) {
323 return ret;
324 }
325 cpu_to_be32s(&len);
326
327 if (len > NBD_MAX_NAME_SIZE) {
328 return nbd_opt_invalid(client, errp,
329 "Invalid name length: %" PRIu32, len);
330 }
331
332 ret = nbd_opt_read(client, name, len, errp);
333 if (ret <= 0) {
334 return ret;
335 }
336 name[len] = '\0';
337
338 if (length) {
339 *length = len;
340 }
341
342 return 1;
343}
344
526e5c65
EB
345/* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
346 * Return -errno on error, 0 on success. */
0cfae925 347static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
2fd2c840 348 Error **errp)
32d7d2e0 349{
b1a75b33 350 size_t name_len, desc_len;
526e5c65 351 uint32_t len;
b1a75b33
EB
352 const char *name = exp->name ? exp->name : "";
353 const char *desc = exp->description ? exp->description : "";
0cfae925 354 QIOChannel *ioc = client->ioc;
2e5c9ad6 355 int ret;
32d7d2e0 356
9588463e 357 trace_nbd_negotiate_send_rep_list(name, desc);
b1a75b33
EB
358 name_len = strlen(name);
359 desc_len = strlen(desc);
526e5c65 360 len = name_len + desc_len + sizeof(len);
0cfae925 361 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
2e5c9ad6
VSO
362 if (ret < 0) {
363 return ret;
32d7d2e0 364 }
526e5c65 365
32d7d2e0 366 len = cpu_to_be32(name_len);
2fd2c840
VSO
367 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
368 error_prepend(errp, "write failed (name length): ");
b1a75b33
EB
369 return -EINVAL;
370 }
2fd2c840
VSO
371
372 if (nbd_write(ioc, name, name_len, errp) < 0) {
373 error_prepend(errp, "write failed (name buffer): ");
32d7d2e0
HB
374 return -EINVAL;
375 }
2fd2c840
VSO
376
377 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
378 error_prepend(errp, "write failed (description buffer): ");
32d7d2e0
HB
379 return -EINVAL;
380 }
2fd2c840 381
32d7d2e0
HB
382 return 0;
383}
384
526e5c65
EB
385/* Process the NBD_OPT_LIST command, with a potential series of replies.
386 * Return -errno on error, 0 on success. */
e68c35cf 387static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
32d7d2e0 388{
32d7d2e0 389 NBDExport *exp;
0cfae925 390 assert(client->opt == NBD_OPT_LIST);
32d7d2e0 391
32d7d2e0
HB
392 /* For each export, send a NBD_REP_SERVER reply. */
393 QTAILQ_FOREACH(exp, &exports, next) {
0cfae925 394 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
32d7d2e0
HB
395 return -EINVAL;
396 }
397 }
398 /* Finish with a NBD_REP_ACK. */
0cfae925 399 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
32d7d2e0
HB
400}
401
af736e54 402static void nbd_check_meta_export(NBDClient *client)
e7b1948d 403{
af736e54 404 client->export_meta.valid &= client->exp == client->export_meta.exp;
e7b1948d
VSO
405}
406
f37708f6
EB
407/* Send a reply to NBD_OPT_EXPORT_NAME.
408 * Return -errno on error, 0 on success. */
0cfae925 409static int nbd_negotiate_handle_export_name(NBDClient *client,
23e099c3 410 uint16_t myflags, bool no_zeroes,
2fd2c840 411 Error **errp)
f5076b5a 412{
943cec86 413 char name[NBD_MAX_NAME_SIZE + 1];
5f66d060 414 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
23e099c3
EB
415 size_t len;
416 int ret;
6b8c01e7 417
f5076b5a
HB
418 /* Client sends:
419 [20 .. xx] export name (length bytes)
5f66d060
EB
420 Server replies:
421 [ 0 .. 7] size
422 [ 8 .. 9] export flags
423 [10 .. 133] reserved (0) [unless no_zeroes]
f5076b5a 424 */
9588463e 425 trace_nbd_negotiate_handle_export_name();
0cfae925 426 if (client->optlen >= sizeof(name)) {
2fd2c840 427 error_setg(errp, "Bad length received");
d9faeed8 428 return -EINVAL;
6b8c01e7 429 }
0cfae925 430 if (nbd_read(client->ioc, name, client->optlen, errp) < 0) {
2fd2c840 431 error_prepend(errp, "read failed: ");
32f158a6 432 return -EIO;
6b8c01e7 433 }
0cfae925
VSO
434 name[client->optlen] = '\0';
435 client->optlen = 0;
6b8c01e7 436
9588463e 437 trace_nbd_negotiate_handle_export_name_request(name);
9344e5f5 438
6b8c01e7
PB
439 client->exp = nbd_export_find(name);
440 if (!client->exp) {
2fd2c840 441 error_setg(errp, "export not found");
d9faeed8 442 return -EINVAL;
6b8c01e7
PB
443 }
444
23e099c3
EB
445 trace_nbd_negotiate_new_style_size_flags(client->exp->size,
446 client->exp->nbdflags | myflags);
447 stq_be_p(buf, client->exp->size);
448 stw_be_p(buf + 8, client->exp->nbdflags | myflags);
449 len = no_zeroes ? 10 : sizeof(buf);
450 ret = nbd_write(client->ioc, buf, len, errp);
451 if (ret < 0) {
452 error_prepend(errp, "write failed: ");
453 return ret;
454 }
455
6b8c01e7
PB
456 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
457 nbd_export_get(client->exp);
af736e54 458 nbd_check_meta_export(client);
d9faeed8
VSO
459
460 return 0;
6b8c01e7
PB
461}
462
f37708f6
EB
463/* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
464 * The buffer does NOT include the info type prefix.
465 * Return -errno on error, 0 if ready to send more. */
0cfae925 466static int nbd_negotiate_send_info(NBDClient *client,
f37708f6
EB
467 uint16_t info, uint32_t length, void *buf,
468 Error **errp)
469{
470 int rc;
471
472 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
0cfae925 473 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
f37708f6
EB
474 sizeof(info) + length, errp);
475 if (rc < 0) {
476 return rc;
477 }
478 cpu_to_be16s(&info);
479 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
480 return -EIO;
481 }
482 if (nbd_write(client->ioc, buf, length, errp) < 0) {
483 return -EIO;
484 }
485 return 0;
486}
487
a16a7907
EB
488/* nbd_reject_length: Handle any unexpected payload.
489 * @fatal requests that we quit talking to the client, even if we are able
490 * to successfully send an error reply.
491 * Return:
492 * -errno transmission error occurred or @fatal was requested, errp is set
493 * 0 error message successfully sent to client, errp is not set
494 */
0cfae925 495static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
a16a7907
EB
496{
497 int ret;
498
0cfae925 499 assert(client->optlen);
2e425fd5
VSO
500 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
501 nbd_opt_lookup(client->opt));
a16a7907 502 if (fatal && !ret) {
894e0280 503 error_setg(errp, "option '%s' has unexpected length",
0cfae925 504 nbd_opt_lookup(client->opt));
a16a7907
EB
505 return -EINVAL;
506 }
507 return ret;
508}
509
f37708f6
EB
510/* Handle NBD_OPT_INFO and NBD_OPT_GO.
511 * Return -errno on error, 0 if ready for next option, and 1 to move
512 * into transmission phase. */
0cfae925 513static int nbd_negotiate_handle_info(NBDClient *client, uint16_t myflags,
f37708f6
EB
514 Error **errp)
515{
516 int rc;
517 char name[NBD_MAX_NAME_SIZE + 1];
518 NBDExport *exp;
519 uint16_t requests;
520 uint16_t request;
521 uint32_t namelen;
522 bool sendname = false;
0c1d50bd
EB
523 bool blocksize = false;
524 uint32_t sizes[3];
f37708f6 525 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
f37708f6
EB
526
527 /* Client sends:
528 4 bytes: L, name length (can be 0)
529 L bytes: export name
530 2 bytes: N, number of requests (can be 0)
531 N * 2 bytes: N requests
532 */
12296459 533 rc = nbd_opt_read_name(client, name, &namelen, errp);
894e0280
EB
534 if (rc <= 0) {
535 return rc;
f37708f6 536 }
f37708f6
EB
537 trace_nbd_negotiate_handle_export_name_request(name);
538
894e0280
EB
539 rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
540 if (rc <= 0) {
541 return rc;
f37708f6
EB
542 }
543 be16_to_cpus(&requests);
f37708f6 544 trace_nbd_negotiate_handle_info_requests(requests);
f37708f6 545 while (requests--) {
894e0280
EB
546 rc = nbd_opt_read(client, &request, sizeof(request), errp);
547 if (rc <= 0) {
548 return rc;
f37708f6
EB
549 }
550 be16_to_cpus(&request);
f37708f6
EB
551 trace_nbd_negotiate_handle_info_request(request,
552 nbd_info_lookup(request));
0c1d50bd
EB
553 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
554 * everything else is either a request we don't know or
555 * something we send regardless of request */
556 switch (request) {
557 case NBD_INFO_NAME:
f37708f6 558 sendname = true;
0c1d50bd
EB
559 break;
560 case NBD_INFO_BLOCK_SIZE:
561 blocksize = true;
562 break;
f37708f6
EB
563 }
564 }
894e0280
EB
565 if (client->optlen) {
566 return nbd_reject_length(client, false, errp);
567 }
f37708f6
EB
568
569 exp = nbd_export_find(name);
570 if (!exp) {
0cfae925
VSO
571 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
572 errp, "export '%s' not present",
f37708f6
EB
573 name);
574 }
575
576 /* Don't bother sending NBD_INFO_NAME unless client requested it */
577 if (sendname) {
0cfae925 578 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
f37708f6
EB
579 errp);
580 if (rc < 0) {
581 return rc;
582 }
583 }
584
585 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
586 * client request */
587 if (exp->description) {
588 size_t len = strlen(exp->description);
589
0cfae925 590 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
f37708f6
EB
591 len, exp->description, errp);
592 if (rc < 0) {
593 return rc;
594 }
595 }
596
0c1d50bd
EB
597 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
598 * according to whether the client requested it, and according to
599 * whether this is OPT_INFO or OPT_GO. */
600 /* minimum - 1 for back-compat, or 512 if client is new enough.
601 * TODO: consult blk_bs(blk)->bl.request_alignment? */
0cfae925
VSO
602 sizes[0] =
603 (client->opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
0c1d50bd
EB
604 /* preferred - Hard-code to 4096 for now.
605 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
606 sizes[1] = 4096;
607 /* maximum - At most 32M, but smaller as appropriate. */
608 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
609 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
610 cpu_to_be32s(&sizes[0]);
611 cpu_to_be32s(&sizes[1]);
612 cpu_to_be32s(&sizes[2]);
0cfae925 613 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
0c1d50bd
EB
614 sizeof(sizes), sizes, errp);
615 if (rc < 0) {
616 return rc;
617 }
618
f37708f6
EB
619 /* Send NBD_INFO_EXPORT always */
620 trace_nbd_negotiate_new_style_size_flags(exp->size,
621 exp->nbdflags | myflags);
622 stq_be_p(buf, exp->size);
623 stw_be_p(buf + 8, exp->nbdflags | myflags);
0cfae925 624 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
f37708f6
EB
625 sizeof(buf), buf, errp);
626 if (rc < 0) {
627 return rc;
628 }
629
0c1d50bd
EB
630 /* If the client is just asking for NBD_OPT_INFO, but forgot to
631 * request block sizes, return an error.
632 * TODO: consult blk_bs(blk)->request_align, and only error if it
633 * is not 1? */
0cfae925
VSO
634 if (client->opt == NBD_OPT_INFO && !blocksize) {
635 return nbd_negotiate_send_rep_err(client,
636 NBD_REP_ERR_BLOCK_SIZE_REQD,
0c1d50bd
EB
637 errp,
638 "request NBD_INFO_BLOCK_SIZE to "
639 "use this export");
640 }
641
f37708f6 642 /* Final reply */
0cfae925 643 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
f37708f6
EB
644 if (rc < 0) {
645 return rc;
646 }
647
0cfae925 648 if (client->opt == NBD_OPT_GO) {
f37708f6
EB
649 client->exp = exp;
650 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
651 nbd_export_get(client->exp);
af736e54 652 nbd_check_meta_export(client);
f37708f6
EB
653 rc = 1;
654 }
655 return rc;
f37708f6
EB
656}
657
658
36683283
EB
659/* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
660 * new channel for all further (now-encrypted) communication. */
f95910fe 661static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
2fd2c840 662 Error **errp)
f95910fe
DB
663{
664 QIOChannel *ioc;
665 QIOChannelTLS *tioc;
666 struct NBDTLSHandshakeData data = { 0 };
667
0cfae925
VSO
668 assert(client->opt == NBD_OPT_STARTTLS);
669
9588463e 670 trace_nbd_negotiate_handle_starttls();
f95910fe 671 ioc = client->ioc;
f95910fe 672
0cfae925 673 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
63d5ef86
EB
674 return NULL;
675 }
f95910fe
DB
676
677 tioc = qio_channel_tls_new_server(ioc,
678 client->tlscreds,
679 client->tlsaclname,
2fd2c840 680 errp);
f95910fe
DB
681 if (!tioc) {
682 return NULL;
683 }
684
0d73f725 685 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
9588463e 686 trace_nbd_negotiate_handle_starttls_handshake();
f95910fe
DB
687 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
688 qio_channel_tls_handshake(tioc,
689 nbd_tls_handshake,
690 &data,
1939ccda 691 NULL,
f95910fe
DB
692 NULL);
693
694 if (!data.complete) {
695 g_main_loop_run(data.loop);
696 }
697 g_main_loop_unref(data.loop);
698 if (data.error) {
699 object_unref(OBJECT(tioc));
2fd2c840 700 error_propagate(errp, data.error);
f95910fe
DB
701 return NULL;
702 }
703
704 return QIO_CHANNEL(tioc);
705}
706
e7b1948d
VSO
707/* nbd_negotiate_send_meta_context
708 *
709 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
710 *
711 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
712 */
713static int nbd_negotiate_send_meta_context(NBDClient *client,
714 const char *context,
715 uint32_t context_id,
716 Error **errp)
717{
718 NBDOptionReplyMetaContext opt;
719 struct iovec iov[] = {
720 {.iov_base = &opt, .iov_len = sizeof(opt)},
721 {.iov_base = (void *)context, .iov_len = strlen(context)}
722 };
723
724 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
725 context_id = 0;
726 }
727
2b53af25 728 trace_nbd_negotiate_meta_query_reply(context, context_id);
e7b1948d
VSO
729 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
730 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
731 stl_be_p(&opt.context_id, context_id);
732
733 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
734}
735
736/* nbd_meta_base_query
737 *
dbb8b396
VSO
738 * Handle queries to 'base' namespace. For now, only the base:allocation
739 * context is available. 'len' is the amount of text remaining to be read from
e7b1948d
VSO
740 * the current name, after the 'base:' portion has been stripped.
741 *
742 * Return -errno on I/O error, 0 if option was completely handled by
dbb8b396
VSO
743 * sending a reply about inconsistent lengths, or 1 on success.
744 *
745 * Note: return code = 1 doesn't mean that we've parsed the "base:allocation"
746 * namespace. It only means that there are no errors.
747 */
e7b1948d
VSO
748static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
749 uint32_t len, Error **errp)
750{
751 int ret;
752 char query[sizeof("allocation") - 1];
753 size_t alen = strlen("allocation");
754
755 if (len == 0) {
756 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
757 meta->base_allocation = true;
758 }
2b53af25 759 trace_nbd_negotiate_meta_query_parse("base:");
e7b1948d
VSO
760 return 1;
761 }
762
763 if (len != alen) {
2b53af25 764 trace_nbd_negotiate_meta_query_skip("not base:allocation");
e7b1948d
VSO
765 return nbd_opt_skip(client, len, errp);
766 }
767
768 ret = nbd_opt_read(client, query, len, errp);
769 if (ret <= 0) {
770 return ret;
771 }
772
773 if (strncmp(query, "allocation", alen) == 0) {
dbb8b396 774 trace_nbd_negotiate_meta_query_parse("base:allocation");
e7b1948d 775 meta->base_allocation = true;
dbb8b396
VSO
776 } else {
777 trace_nbd_negotiate_meta_query_skip("not base:allocation");
e7b1948d
VSO
778 }
779
780 return 1;
781}
782
783/* nbd_negotiate_meta_query
784 *
785 * Parse namespace name and call corresponding function to parse body of the
786 * query.
787 *
788 * The only supported namespace now is 'base'.
789 *
790 * The function aims not wasting time and memory to read long unknown namespace
791 * names.
792 *
793 * Return -errno on I/O error, 0 if option was completely handled by
794 * sending a reply about inconsistent lengths, or 1 on success. */
795static int nbd_negotiate_meta_query(NBDClient *client,
796 NBDExportMetaContexts *meta, Error **errp)
797{
798 int ret;
799 char query[sizeof("base:") - 1];
800 size_t baselen = strlen("base:");
801 uint32_t len;
802
803 ret = nbd_opt_read(client, &len, sizeof(len), errp);
804 if (ret <= 0) {
805 return ret;
806 }
807 cpu_to_be32s(&len);
808
809 /* The only supported namespace for now is 'base'. So query should start
810 * with 'base:'. Otherwise, we can ignore it and skip the remainder. */
811 if (len < baselen) {
2b53af25 812 trace_nbd_negotiate_meta_query_skip("length too short");
e7b1948d
VSO
813 return nbd_opt_skip(client, len, errp);
814 }
815
816 len -= baselen;
817 ret = nbd_opt_read(client, query, baselen, errp);
818 if (ret <= 0) {
819 return ret;
820 }
821 if (strncmp(query, "base:", baselen) != 0) {
2b53af25 822 trace_nbd_negotiate_meta_query_skip("not for base: namespace");
e7b1948d
VSO
823 return nbd_opt_skip(client, len, errp);
824 }
825
826 return nbd_meta_base_query(client, meta, len, errp);
827}
828
829/* nbd_negotiate_meta_queries
830 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
831 *
832 * Return -errno on I/O error, or 0 if option was completely handled. */
833static int nbd_negotiate_meta_queries(NBDClient *client,
834 NBDExportMetaContexts *meta, Error **errp)
835{
836 int ret;
af736e54 837 char export_name[NBD_MAX_NAME_SIZE + 1];
e7b1948d
VSO
838 NBDExportMetaContexts local_meta;
839 uint32_t nb_queries;
840 int i;
841
842 if (!client->structured_reply) {
843 return nbd_opt_invalid(client, errp,
844 "request option '%s' when structured reply "
845 "is not negotiated",
846 nbd_opt_lookup(client->opt));
847 }
848
849 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
850 /* Only change the caller's meta on SET. */
851 meta = &local_meta;
852 }
853
854 memset(meta, 0, sizeof(*meta));
855
af736e54 856 ret = nbd_opt_read_name(client, export_name, NULL, errp);
e7b1948d
VSO
857 if (ret <= 0) {
858 return ret;
859 }
860
af736e54
VSO
861 meta->exp = nbd_export_find(export_name);
862 if (meta->exp == NULL) {
e7b1948d 863 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
af736e54 864 "export '%s' not present", export_name);
e7b1948d
VSO
865 }
866
867 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp);
868 if (ret <= 0) {
869 return ret;
870 }
871 cpu_to_be32s(&nb_queries);
2b53af25 872 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
af736e54 873 export_name, nb_queries);
e7b1948d
VSO
874
875 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
876 /* enable all known contexts */
877 meta->base_allocation = true;
878 } else {
879 for (i = 0; i < nb_queries; ++i) {
880 ret = nbd_negotiate_meta_query(client, meta, errp);
881 if (ret <= 0) {
882 return ret;
883 }
884 }
885 }
886
887 if (meta->base_allocation) {
888 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
889 NBD_META_ID_BASE_ALLOCATION,
890 errp);
891 if (ret < 0) {
892 return ret;
893 }
894 }
895
896 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
897 if (ret == 0) {
898 meta->valid = true;
899 }
900
901 return ret;
902}
903
1e120ffe 904/* nbd_negotiate_options
f37708f6
EB
905 * Process all NBD_OPT_* client option commands, during fixed newstyle
906 * negotiation.
1e120ffe 907 * Return:
2fd2c840
VSO
908 * -errno on error, errp is set
909 * 0 on successful negotiation, errp is not set
910 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
911 * errp is not set
1e120ffe 912 */
23e099c3
EB
913static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
914 Error **errp)
f5076b5a 915{
9c122ada 916 uint32_t flags;
26afa868 917 bool fixedNewstyle = false;
23e099c3 918 bool no_zeroes = false;
9c122ada
HR
919
920 /* Client sends:
921 [ 0 .. 3] client flags
922
f37708f6 923 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
9c122ada
HR
924 [ 0 .. 7] NBD_OPTS_MAGIC
925 [ 8 .. 11] NBD option
926 [12 .. 15] Data length
927 ... Rest of request
928
929 [ 0 .. 7] NBD_OPTS_MAGIC
930 [ 8 .. 11] Second NBD option
931 [12 .. 15] Data length
932 ... Rest of request
933 */
934
2fd2c840
VSO
935 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
936 error_prepend(errp, "read failed: ");
9c122ada
HR
937 return -EIO;
938 }
9c122ada 939 be32_to_cpus(&flags);
621c4f4e 940 trace_nbd_negotiate_options_flags(flags);
26afa868 941 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
26afa868
DB
942 fixedNewstyle = true;
943 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
944 }
c203c59a 945 if (flags & NBD_FLAG_C_NO_ZEROES) {
23e099c3 946 no_zeroes = true;
c203c59a
EB
947 flags &= ~NBD_FLAG_C_NO_ZEROES;
948 }
26afa868 949 if (flags != 0) {
2fd2c840 950 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
621c4f4e 951 return -EINVAL;
9c122ada
HR
952 }
953
f5076b5a 954 while (1) {
9c122ada 955 int ret;
7f9039cd 956 uint32_t option, length;
f5076b5a
HB
957 uint64_t magic;
958
2fd2c840
VSO
959 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
960 error_prepend(errp, "read failed: ");
f5076b5a
HB
961 return -EINVAL;
962 }
9588463e
VSO
963 magic = be64_to_cpu(magic);
964 trace_nbd_negotiate_options_check_magic(magic);
965 if (magic != NBD_OPTS_MAGIC) {
2fd2c840 966 error_setg(errp, "Bad magic received");
f5076b5a
HB
967 return -EINVAL;
968 }
969
7f9039cd
VSO
970 if (nbd_read(client->ioc, &option,
971 sizeof(option), errp) < 0) {
2fd2c840 972 error_prepend(errp, "read failed: ");
f5076b5a
HB
973 return -EINVAL;
974 }
7f9039cd 975 option = be32_to_cpu(option);
0cfae925 976 client->opt = option;
f5076b5a 977
2fd2c840
VSO
978 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
979 error_prepend(errp, "read failed: ");
f5076b5a
HB
980 return -EINVAL;
981 }
982 length = be32_to_cpu(length);
894e0280 983 assert(!client->optlen);
0cfae925 984 client->optlen = length;
f5076b5a 985
fdad35ef
EB
986 if (length > NBD_MAX_BUFFER_SIZE) {
987 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
988 length, NBD_MAX_BUFFER_SIZE);
989 return -EINVAL;
990 }
991
3736cc5b
EB
992 trace_nbd_negotiate_options_check_option(option,
993 nbd_opt_lookup(option));
f95910fe
DB
994 if (client->tlscreds &&
995 client->ioc == (QIOChannel *)client->sioc) {
996 QIOChannel *tioc;
997 if (!fixedNewstyle) {
7f9039cd 998 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
f95910fe
DB
999 return -EINVAL;
1000 }
7f9039cd 1001 switch (option) {
f95910fe 1002 case NBD_OPT_STARTTLS:
e68c35cf
EB
1003 if (length) {
1004 /* Unconditionally drop the connection if the client
1005 * can't start a TLS negotiation correctly */
0cfae925 1006 return nbd_reject_length(client, true, errp);
e68c35cf
EB
1007 }
1008 tioc = nbd_negotiate_handle_starttls(client, errp);
f95910fe
DB
1009 if (!tioc) {
1010 return -EIO;
1011 }
8cbee49e 1012 ret = 0;
f95910fe
DB
1013 object_unref(OBJECT(client->ioc));
1014 client->ioc = QIO_CHANNEL(tioc);
1015 break;
1016
d1129a8a
EB
1017 case NBD_OPT_EXPORT_NAME:
1018 /* No way to return an error to client, so drop connection */
2fd2c840 1019 error_setg(errp, "Option 0x%x not permitted before TLS",
7f9039cd 1020 option);
d1129a8a
EB
1021 return -EINVAL;
1022
f95910fe 1023 default:
894e0280
EB
1024 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD, errp,
1025 "Option 0x%" PRIx32
1026 "not permitted before TLS", option);
37ec36f6
EB
1027 /* Let the client keep trying, unless they asked to
1028 * quit. In this mode, we've already sent an error, so
1029 * we can't ack the abort. */
7f9039cd 1030 if (option == NBD_OPT_ABORT) {
1e120ffe 1031 return 1;
b6f5d3b5 1032 }
d1129a8a 1033 break;
f95910fe
DB
1034 }
1035 } else if (fixedNewstyle) {
7f9039cd 1036 switch (option) {
26afa868 1037 case NBD_OPT_LIST:
e68c35cf 1038 if (length) {
0cfae925 1039 ret = nbd_reject_length(client, false, errp);
e68c35cf
EB
1040 } else {
1041 ret = nbd_negotiate_handle_list(client, errp);
1042 }
26afa868
DB
1043 break;
1044
1045 case NBD_OPT_ABORT:
b6f5d3b5
EB
1046 /* NBD spec says we must try to reply before
1047 * disconnecting, but that we must also tolerate
1048 * guests that don't wait for our reply. */
0cfae925 1049 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1e120ffe 1050 return 1;
26afa868
DB
1051
1052 case NBD_OPT_EXPORT_NAME:
0cfae925 1053 return nbd_negotiate_handle_export_name(client,
23e099c3
EB
1054 myflags, no_zeroes,
1055 errp);
26afa868 1056
f37708f6
EB
1057 case NBD_OPT_INFO:
1058 case NBD_OPT_GO:
0cfae925 1059 ret = nbd_negotiate_handle_info(client, myflags, errp);
f37708f6
EB
1060 if (ret == 1) {
1061 assert(option == NBD_OPT_GO);
1062 return 0;
1063 }
f37708f6
EB
1064 break;
1065
f95910fe 1066 case NBD_OPT_STARTTLS:
e68c35cf 1067 if (length) {
0cfae925 1068 ret = nbd_reject_length(client, false, errp);
e68c35cf 1069 } else if (client->tlscreds) {
0cfae925
VSO
1070 ret = nbd_negotiate_send_rep_err(client,
1071 NBD_REP_ERR_INVALID, errp,
36683283 1072 "TLS already enabled");
f95910fe 1073 } else {
0cfae925
VSO
1074 ret = nbd_negotiate_send_rep_err(client,
1075 NBD_REP_ERR_POLICY, errp,
36683283 1076 "TLS not configured");
63d5ef86 1077 }
d1129a8a 1078 break;
5c54e7fa
VSO
1079
1080 case NBD_OPT_STRUCTURED_REPLY:
1081 if (length) {
0cfae925 1082 ret = nbd_reject_length(client, false, errp);
5c54e7fa
VSO
1083 } else if (client->structured_reply) {
1084 ret = nbd_negotiate_send_rep_err(
0cfae925 1085 client, NBD_REP_ERR_INVALID, errp,
5c54e7fa
VSO
1086 "structured reply already negotiated");
1087 } else {
0cfae925 1088 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
5c54e7fa
VSO
1089 client->structured_reply = true;
1090 myflags |= NBD_FLAG_SEND_DF;
1091 }
1092 break;
1093
e7b1948d
VSO
1094 case NBD_OPT_LIST_META_CONTEXT:
1095 case NBD_OPT_SET_META_CONTEXT:
1096 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1097 errp);
1098 break;
1099
26afa868 1100 default:
894e0280 1101 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
28fb494f 1102 "Unsupported option %" PRIu32 " (%s)",
894e0280 1103 option, nbd_opt_lookup(option));
156f6a10 1104 break;
26afa868
DB
1105 }
1106 } else {
1107 /*
1108 * If broken new-style we should drop the connection
1109 * for anything except NBD_OPT_EXPORT_NAME
1110 */
7f9039cd 1111 switch (option) {
26afa868 1112 case NBD_OPT_EXPORT_NAME:
0cfae925 1113 return nbd_negotiate_handle_export_name(client,
23e099c3
EB
1114 myflags, no_zeroes,
1115 errp);
26afa868
DB
1116
1117 default:
28fb494f 1118 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
3736cc5b 1119 option, nbd_opt_lookup(option));
26afa868 1120 return -EINVAL;
32d7d2e0 1121 }
f5076b5a 1122 }
8cbee49e
EB
1123 if (ret < 0) {
1124 return ret;
1125 }
f5076b5a
HB
1126 }
1127}
1128
1e120ffe
VSO
1129/* nbd_negotiate
1130 * Return:
2fd2c840
VSO
1131 * -errno on error, errp is set
1132 * 0 on successful negotiation, errp is not set
1133 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1134 * errp is not set
1e120ffe 1135 */
2fd2c840 1136static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
7a5ca864 1137{
5f66d060 1138 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
2e5c9ad6 1139 int ret;
7423f417 1140 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
1f4d6d18
EB
1141 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
1142 NBD_FLAG_SEND_WRITE_ZEROES);
f95910fe 1143 bool oldStyle;
b2e3d87f 1144
5f66d060 1145 /* Old style negotiation header, no room for options
6b8c01e7
PB
1146 [ 0 .. 7] passwd ("NBDMAGIC")
1147 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
b2e3d87f 1148 [16 .. 23] size
5f66d060 1149 [24 .. 27] export flags (zero-extended)
6b8c01e7
PB
1150 [28 .. 151] reserved (0)
1151
5f66d060 1152 New style negotiation header, client can send options
6b8c01e7
PB
1153 [ 0 .. 7] passwd ("NBDMAGIC")
1154 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1155 [16 .. 17] server flags (0)
f37708f6 1156 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
b2e3d87f
NT
1157 */
1158
1c778ef7 1159 qio_channel_set_blocking(client->ioc, false, NULL);
185b4338 1160
9588463e 1161 trace_nbd_negotiate_begin();
b2e3d87f 1162 memcpy(buf, "NBDMAGIC", 8);
f95910fe
DB
1163
1164 oldStyle = client->exp != NULL && !client->tlscreds;
1165 if (oldStyle) {
9588463e
VSO
1166 trace_nbd_negotiate_old_style(client->exp->size,
1167 client->exp->nbdflags | myflags);
667ad26f
JS
1168 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
1169 stq_be_p(buf + 16, client->exp->size);
5f66d060 1170 stl_be_p(buf + 24, client->exp->nbdflags | myflags);
b2e3d87f 1171
2fd2c840
VSO
1172 if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
1173 error_prepend(errp, "write failed: ");
d9faeed8 1174 return -EINVAL;
6b8c01e7
PB
1175 }
1176 } else {
76ff081d
VSO
1177 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1178 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1179
2fd2c840
VSO
1180 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1181 error_prepend(errp, "write failed: ");
d9faeed8 1182 return -EINVAL;
6b8c01e7 1183 }
23e099c3 1184 ret = nbd_negotiate_options(client, myflags, errp);
2e5c9ad6 1185 if (ret != 0) {
2fd2c840
VSO
1186 if (ret < 0) {
1187 error_prepend(errp, "option negotiation failed: ");
1188 }
2e5c9ad6 1189 return ret;
6b8c01e7 1190 }
b2e3d87f
NT
1191 }
1192
0cfae925 1193 assert(!client->optlen);
9588463e 1194 trace_nbd_negotiate_success();
d9faeed8
VSO
1195
1196 return 0;
7a5ca864
FB
1197}
1198
2fd2c840
VSO
1199static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1200 Error **errp)
75818250 1201{
fa26c26b 1202 uint8_t buf[NBD_REQUEST_SIZE];
b2e3d87f 1203 uint32_t magic;
a0dc63a6 1204 int ret;
b2e3d87f 1205
2fd2c840 1206 ret = nbd_read(ioc, buf, sizeof(buf), errp);
185b4338
PB
1207 if (ret < 0) {
1208 return ret;
1209 }
1210
b2e3d87f
NT
1211 /* Request
1212 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
b626b51a
EB
1213 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1214 [ 6 .. 7] type (NBD_CMD_READ, ...)
b2e3d87f
NT
1215 [ 8 .. 15] handle
1216 [16 .. 23] from
1217 [24 .. 27] len
1218 */
1219
773dce3c 1220 magic = ldl_be_p(buf);
b626b51a
EB
1221 request->flags = lduw_be_p(buf + 4);
1222 request->type = lduw_be_p(buf + 6);
773dce3c
PM
1223 request->handle = ldq_be_p(buf + 8);
1224 request->from = ldq_be_p(buf + 16);
1225 request->len = ldl_be_p(buf + 24);
b2e3d87f 1226
9588463e
VSO
1227 trace_nbd_receive_request(magic, request->flags, request->type,
1228 request->from, request->len);
b2e3d87f
NT
1229
1230 if (magic != NBD_REQUEST_MAGIC) {
2fd2c840 1231 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
185b4338 1232 return -EINVAL;
b2e3d87f
NT
1233 }
1234 return 0;
75818250
TS
1235}
1236
41996e38
PB
1237#define MAX_NBD_REQUESTS 16
1238
ce33967a 1239void nbd_client_get(NBDClient *client)
1743b515
PB
1240{
1241 client->refcount++;
1242}
1243
ce33967a 1244void nbd_client_put(NBDClient *client)
1743b515
PB
1245{
1246 if (--client->refcount == 0) {
ff2b68aa 1247 /* The last reference should be dropped by client->close,
f53a829b 1248 * which is called by client_close.
ff2b68aa
PB
1249 */
1250 assert(client->closing);
1251
ff82911c 1252 qio_channel_detach_aio_context(client->ioc);
1c778ef7
DB
1253 object_unref(OBJECT(client->sioc));
1254 object_unref(OBJECT(client->ioc));
f95910fe
DB
1255 if (client->tlscreds) {
1256 object_unref(OBJECT(client->tlscreds));
1257 }
1258 g_free(client->tlsaclname);
6b8c01e7
PB
1259 if (client->exp) {
1260 QTAILQ_REMOVE(&client->exp->clients, client, next);
1261 nbd_export_put(client->exp);
1262 }
1743b515
PB
1263 g_free(client);
1264 }
1265}
1266
0c9390d9 1267static void client_close(NBDClient *client, bool negotiated)
1743b515 1268{
ff2b68aa
PB
1269 if (client->closing) {
1270 return;
1271 }
1272
1273 client->closing = true;
1274
1275 /* Force requests to finish. They will drop their own references,
1276 * then we'll close the socket and free the NBDClient.
1277 */
1c778ef7
DB
1278 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1279 NULL);
ff2b68aa
PB
1280
1281 /* Also tell the client, so that they release their reference. */
0c9390d9
EB
1282 if (client->close_fn) {
1283 client->close_fn(client, negotiated);
1743b515 1284 }
1743b515
PB
1285}
1286
315f78ab 1287static NBDRequestData *nbd_request_get(NBDClient *client)
d9a73806 1288{
315f78ab 1289 NBDRequestData *req;
72deddc5 1290
41996e38
PB
1291 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1292 client->nb_requests++;
1293
315f78ab 1294 req = g_new0(NBDRequestData, 1);
72deddc5
PB
1295 nbd_client_get(client);
1296 req->client = client;
d9a73806
PB
1297 return req;
1298}
1299
315f78ab 1300static void nbd_request_put(NBDRequestData *req)
d9a73806 1301{
72deddc5 1302 NBDClient *client = req->client;
e1adb27a 1303
2d821488
SH
1304 if (req->data) {
1305 qemu_vfree(req->data);
1306 }
1729404c 1307 g_free(req);
e1adb27a 1308
958c717d 1309 client->nb_requests--;
ff82911c
PB
1310 nbd_client_receive_next_request(client);
1311
72deddc5 1312 nbd_client_put(client);
d9a73806
PB
1313}
1314
aadf99a7 1315static void blk_aio_attached(AioContext *ctx, void *opaque)
f2149281
HR
1316{
1317 NBDExport *exp = opaque;
1318 NBDClient *client;
1319
9588463e 1320 trace_nbd_blk_aio_attached(exp->name, ctx);
f2149281
HR
1321
1322 exp->ctx = ctx;
1323
1324 QTAILQ_FOREACH(client, &exp->clients, next) {
ff82911c
PB
1325 qio_channel_attach_aio_context(client->ioc, ctx);
1326 if (client->recv_coroutine) {
1327 aio_co_schedule(ctx, client->recv_coroutine);
1328 }
1329 if (client->send_coroutine) {
1330 aio_co_schedule(ctx, client->send_coroutine);
1331 }
f2149281
HR
1332 }
1333}
1334
aadf99a7 1335static void blk_aio_detach(void *opaque)
f2149281
HR
1336{
1337 NBDExport *exp = opaque;
1338 NBDClient *client;
1339
9588463e 1340 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
f2149281
HR
1341
1342 QTAILQ_FOREACH(client, &exp->clients, next) {
ff82911c 1343 qio_channel_detach_aio_context(client->ioc);
f2149281
HR
1344 }
1345
1346 exp->ctx = NULL;
1347}
1348
741cc431
HR
1349static void nbd_eject_notifier(Notifier *n, void *data)
1350{
1351 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1352 nbd_export_close(exp);
1353}
1354
cd7fca95 1355NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
7423f417 1356 uint16_t nbdflags, void (*close)(NBDExport *),
cd7fca95 1357 bool writethrough, BlockBackend *on_eject_blk,
98f44bbe 1358 Error **errp)
af49bbbe 1359{
3dff24f2 1360 AioContext *ctx;
cd7fca95 1361 BlockBackend *blk;
e8d3eb74 1362 NBDExport *exp = g_new0(NBDExport, 1);
8a7ce4f9 1363 uint64_t perm;
d7086422 1364 int ret;
cd7fca95 1365
3dff24f2
KW
1366 /*
1367 * NBD exports are used for non-shared storage migration. Make sure
1368 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1369 * access since the export could be available before migration handover.
1370 */
1371 ctx = bdrv_get_aio_context(bs);
1372 aio_context_acquire(ctx);
1373 bdrv_invalidate_cache(bs, NULL);
1374 aio_context_release(ctx);
1375
8a7ce4f9
KW
1376 /* Don't allow resize while the NBD server is running, otherwise we don't
1377 * care what happens with the node. */
1378 perm = BLK_PERM_CONSISTENT_READ;
1379 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1380 perm |= BLK_PERM_WRITE;
1381 }
1382 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1383 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
d7086422
KW
1384 ret = blk_insert_bs(blk, bs, errp);
1385 if (ret < 0) {
1386 goto fail;
1387 }
cd7fca95
KW
1388 blk_set_enable_write_cache(blk, !writethrough);
1389
2c8d9f06 1390 exp->refcount = 1;
4b9441f6 1391 QTAILQ_INIT(&exp->clients);
aadf99a7 1392 exp->blk = blk;
af49bbbe
PB
1393 exp->dev_offset = dev_offset;
1394 exp->nbdflags = nbdflags;
98f44bbe
HR
1395 exp->size = size < 0 ? blk_getlength(blk) : size;
1396 if (exp->size < 0) {
1397 error_setg_errno(errp, -exp->size,
1398 "Failed to determine the NBD export's length");
1399 goto fail;
1400 }
1401 exp->size -= exp->size % BDRV_SECTOR_SIZE;
1402
0ddf08db 1403 exp->close = close;
aadf99a7 1404 exp->ctx = blk_get_aio_context(blk);
aadf99a7 1405 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
741cc431 1406
cd7fca95
KW
1407 if (on_eject_blk) {
1408 blk_ref(on_eject_blk);
1409 exp->eject_notifier_blk = on_eject_blk;
1410 exp->eject_notifier.notify = nbd_eject_notifier;
1411 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1412 }
af49bbbe 1413 return exp;
98f44bbe
HR
1414
1415fail:
cd7fca95 1416 blk_unref(blk);
98f44bbe
HR
1417 g_free(exp);
1418 return NULL;
af49bbbe
PB
1419}
1420
ee0a19ec
PB
1421NBDExport *nbd_export_find(const char *name)
1422{
1423 NBDExport *exp;
1424 QTAILQ_FOREACH(exp, &exports, next) {
1425 if (strcmp(name, exp->name) == 0) {
1426 return exp;
1427 }
1428 }
1429
1430 return NULL;
1431}
1432
1433void nbd_export_set_name(NBDExport *exp, const char *name)
1434{
1435 if (exp->name == name) {
1436 return;
1437 }
1438
1439 nbd_export_get(exp);
1440 if (exp->name != NULL) {
1441 g_free(exp->name);
1442 exp->name = NULL;
1443 QTAILQ_REMOVE(&exports, exp, next);
1444 nbd_export_put(exp);
1445 }
1446 if (name != NULL) {
1447 nbd_export_get(exp);
1448 exp->name = g_strdup(name);
1449 QTAILQ_INSERT_TAIL(&exports, exp, next);
1450 }
1451 nbd_export_put(exp);
1452}
1453
b1a75b33
EB
1454void nbd_export_set_description(NBDExport *exp, const char *description)
1455{
1456 g_free(exp->description);
1457 exp->description = g_strdup(description);
1458}
1459
af49bbbe
PB
1460void nbd_export_close(NBDExport *exp)
1461{
4b9441f6 1462 NBDClient *client, *next;
2c8d9f06 1463
4b9441f6
PB
1464 nbd_export_get(exp);
1465 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
0c9390d9 1466 client_close(client, true);
4b9441f6 1467 }
125afda8 1468 nbd_export_set_name(exp, NULL);
b1a75b33 1469 nbd_export_set_description(exp, NULL);
4b9441f6 1470 nbd_export_put(exp);
2c8d9f06
PB
1471}
1472
a3b0dc75
VSO
1473void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1474{
1475 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1476 nbd_export_close(exp);
1477 return;
1478 }
1479
1480 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1481
1482 error_setg(errp, "export '%s' still in use", exp->name);
1483 error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1484}
1485
2c8d9f06
PB
1486void nbd_export_get(NBDExport *exp)
1487{
1488 assert(exp->refcount > 0);
1489 exp->refcount++;
1490}
1491
1492void nbd_export_put(NBDExport *exp)
1493{
1494 assert(exp->refcount > 0);
1495 if (exp->refcount == 1) {
1496 nbd_export_close(exp);
d9a73806
PB
1497 }
1498
9156245e
VSO
1499 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1500 * if someone calls nbd_export_put() on named export not through
1501 * nbd_export_set_name() when refcount is 1. So, let's assert that
1502 * it is > 0.
1503 */
1504 assert(exp->refcount > 0);
2c8d9f06 1505 if (--exp->refcount == 0) {
ee0a19ec 1506 assert(exp->name == NULL);
b1a75b33 1507 assert(exp->description == NULL);
ee0a19ec 1508
0ddf08db
PB
1509 if (exp->close) {
1510 exp->close(exp);
1511 }
1512
d6268348 1513 if (exp->blk) {
cd7fca95
KW
1514 if (exp->eject_notifier_blk) {
1515 notifier_remove(&exp->eject_notifier);
1516 blk_unref(exp->eject_notifier_blk);
1517 }
d6268348
WC
1518 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1519 blk_aio_detach, exp);
1520 blk_unref(exp->blk);
1521 exp->blk = NULL;
1522 }
1523
2c8d9f06
PB
1524 g_free(exp);
1525 }
af49bbbe
PB
1526}
1527
e140177d 1528BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
125afda8 1529{
aadf99a7 1530 return exp->blk;
125afda8
PB
1531}
1532
ee0a19ec
PB
1533void nbd_export_close_all(void)
1534{
1535 NBDExport *exp, *next;
1536
1537 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1538 nbd_export_close(exp);
ee0a19ec
PB
1539 }
1540}
1541
de79bfc3
VSO
1542static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1543 unsigned niov, Error **errp)
1544{
1545 int ret;
1546
1547 g_assert(qemu_in_coroutine());
1548 qemu_co_mutex_lock(&client->send_lock);
1549 client->send_coroutine = qemu_coroutine_self();
1550
1551 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1552
1553 client->send_coroutine = NULL;
1554 qemu_co_mutex_unlock(&client->send_lock);
1555
1556 return ret;
1557}
1558
caad5384
VSO
1559static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1560 uint64_t handle)
1561{
1562 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1563 stl_be_p(&reply->error, error);
1564 stq_be_p(&reply->handle, handle);
1565}
1566
978df1b6 1567static int nbd_co_send_simple_reply(NBDClient *client,
14cea41d
VSO
1568 uint64_t handle,
1569 uint32_t error,
978df1b6
VSO
1570 void *data,
1571 size_t len,
1572 Error **errp)
22045592 1573{
de79bfc3 1574 NBDSimpleReply reply;
14cea41d 1575 int nbd_err = system_errno_to_nbd_errno(error);
de79bfc3
VSO
1576 struct iovec iov[] = {
1577 {.iov_base = &reply, .iov_len = sizeof(reply)},
1578 {.iov_base = data, .iov_len = len}
1579 };
6fb2b972 1580
e7a78d0e
EB
1581 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1582 len);
de79bfc3 1583 set_be_simple_reply(&reply, nbd_err, handle);
262db388 1584
de79bfc3 1585 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
22045592
PB
1586}
1587
5c54e7fa
VSO
1588static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1589 uint16_t type, uint64_t handle, uint32_t length)
1590{
1591 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1592 stw_be_p(&chunk->flags, flags);
1593 stw_be_p(&chunk->type, type);
1594 stq_be_p(&chunk->handle, handle);
1595 stl_be_p(&chunk->length, length);
1596}
1597
ef8c887e
EB
1598static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1599 uint64_t handle,
1600 Error **errp)
1601{
1602 NBDStructuredReplyChunk chunk;
1603 struct iovec iov[] = {
1604 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1605 };
1606
1607 trace_nbd_co_send_structured_done(handle);
1608 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1609
1610 return nbd_co_send_iov(client, iov, 1, errp);
1611}
1612
5c54e7fa
VSO
1613static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1614 uint64_t handle,
1615 uint64_t offset,
1616 void *data,
1617 size_t size,
418638d3 1618 bool final,
5c54e7fa
VSO
1619 Error **errp)
1620{
efdc0c10 1621 NBDStructuredReadData chunk;
5c54e7fa
VSO
1622 struct iovec iov[] = {
1623 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1624 {.iov_base = data, .iov_len = size}
1625 };
1626
ef8c887e 1627 assert(size);
5c54e7fa 1628 trace_nbd_co_send_structured_read(handle, offset, data, size);
418638d3
EB
1629 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1630 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1631 sizeof(chunk) - sizeof(chunk.h) + size);
5c54e7fa
VSO
1632 stq_be_p(&chunk.offset, offset);
1633
1634 return nbd_co_send_iov(client, iov, 2, errp);
1635}
1636
60ace2ba
VSO
1637static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1638 uint64_t handle,
1639 uint32_t error,
1640 const char *msg,
1641 Error **errp)
1642{
1643 NBDStructuredError chunk;
1644 int nbd_err = system_errno_to_nbd_errno(error);
1645 struct iovec iov[] = {
1646 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1647 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1648 };
1649
1650 assert(nbd_err);
1651 trace_nbd_co_send_structured_error(handle, nbd_err,
1652 nbd_err_lookup(nbd_err), msg ? msg : "");
1653 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1654 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1655 stl_be_p(&chunk.error, nbd_err);
1656 stw_be_p(&chunk.message_length, iov[1].iov_len);
1657
1658 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1659}
1660
37e02aeb
VSO
1661/* Do a sparse read and send the structured reply to the client.
1662 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1663 * reported to the client, at which point this function succeeds.
1664 */
418638d3
EB
1665static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1666 uint64_t handle,
1667 uint64_t offset,
1668 uint8_t *data,
1669 size_t size,
1670 Error **errp)
1671{
1672 int ret = 0;
1673 NBDExport *exp = client->exp;
1674 size_t progress = 0;
1675
1676 while (progress < size) {
1677 int64_t pnum;
1678 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1679 offset + progress,
1680 size - progress, &pnum, NULL,
1681 NULL);
e2de3256 1682 bool final;
418638d3
EB
1683
1684 if (status < 0) {
37e02aeb
VSO
1685 char *msg = g_strdup_printf("unable to check for holes: %s",
1686 strerror(-status));
1687
1688 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1689 errp);
1690 g_free(msg);
1691 return ret;
418638d3
EB
1692 }
1693 assert(pnum && pnum <= size - progress);
e2de3256 1694 final = progress + pnum == size;
418638d3
EB
1695 if (status & BDRV_BLOCK_ZERO) {
1696 NBDStructuredReadHole chunk;
1697 struct iovec iov[] = {
1698 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1699 };
1700
1701 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1702 pnum);
e2de3256
EB
1703 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1704 NBD_REPLY_TYPE_OFFSET_HOLE,
418638d3
EB
1705 handle, sizeof(chunk) - sizeof(chunk.h));
1706 stq_be_p(&chunk.offset, offset + progress);
1707 stl_be_p(&chunk.length, pnum);
1708 ret = nbd_co_send_iov(client, iov, 1, errp);
1709 } else {
1710 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1711 data + progress, pnum);
1712 if (ret < 0) {
1713 error_setg_errno(errp, -ret, "reading from file failed");
1714 break;
1715 }
1716 ret = nbd_co_send_structured_read(client, handle, offset + progress,
e2de3256 1717 data + progress, pnum, final,
418638d3
EB
1718 errp);
1719 }
1720
1721 if (ret < 0) {
1722 break;
1723 }
1724 progress += pnum;
1725 }
418638d3
EB
1726 return ret;
1727}
1728
e7b1948d
VSO
1729static int blockstatus_to_extent_be(BlockDriverState *bs, uint64_t offset,
1730 uint64_t bytes, NBDExtent *extent)
1731{
1732 uint64_t remaining_bytes = bytes;
1733
1734 while (remaining_bytes) {
1735 uint32_t flags;
1736 int64_t num;
1737 int ret = bdrv_block_status_above(bs, NULL, offset, remaining_bytes,
1738 &num, NULL, NULL);
1739 if (ret < 0) {
1740 return ret;
1741 }
1742
1743 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
1744 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
1745
1746 if (remaining_bytes == bytes) {
1747 extent->flags = flags;
1748 }
1749
1750 if (flags != extent->flags) {
1751 break;
1752 }
1753
1754 offset += num;
1755 remaining_bytes -= num;
1756 }
1757
1758 cpu_to_be32s(&extent->flags);
1759 extent->length = cpu_to_be32(bytes - remaining_bytes);
1760
1761 return 0;
1762}
1763
1764/* nbd_co_send_extents
1765 * @extents should be in big-endian */
1766static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
1767 NBDExtent *extents, unsigned nb_extents,
1768 uint32_t context_id, Error **errp)
1769{
1770 NBDStructuredMeta chunk;
1771
1772 struct iovec iov[] = {
1773 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1774 {.iov_base = extents, .iov_len = nb_extents * sizeof(extents[0])}
1775 };
1776
1777 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_BLOCK_STATUS,
1778 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1779 stl_be_p(&chunk.context_id, context_id);
1780
1781 return nbd_co_send_iov(client, iov, 2, errp);
1782}
1783
1784/* Get block status from the exported device and send it to the client */
1785static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
1786 BlockDriverState *bs, uint64_t offset,
1787 uint64_t length, uint32_t context_id,
1788 Error **errp)
1789{
1790 int ret;
1791 NBDExtent extent;
1792
1793 ret = blockstatus_to_extent_be(bs, offset, length, &extent);
1794 if (ret < 0) {
1795 return nbd_co_send_structured_error(
1796 client, handle, -ret, "can't get block status", errp);
1797 }
1798
1799 return nbd_co_send_extents(client, handle, &extent, 1, context_id, errp);
1800}
1801
2a6e128b
VSO
1802/* nbd_co_receive_request
1803 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1804 * connection right away, and any other negative value to report an error to
1805 * the client (although the caller may still need to disconnect after reporting
1806 * the error).
1807 */
2fd2c840
VSO
1808static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1809 Error **errp)
a030b347 1810{
72deddc5 1811 NBDClient *client = req->client;
5c54e7fa 1812 int valid_flags;
a030b347 1813
1c778ef7 1814 g_assert(qemu_in_coroutine());
ff82911c 1815 assert(client->recv_coroutine == qemu_coroutine_self());
2fd2c840 1816 if (nbd_receive_request(client->ioc, request, errp) < 0) {
ee898b87 1817 return -EIO;
a030b347
PB
1818 }
1819
3736cc5b
EB
1820 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
1821 nbd_cmd_lookup(request->type));
29b6c3b3 1822
b626b51a 1823 if (request->type != NBD_CMD_WRITE) {
29b6c3b3
EB
1824 /* No payload, we are ready to read the next request. */
1825 req->complete = true;
1826 }
1827
b626b51a 1828 if (request->type == NBD_CMD_DISC) {
29b6c3b3
EB
1829 /* Special case: we're going to disconnect without a reply,
1830 * whether or not flags, from, or len are bogus */
ee898b87 1831 return -EIO;
29b6c3b3
EB
1832 }
1833
b626b51a 1834 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
eb38c3b6 1835 if (request->len > NBD_MAX_BUFFER_SIZE) {
2fd2c840
VSO
1836 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1837 request->len, NBD_MAX_BUFFER_SIZE);
ee898b87 1838 return -EINVAL;
eb38c3b6
PB
1839 }
1840
f1c17521
PB
1841 req->data = blk_try_blockalign(client->exp->blk, request->len);
1842 if (req->data == NULL) {
2fd2c840 1843 error_setg(errp, "No memory");
ee898b87 1844 return -ENOMEM;
f1c17521 1845 }
2d821488 1846 }
b626b51a 1847 if (request->type == NBD_CMD_WRITE) {
2fd2c840
VSO
1848 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1849 error_prepend(errp, "reading from socket failed: ");
ee898b87 1850 return -EIO;
a030b347 1851 }
29b6c3b3 1852 req->complete = true;
6fb2b972 1853
9588463e
VSO
1854 trace_nbd_co_receive_request_payload_received(request->handle,
1855 request->len);
a030b347 1856 }
29b6c3b3 1857
fed5f8f8
EB
1858 /* Sanity checks. */
1859 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
1860 (request->type == NBD_CMD_WRITE ||
1861 request->type == NBD_CMD_WRITE_ZEROES ||
1862 request->type == NBD_CMD_TRIM)) {
1863 error_setg(errp, "Export is read-only");
1864 return -EROFS;
1865 }
1866 if (request->from > client->exp->size ||
1867 request->from + request->len > client->exp->size) {
2fd2c840
VSO
1868 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1869 ", Size: %" PRIu64, request->from, request->len,
1870 (uint64_t)client->exp->size);
fed5f8f8
EB
1871 return (request->type == NBD_CMD_WRITE ||
1872 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
29b6c3b3 1873 }
5c54e7fa
VSO
1874 valid_flags = NBD_CMD_FLAG_FUA;
1875 if (request->type == NBD_CMD_READ && client->structured_reply) {
1876 valid_flags |= NBD_CMD_FLAG_DF;
1877 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
1878 valid_flags |= NBD_CMD_FLAG_NO_HOLE;
e7b1948d
VSO
1879 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
1880 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
ab7c548e 1881 }
5c54e7fa
VSO
1882 if (request->flags & ~valid_flags) {
1883 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
1884 nbd_cmd_lookup(request->type), request->flags);
ee898b87 1885 return -EINVAL;
1f4d6d18 1886 }
29b6c3b3 1887
ee898b87 1888 return 0;
a030b347
PB
1889}
1890
6a417599
VSO
1891/* Send simple reply without a payload, or a structured error
1892 * @error_msg is ignored if @ret >= 0
1893 * Returns 0 if connection is still live, -errno on failure to talk to client
1894 */
1895static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
1896 uint64_t handle,
1897 int ret,
1898 const char *error_msg,
1899 Error **errp)
1900{
1901 if (client->structured_reply && ret < 0) {
1902 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
1903 errp);
1904 } else {
1905 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
1906 NULL, 0, errp);
1907 }
1908}
1909
1910/* Handle NBD_CMD_READ request.
1911 * Return -errno if sending fails. Other errors are reported directly to the
1912 * client as an error reply. */
1913static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
1914 uint8_t *data, Error **errp)
1915{
1916 int ret;
1917 NBDExport *exp = client->exp;
1918
1919 assert(request->type == NBD_CMD_READ);
1920
1921 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1922 if (request->flags & NBD_CMD_FLAG_FUA) {
1923 ret = blk_co_flush(exp->blk);
1924 if (ret < 0) {
1925 return nbd_send_generic_reply(client, request->handle, ret,
1926 "flush failed", errp);
1927 }
1928 }
1929
1930 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
1931 request->len) {
1932 return nbd_co_send_sparse_read(client, request->handle, request->from,
1933 data, request->len, errp);
1934 }
1935
1936 ret = blk_pread(exp->blk, request->from + exp->dev_offset, data,
1937 request->len);
1938 if (ret < 0) {
1939 return nbd_send_generic_reply(client, request->handle, ret,
1940 "reading from file failed", errp);
1941 }
1942
1943 if (client->structured_reply) {
1944 if (request->len) {
1945 return nbd_co_send_structured_read(client, request->handle,
1946 request->from, data,
1947 request->len, true, errp);
1948 } else {
1949 return nbd_co_send_structured_done(client, request->handle, errp);
1950 }
1951 } else {
1952 return nbd_co_send_simple_reply(client, request->handle, 0,
1953 data, request->len, errp);
1954 }
1955}
1956
6f302e60
VSO
1957/* Handle NBD request.
1958 * Return -errno if sending fails. Other errors are reported directly to the
1959 * client as an error reply. */
1960static coroutine_fn int nbd_handle_request(NBDClient *client,
1961 NBDRequest *request,
1962 uint8_t *data, Error **errp)
1963{
1964 int ret;
1965 int flags;
1966 NBDExport *exp = client->exp;
1967 char *msg;
1968
1969 switch (request->type) {
1970 case NBD_CMD_READ:
1971 return nbd_do_cmd_read(client, request, data, errp);
1972
1973 case NBD_CMD_WRITE:
1974 flags = 0;
1975 if (request->flags & NBD_CMD_FLAG_FUA) {
1976 flags |= BDRV_REQ_FUA;
1977 }
1978 ret = blk_pwrite(exp->blk, request->from + exp->dev_offset,
1979 data, request->len, flags);
1980 return nbd_send_generic_reply(client, request->handle, ret,
1981 "writing to file failed", errp);
1982
1983 case NBD_CMD_WRITE_ZEROES:
1984 flags = 0;
1985 if (request->flags & NBD_CMD_FLAG_FUA) {
1986 flags |= BDRV_REQ_FUA;
1987 }
1988 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
1989 flags |= BDRV_REQ_MAY_UNMAP;
1990 }
1991 ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset,
1992 request->len, flags);
1993 return nbd_send_generic_reply(client, request->handle, ret,
1994 "writing to file failed", errp);
1995
1996 case NBD_CMD_DISC:
1997 /* unreachable, thanks to special case in nbd_co_receive_request() */
1998 abort();
1999
2000 case NBD_CMD_FLUSH:
2001 ret = blk_co_flush(exp->blk);
2002 return nbd_send_generic_reply(client, request->handle, ret,
2003 "flush failed", errp);
2004
2005 case NBD_CMD_TRIM:
2006 ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset,
2007 request->len);
65529782
EB
2008 if (ret == 0 && request->flags & NBD_CMD_FLAG_FUA) {
2009 ret = blk_co_flush(exp->blk);
2010 }
6f302e60
VSO
2011 return nbd_send_generic_reply(client, request->handle, ret,
2012 "discard failed", errp);
2013
e7b1948d 2014 case NBD_CMD_BLOCK_STATUS:
d8b20291
EB
2015 if (!request->len) {
2016 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2017 "need non-zero length", errp);
2018 }
e7b1948d
VSO
2019 if (client->export_meta.valid && client->export_meta.base_allocation) {
2020 return nbd_co_send_block_status(client, request->handle,
2021 blk_bs(exp->blk), request->from,
2022 request->len,
2023 NBD_META_ID_BASE_ALLOCATION, errp);
2024 } else {
2025 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2026 "CMD_BLOCK_STATUS not negotiated",
2027 errp);
2028 }
2029
6f302e60
VSO
2030 default:
2031 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2032 request->type);
2033 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2034 errp);
2035 g_free(msg);
2036 return ret;
2037 }
2038}
2039
ff82911c
PB
2040/* Owns a reference to the NBDClient passed as opaque. */
2041static coroutine_fn void nbd_trip(void *opaque)
75818250 2042{
262db388 2043 NBDClient *client = opaque;
315f78ab 2044 NBDRequestData *req;
ff82911c 2045 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
a0dc63a6 2046 int ret;
2fd2c840 2047 Error *local_err = NULL;
b2e3d87f 2048
9588463e 2049 trace_nbd_trip();
ff2b68aa 2050 if (client->closing) {
ff82911c 2051 nbd_client_put(client);
ff2b68aa
PB
2052 return;
2053 }
b2e3d87f 2054
ff2b68aa 2055 req = nbd_request_get(client);
2fd2c840 2056 ret = nbd_co_receive_request(req, &request, &local_err);
ee898b87 2057 client->recv_coroutine = NULL;
b2e3d87f 2058
d6268348
WC
2059 if (client->closing) {
2060 /*
2061 * The client may be closed when we are blocked in
2062 * nbd_co_receive_request()
2063 */
2064 goto done;
2065 }
2066
a0d7ce20
VSO
2067 nbd_client_receive_next_request(client);
2068 if (ret == -EIO) {
2069 goto disconnect;
2070 }
2071
2072 if (ret < 0) {
6a417599
VSO
2073 /* It wans't -EIO, so, according to nbd_co_receive_request()
2074 * semantics, we should return the error to the client. */
2075 Error *export_err = local_err;
2076
2077 local_err = NULL;
2078 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2079 error_get_pretty(export_err), &local_err);
2080 error_free(export_err);
6f302e60
VSO
2081 } else {
2082 ret = nbd_handle_request(client, &request, req->data, &local_err);
5c54e7fa
VSO
2083 }
2084 if (ret < 0) {
c7b97282 2085 error_prepend(&local_err, "Failed to send reply: ");
2fd2c840
VSO
2086 goto disconnect;
2087 }
2088
8c372a02
VSO
2089 /* We must disconnect after NBD_CMD_WRITE if we did not
2090 * read the payload.
2091 */
2fd2c840
VSO
2092 if (!req->complete) {
2093 error_setg(&local_err, "Request handling failed in intermediate state");
8c372a02 2094 goto disconnect;
b2e3d87f
NT
2095 }
2096
7fe7b68b 2097done:
262db388 2098 nbd_request_put(req);
ff82911c 2099 nbd_client_put(client);
262db388
PB
2100 return;
2101
8c372a02 2102disconnect:
2fd2c840
VSO
2103 if (local_err) {
2104 error_reportf_err(local_err, "Disconnect client, due to: ");
2105 }
72deddc5 2106 nbd_request_put(req);
0c9390d9 2107 client_close(client, true);
ff82911c 2108 nbd_client_put(client);
7a5ca864 2109}
af49bbbe 2110
ff82911c 2111static void nbd_client_receive_next_request(NBDClient *client)
958c717d 2112{
ff82911c
PB
2113 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2114 nbd_client_get(client);
2115 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2116 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
958c717d
HR
2117 }
2118}
2119
1a6245a5
FZ
2120static coroutine_fn void nbd_co_client_start(void *opaque)
2121{
c84087f2 2122 NBDClient *client = opaque;
1a6245a5 2123 NBDExport *exp = client->exp;
2fd2c840 2124 Error *local_err = NULL;
1a6245a5
FZ
2125
2126 if (exp) {
2127 nbd_export_get(exp);
df8ad9f1 2128 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1a6245a5 2129 }
df8ad9f1
EB
2130 qemu_co_mutex_init(&client->send_lock);
2131
2fd2c840
VSO
2132 if (nbd_negotiate(client, &local_err)) {
2133 if (local_err) {
2134 error_report_err(local_err);
2135 }
0c9390d9 2136 client_close(client, false);
c84087f2 2137 return;
1a6245a5 2138 }
ff82911c
PB
2139
2140 nbd_client_receive_next_request(client);
1a6245a5
FZ
2141}
2142
0c9390d9
EB
2143/*
2144 * Create a new client listener on the given export @exp, using the
2145 * given channel @sioc. Begin servicing it in a coroutine. When the
2146 * connection closes, call @close_fn with an indication of whether the
2147 * client completed negotiation.
2148 */
1c778ef7
DB
2149void nbd_client_new(NBDExport *exp,
2150 QIOChannelSocket *sioc,
f95910fe
DB
2151 QCryptoTLSCreds *tlscreds,
2152 const char *tlsaclname,
0c9390d9 2153 void (*close_fn)(NBDClient *, bool))
af49bbbe 2154{
1743b515 2155 NBDClient *client;
c84087f2 2156 Coroutine *co;
1a6245a5 2157
e8d3eb74 2158 client = g_new0(NBDClient, 1);
1743b515
PB
2159 client->refcount = 1;
2160 client->exp = exp;
f95910fe
DB
2161 client->tlscreds = tlscreds;
2162 if (tlscreds) {
2163 object_ref(OBJECT(client->tlscreds));
2164 }
2165 client->tlsaclname = g_strdup(tlsaclname);
1c778ef7
DB
2166 client->sioc = sioc;
2167 object_ref(OBJECT(client->sioc));
2168 client->ioc = QIO_CHANNEL(sioc);
2169 object_ref(OBJECT(client->ioc));
0c9390d9 2170 client->close_fn = close_fn;
2c8d9f06 2171
c84087f2
VSO
2172 co = qemu_coroutine_create(nbd_co_client_start, client);
2173 qemu_coroutine_enter(co);
af49bbbe 2174}