]> git.proxmox.com Git - mirror_qemu.git/blob - nbd/server.c
nbd/server: move nbd_co_send_structured_error up
[mirror_qemu.git] / nbd / server.c
1 /*
2 * Copyright (C) 2016-2018 Red Hat, Inc.
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 *
5 * Network Block Device Server 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
20 #include "qemu/osdep.h"
21 #include "qapi/error.h"
22 #include "trace.h"
23 #include "nbd-internal.h"
24
25 static int system_errno_to_nbd_errno(int err)
26 {
27 switch (err) {
28 case 0:
29 return NBD_SUCCESS;
30 case EPERM:
31 case EROFS:
32 return NBD_EPERM;
33 case EIO:
34 return NBD_EIO;
35 case ENOMEM:
36 return NBD_ENOMEM;
37 #ifdef EDQUOT
38 case EDQUOT:
39 #endif
40 case EFBIG:
41 case ENOSPC:
42 return NBD_ENOSPC;
43 case EOVERFLOW:
44 return NBD_EOVERFLOW;
45 case ESHUTDOWN:
46 return NBD_ESHUTDOWN;
47 case EINVAL:
48 default:
49 return NBD_EINVAL;
50 }
51 }
52
53 /* Definitions for opaque data types */
54
55 typedef struct NBDRequestData NBDRequestData;
56
57 struct NBDRequestData {
58 QSIMPLEQ_ENTRY(NBDRequestData) entry;
59 NBDClient *client;
60 uint8_t *data;
61 bool complete;
62 };
63
64 struct NBDExport {
65 int refcount;
66 void (*close)(NBDExport *exp);
67
68 BlockBackend *blk;
69 char *name;
70 char *description;
71 off_t dev_offset;
72 off_t size;
73 uint16_t nbdflags;
74 QTAILQ_HEAD(, NBDClient) clients;
75 QTAILQ_ENTRY(NBDExport) next;
76
77 AioContext *ctx;
78
79 BlockBackend *eject_notifier_blk;
80 Notifier eject_notifier;
81 };
82
83 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
84
85 struct NBDClient {
86 int refcount;
87 void (*close_fn)(NBDClient *client, bool negotiated);
88
89 NBDExport *exp;
90 QCryptoTLSCreds *tlscreds;
91 char *tlsaclname;
92 QIOChannelSocket *sioc; /* The underlying data channel */
93 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
94
95 Coroutine *recv_coroutine;
96
97 CoMutex send_lock;
98 Coroutine *send_coroutine;
99
100 QTAILQ_ENTRY(NBDClient) next;
101 int nb_requests;
102 bool closing;
103
104 bool structured_reply;
105
106 uint32_t opt; /* Current option being negotiated */
107 uint32_t optlen; /* remaining length of data in ioc for the option being
108 negotiated now */
109 };
110
111 static void nbd_client_receive_next_request(NBDClient *client);
112
113 /* Basic flow for negotiation
114
115 Server Client
116 Negotiate
117
118 or
119
120 Server Client
121 Negotiate #1
122 Option
123 Negotiate #2
124
125 ----
126
127 followed by
128
129 Server Client
130 Request
131 Response
132 Request
133 Response
134 ...
135 ...
136 Request (type == 2)
137
138 */
139
140 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
141 uint32_t type, uint32_t length)
142 {
143 stq_be_p(&rep->magic, NBD_REP_MAGIC);
144 stl_be_p(&rep->option, option);
145 stl_be_p(&rep->type, type);
146 stl_be_p(&rep->length, length);
147 }
148
149 /* Send a reply header, including length, but no payload.
150 * Return -errno on error, 0 on success. */
151 static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
152 uint32_t len, Error **errp)
153 {
154 NBDOptionReply rep;
155
156 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
157 type, nbd_rep_lookup(type), len);
158
159 assert(len < NBD_MAX_BUFFER_SIZE);
160
161 set_be_option_rep(&rep, client->opt, type, len);
162 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
163 }
164
165 /* Send a reply header with default 0 length.
166 * Return -errno on error, 0 on success. */
167 static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
168 Error **errp)
169 {
170 return nbd_negotiate_send_rep_len(client, type, 0, errp);
171 }
172
173 /* Send an error reply.
174 * Return -errno on error, 0 on success. */
175 static int GCC_FMT_ATTR(4, 0)
176 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
177 Error **errp, const char *fmt, va_list va)
178 {
179 char *msg;
180 int ret;
181 size_t len;
182
183 msg = g_strdup_vprintf(fmt, va);
184 len = strlen(msg);
185 assert(len < 4096);
186 trace_nbd_negotiate_send_rep_err(msg);
187 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
188 if (ret < 0) {
189 goto out;
190 }
191 if (nbd_write(client->ioc, msg, len, errp) < 0) {
192 error_prepend(errp, "write failed (error message): ");
193 ret = -EIO;
194 } else {
195 ret = 0;
196 }
197
198 out:
199 g_free(msg);
200 return ret;
201 }
202
203 /* Send an error reply.
204 * Return -errno on error, 0 on success. */
205 static int GCC_FMT_ATTR(4, 5)
206 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
207 Error **errp, const char *fmt, ...)
208 {
209 va_list va;
210 int ret;
211
212 va_start(va, fmt);
213 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
214 va_end(va);
215 return ret;
216 }
217
218 /* Drop remainder of the current option, and send a reply with the
219 * given error type and message. Return -errno on read or write
220 * failure; or 0 if connection is still live. */
221 static int GCC_FMT_ATTR(4, 5)
222 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
223 const char *fmt, ...)
224 {
225 int ret = nbd_drop(client->ioc, client->optlen, errp);
226 va_list va;
227
228 client->optlen = 0;
229 if (!ret) {
230 va_start(va, fmt);
231 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
232 va_end(va);
233 }
234 return ret;
235 }
236
237 /* Read size bytes from the unparsed payload of the current option.
238 * Return -errno on I/O error, 0 if option was completely handled by
239 * sending a reply about inconsistent lengths, or 1 on success. */
240 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
241 Error **errp)
242 {
243 if (size > client->optlen) {
244 return nbd_opt_drop(client, NBD_REP_ERR_INVALID, errp,
245 "Inconsistent lengths in option %s",
246 nbd_opt_lookup(client->opt));
247 }
248 client->optlen -= size;
249 return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1;
250 }
251
252 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
253 * Return -errno on error, 0 on success. */
254 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
255 Error **errp)
256 {
257 size_t name_len, desc_len;
258 uint32_t len;
259 const char *name = exp->name ? exp->name : "";
260 const char *desc = exp->description ? exp->description : "";
261 QIOChannel *ioc = client->ioc;
262 int ret;
263
264 trace_nbd_negotiate_send_rep_list(name, desc);
265 name_len = strlen(name);
266 desc_len = strlen(desc);
267 len = name_len + desc_len + sizeof(len);
268 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
269 if (ret < 0) {
270 return ret;
271 }
272
273 len = cpu_to_be32(name_len);
274 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
275 error_prepend(errp, "write failed (name length): ");
276 return -EINVAL;
277 }
278
279 if (nbd_write(ioc, name, name_len, errp) < 0) {
280 error_prepend(errp, "write failed (name buffer): ");
281 return -EINVAL;
282 }
283
284 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
285 error_prepend(errp, "write failed (description buffer): ");
286 return -EINVAL;
287 }
288
289 return 0;
290 }
291
292 /* Process the NBD_OPT_LIST command, with a potential series of replies.
293 * Return -errno on error, 0 on success. */
294 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
295 {
296 NBDExport *exp;
297 assert(client->opt == NBD_OPT_LIST);
298
299 /* For each export, send a NBD_REP_SERVER reply. */
300 QTAILQ_FOREACH(exp, &exports, next) {
301 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
302 return -EINVAL;
303 }
304 }
305 /* Finish with a NBD_REP_ACK. */
306 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
307 }
308
309 /* Send a reply to NBD_OPT_EXPORT_NAME.
310 * Return -errno on error, 0 on success. */
311 static int nbd_negotiate_handle_export_name(NBDClient *client,
312 uint16_t myflags, bool no_zeroes,
313 Error **errp)
314 {
315 char name[NBD_MAX_NAME_SIZE + 1];
316 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
317 size_t len;
318 int ret;
319
320 /* Client sends:
321 [20 .. xx] export name (length bytes)
322 Server replies:
323 [ 0 .. 7] size
324 [ 8 .. 9] export flags
325 [10 .. 133] reserved (0) [unless no_zeroes]
326 */
327 trace_nbd_negotiate_handle_export_name();
328 if (client->optlen >= sizeof(name)) {
329 error_setg(errp, "Bad length received");
330 return -EINVAL;
331 }
332 if (nbd_read(client->ioc, name, client->optlen, errp) < 0) {
333 error_prepend(errp, "read failed: ");
334 return -EIO;
335 }
336 name[client->optlen] = '\0';
337 client->optlen = 0;
338
339 trace_nbd_negotiate_handle_export_name_request(name);
340
341 client->exp = nbd_export_find(name);
342 if (!client->exp) {
343 error_setg(errp, "export not found");
344 return -EINVAL;
345 }
346
347 trace_nbd_negotiate_new_style_size_flags(client->exp->size,
348 client->exp->nbdflags | myflags);
349 stq_be_p(buf, client->exp->size);
350 stw_be_p(buf + 8, client->exp->nbdflags | myflags);
351 len = no_zeroes ? 10 : sizeof(buf);
352 ret = nbd_write(client->ioc, buf, len, errp);
353 if (ret < 0) {
354 error_prepend(errp, "write failed: ");
355 return ret;
356 }
357
358 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
359 nbd_export_get(client->exp);
360
361 return 0;
362 }
363
364 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
365 * The buffer does NOT include the info type prefix.
366 * Return -errno on error, 0 if ready to send more. */
367 static int nbd_negotiate_send_info(NBDClient *client,
368 uint16_t info, uint32_t length, void *buf,
369 Error **errp)
370 {
371 int rc;
372
373 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
374 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
375 sizeof(info) + length, errp);
376 if (rc < 0) {
377 return rc;
378 }
379 cpu_to_be16s(&info);
380 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
381 return -EIO;
382 }
383 if (nbd_write(client->ioc, buf, length, errp) < 0) {
384 return -EIO;
385 }
386 return 0;
387 }
388
389 /* nbd_reject_length: Handle any unexpected payload.
390 * @fatal requests that we quit talking to the client, even if we are able
391 * to successfully send an error reply.
392 * Return:
393 * -errno transmission error occurred or @fatal was requested, errp is set
394 * 0 error message successfully sent to client, errp is not set
395 */
396 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
397 {
398 int ret;
399
400 assert(client->optlen);
401 ret = nbd_opt_drop(client, NBD_REP_ERR_INVALID, errp,
402 "option '%s' has unexpected length",
403 nbd_opt_lookup(client->opt));
404 if (fatal && !ret) {
405 error_setg(errp, "option '%s' has unexpected length",
406 nbd_opt_lookup(client->opt));
407 return -EINVAL;
408 }
409 return ret;
410 }
411
412 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
413 * Return -errno on error, 0 if ready for next option, and 1 to move
414 * into transmission phase. */
415 static int nbd_negotiate_handle_info(NBDClient *client, uint16_t myflags,
416 Error **errp)
417 {
418 int rc;
419 char name[NBD_MAX_NAME_SIZE + 1];
420 NBDExport *exp;
421 uint16_t requests;
422 uint16_t request;
423 uint32_t namelen;
424 bool sendname = false;
425 bool blocksize = false;
426 uint32_t sizes[3];
427 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
428
429 /* Client sends:
430 4 bytes: L, name length (can be 0)
431 L bytes: export name
432 2 bytes: N, number of requests (can be 0)
433 N * 2 bytes: N requests
434 */
435 rc = nbd_opt_read(client, &namelen, sizeof(namelen), errp);
436 if (rc <= 0) {
437 return rc;
438 }
439 be32_to_cpus(&namelen);
440 if (namelen >= sizeof(name)) {
441 return nbd_opt_drop(client, NBD_REP_ERR_INVALID, errp,
442 "name too long for qemu");
443 }
444 rc = nbd_opt_read(client, name, namelen, errp);
445 if (rc <= 0) {
446 return rc;
447 }
448 name[namelen] = '\0';
449 trace_nbd_negotiate_handle_export_name_request(name);
450
451 rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
452 if (rc <= 0) {
453 return rc;
454 }
455 be16_to_cpus(&requests);
456 trace_nbd_negotiate_handle_info_requests(requests);
457 while (requests--) {
458 rc = nbd_opt_read(client, &request, sizeof(request), errp);
459 if (rc <= 0) {
460 return rc;
461 }
462 be16_to_cpus(&request);
463 trace_nbd_negotiate_handle_info_request(request,
464 nbd_info_lookup(request));
465 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
466 * everything else is either a request we don't know or
467 * something we send regardless of request */
468 switch (request) {
469 case NBD_INFO_NAME:
470 sendname = true;
471 break;
472 case NBD_INFO_BLOCK_SIZE:
473 blocksize = true;
474 break;
475 }
476 }
477 if (client->optlen) {
478 return nbd_reject_length(client, false, errp);
479 }
480
481 exp = nbd_export_find(name);
482 if (!exp) {
483 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
484 errp, "export '%s' not present",
485 name);
486 }
487
488 /* Don't bother sending NBD_INFO_NAME unless client requested it */
489 if (sendname) {
490 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
491 errp);
492 if (rc < 0) {
493 return rc;
494 }
495 }
496
497 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
498 * client request */
499 if (exp->description) {
500 size_t len = strlen(exp->description);
501
502 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
503 len, exp->description, errp);
504 if (rc < 0) {
505 return rc;
506 }
507 }
508
509 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
510 * according to whether the client requested it, and according to
511 * whether this is OPT_INFO or OPT_GO. */
512 /* minimum - 1 for back-compat, or 512 if client is new enough.
513 * TODO: consult blk_bs(blk)->bl.request_alignment? */
514 sizes[0] =
515 (client->opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
516 /* preferred - Hard-code to 4096 for now.
517 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
518 sizes[1] = 4096;
519 /* maximum - At most 32M, but smaller as appropriate. */
520 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
521 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
522 cpu_to_be32s(&sizes[0]);
523 cpu_to_be32s(&sizes[1]);
524 cpu_to_be32s(&sizes[2]);
525 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
526 sizeof(sizes), sizes, errp);
527 if (rc < 0) {
528 return rc;
529 }
530
531 /* Send NBD_INFO_EXPORT always */
532 trace_nbd_negotiate_new_style_size_flags(exp->size,
533 exp->nbdflags | myflags);
534 stq_be_p(buf, exp->size);
535 stw_be_p(buf + 8, exp->nbdflags | myflags);
536 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
537 sizeof(buf), buf, errp);
538 if (rc < 0) {
539 return rc;
540 }
541
542 /* If the client is just asking for NBD_OPT_INFO, but forgot to
543 * request block sizes, return an error.
544 * TODO: consult blk_bs(blk)->request_align, and only error if it
545 * is not 1? */
546 if (client->opt == NBD_OPT_INFO && !blocksize) {
547 return nbd_negotiate_send_rep_err(client,
548 NBD_REP_ERR_BLOCK_SIZE_REQD,
549 errp,
550 "request NBD_INFO_BLOCK_SIZE to "
551 "use this export");
552 }
553
554 /* Final reply */
555 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
556 if (rc < 0) {
557 return rc;
558 }
559
560 if (client->opt == NBD_OPT_GO) {
561 client->exp = exp;
562 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
563 nbd_export_get(client->exp);
564 rc = 1;
565 }
566 return rc;
567 }
568
569
570 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
571 * new channel for all further (now-encrypted) communication. */
572 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
573 Error **errp)
574 {
575 QIOChannel *ioc;
576 QIOChannelTLS *tioc;
577 struct NBDTLSHandshakeData data = { 0 };
578
579 assert(client->opt == NBD_OPT_STARTTLS);
580
581 trace_nbd_negotiate_handle_starttls();
582 ioc = client->ioc;
583
584 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
585 return NULL;
586 }
587
588 tioc = qio_channel_tls_new_server(ioc,
589 client->tlscreds,
590 client->tlsaclname,
591 errp);
592 if (!tioc) {
593 return NULL;
594 }
595
596 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
597 trace_nbd_negotiate_handle_starttls_handshake();
598 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
599 qio_channel_tls_handshake(tioc,
600 nbd_tls_handshake,
601 &data,
602 NULL,
603 NULL);
604
605 if (!data.complete) {
606 g_main_loop_run(data.loop);
607 }
608 g_main_loop_unref(data.loop);
609 if (data.error) {
610 object_unref(OBJECT(tioc));
611 error_propagate(errp, data.error);
612 return NULL;
613 }
614
615 return QIO_CHANNEL(tioc);
616 }
617
618 /* nbd_negotiate_options
619 * Process all NBD_OPT_* client option commands, during fixed newstyle
620 * negotiation.
621 * Return:
622 * -errno on error, errp is set
623 * 0 on successful negotiation, errp is not set
624 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
625 * errp is not set
626 */
627 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
628 Error **errp)
629 {
630 uint32_t flags;
631 bool fixedNewstyle = false;
632 bool no_zeroes = false;
633
634 /* Client sends:
635 [ 0 .. 3] client flags
636
637 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
638 [ 0 .. 7] NBD_OPTS_MAGIC
639 [ 8 .. 11] NBD option
640 [12 .. 15] Data length
641 ... Rest of request
642
643 [ 0 .. 7] NBD_OPTS_MAGIC
644 [ 8 .. 11] Second NBD option
645 [12 .. 15] Data length
646 ... Rest of request
647 */
648
649 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
650 error_prepend(errp, "read failed: ");
651 return -EIO;
652 }
653 be32_to_cpus(&flags);
654 trace_nbd_negotiate_options_flags(flags);
655 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
656 fixedNewstyle = true;
657 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
658 }
659 if (flags & NBD_FLAG_C_NO_ZEROES) {
660 no_zeroes = true;
661 flags &= ~NBD_FLAG_C_NO_ZEROES;
662 }
663 if (flags != 0) {
664 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
665 return -EINVAL;
666 }
667
668 while (1) {
669 int ret;
670 uint32_t option, length;
671 uint64_t magic;
672
673 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
674 error_prepend(errp, "read failed: ");
675 return -EINVAL;
676 }
677 magic = be64_to_cpu(magic);
678 trace_nbd_negotiate_options_check_magic(magic);
679 if (magic != NBD_OPTS_MAGIC) {
680 error_setg(errp, "Bad magic received");
681 return -EINVAL;
682 }
683
684 if (nbd_read(client->ioc, &option,
685 sizeof(option), errp) < 0) {
686 error_prepend(errp, "read failed: ");
687 return -EINVAL;
688 }
689 option = be32_to_cpu(option);
690 client->opt = option;
691
692 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
693 error_prepend(errp, "read failed: ");
694 return -EINVAL;
695 }
696 length = be32_to_cpu(length);
697 assert(!client->optlen);
698 client->optlen = length;
699
700 if (length > NBD_MAX_BUFFER_SIZE) {
701 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
702 length, NBD_MAX_BUFFER_SIZE);
703 return -EINVAL;
704 }
705
706 trace_nbd_negotiate_options_check_option(option,
707 nbd_opt_lookup(option));
708 if (client->tlscreds &&
709 client->ioc == (QIOChannel *)client->sioc) {
710 QIOChannel *tioc;
711 if (!fixedNewstyle) {
712 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
713 return -EINVAL;
714 }
715 switch (option) {
716 case NBD_OPT_STARTTLS:
717 if (length) {
718 /* Unconditionally drop the connection if the client
719 * can't start a TLS negotiation correctly */
720 return nbd_reject_length(client, true, errp);
721 }
722 tioc = nbd_negotiate_handle_starttls(client, errp);
723 if (!tioc) {
724 return -EIO;
725 }
726 ret = 0;
727 object_unref(OBJECT(client->ioc));
728 client->ioc = QIO_CHANNEL(tioc);
729 break;
730
731 case NBD_OPT_EXPORT_NAME:
732 /* No way to return an error to client, so drop connection */
733 error_setg(errp, "Option 0x%x not permitted before TLS",
734 option);
735 return -EINVAL;
736
737 default:
738 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD, errp,
739 "Option 0x%" PRIx32
740 "not permitted before TLS", option);
741 /* Let the client keep trying, unless they asked to
742 * quit. In this mode, we've already sent an error, so
743 * we can't ack the abort. */
744 if (option == NBD_OPT_ABORT) {
745 return 1;
746 }
747 break;
748 }
749 } else if (fixedNewstyle) {
750 switch (option) {
751 case NBD_OPT_LIST:
752 if (length) {
753 ret = nbd_reject_length(client, false, errp);
754 } else {
755 ret = nbd_negotiate_handle_list(client, errp);
756 }
757 break;
758
759 case NBD_OPT_ABORT:
760 /* NBD spec says we must try to reply before
761 * disconnecting, but that we must also tolerate
762 * guests that don't wait for our reply. */
763 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
764 return 1;
765
766 case NBD_OPT_EXPORT_NAME:
767 return nbd_negotiate_handle_export_name(client,
768 myflags, no_zeroes,
769 errp);
770
771 case NBD_OPT_INFO:
772 case NBD_OPT_GO:
773 ret = nbd_negotiate_handle_info(client, myflags, errp);
774 if (ret == 1) {
775 assert(option == NBD_OPT_GO);
776 return 0;
777 }
778 break;
779
780 case NBD_OPT_STARTTLS:
781 if (length) {
782 ret = nbd_reject_length(client, false, errp);
783 } else if (client->tlscreds) {
784 ret = nbd_negotiate_send_rep_err(client,
785 NBD_REP_ERR_INVALID, errp,
786 "TLS already enabled");
787 } else {
788 ret = nbd_negotiate_send_rep_err(client,
789 NBD_REP_ERR_POLICY, errp,
790 "TLS not configured");
791 }
792 break;
793
794 case NBD_OPT_STRUCTURED_REPLY:
795 if (length) {
796 ret = nbd_reject_length(client, false, errp);
797 } else if (client->structured_reply) {
798 ret = nbd_negotiate_send_rep_err(
799 client, NBD_REP_ERR_INVALID, errp,
800 "structured reply already negotiated");
801 } else {
802 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
803 client->structured_reply = true;
804 myflags |= NBD_FLAG_SEND_DF;
805 }
806 break;
807
808 default:
809 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
810 "Unsupported option %" PRIu32 " (%s)",
811 option, nbd_opt_lookup(option));
812 break;
813 }
814 } else {
815 /*
816 * If broken new-style we should drop the connection
817 * for anything except NBD_OPT_EXPORT_NAME
818 */
819 switch (option) {
820 case NBD_OPT_EXPORT_NAME:
821 return nbd_negotiate_handle_export_name(client,
822 myflags, no_zeroes,
823 errp);
824
825 default:
826 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
827 option, nbd_opt_lookup(option));
828 return -EINVAL;
829 }
830 }
831 if (ret < 0) {
832 return ret;
833 }
834 }
835 }
836
837 /* nbd_negotiate
838 * Return:
839 * -errno on error, errp is set
840 * 0 on successful negotiation, errp is not set
841 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
842 * errp is not set
843 */
844 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
845 {
846 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
847 int ret;
848 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
849 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
850 NBD_FLAG_SEND_WRITE_ZEROES);
851 bool oldStyle;
852
853 /* Old style negotiation header, no room for options
854 [ 0 .. 7] passwd ("NBDMAGIC")
855 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
856 [16 .. 23] size
857 [24 .. 27] export flags (zero-extended)
858 [28 .. 151] reserved (0)
859
860 New style negotiation header, client can send options
861 [ 0 .. 7] passwd ("NBDMAGIC")
862 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
863 [16 .. 17] server flags (0)
864 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
865 */
866
867 qio_channel_set_blocking(client->ioc, false, NULL);
868
869 trace_nbd_negotiate_begin();
870 memcpy(buf, "NBDMAGIC", 8);
871
872 oldStyle = client->exp != NULL && !client->tlscreds;
873 if (oldStyle) {
874 trace_nbd_negotiate_old_style(client->exp->size,
875 client->exp->nbdflags | myflags);
876 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
877 stq_be_p(buf + 16, client->exp->size);
878 stl_be_p(buf + 24, client->exp->nbdflags | myflags);
879
880 if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
881 error_prepend(errp, "write failed: ");
882 return -EINVAL;
883 }
884 } else {
885 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
886 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
887
888 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
889 error_prepend(errp, "write failed: ");
890 return -EINVAL;
891 }
892 ret = nbd_negotiate_options(client, myflags, errp);
893 if (ret != 0) {
894 if (ret < 0) {
895 error_prepend(errp, "option negotiation failed: ");
896 }
897 return ret;
898 }
899 }
900
901 assert(!client->optlen);
902 trace_nbd_negotiate_success();
903
904 return 0;
905 }
906
907 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
908 Error **errp)
909 {
910 uint8_t buf[NBD_REQUEST_SIZE];
911 uint32_t magic;
912 int ret;
913
914 ret = nbd_read(ioc, buf, sizeof(buf), errp);
915 if (ret < 0) {
916 return ret;
917 }
918
919 /* Request
920 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
921 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
922 [ 6 .. 7] type (NBD_CMD_READ, ...)
923 [ 8 .. 15] handle
924 [16 .. 23] from
925 [24 .. 27] len
926 */
927
928 magic = ldl_be_p(buf);
929 request->flags = lduw_be_p(buf + 4);
930 request->type = lduw_be_p(buf + 6);
931 request->handle = ldq_be_p(buf + 8);
932 request->from = ldq_be_p(buf + 16);
933 request->len = ldl_be_p(buf + 24);
934
935 trace_nbd_receive_request(magic, request->flags, request->type,
936 request->from, request->len);
937
938 if (magic != NBD_REQUEST_MAGIC) {
939 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
940 return -EINVAL;
941 }
942 return 0;
943 }
944
945 #define MAX_NBD_REQUESTS 16
946
947 void nbd_client_get(NBDClient *client)
948 {
949 client->refcount++;
950 }
951
952 void nbd_client_put(NBDClient *client)
953 {
954 if (--client->refcount == 0) {
955 /* The last reference should be dropped by client->close,
956 * which is called by client_close.
957 */
958 assert(client->closing);
959
960 qio_channel_detach_aio_context(client->ioc);
961 object_unref(OBJECT(client->sioc));
962 object_unref(OBJECT(client->ioc));
963 if (client->tlscreds) {
964 object_unref(OBJECT(client->tlscreds));
965 }
966 g_free(client->tlsaclname);
967 if (client->exp) {
968 QTAILQ_REMOVE(&client->exp->clients, client, next);
969 nbd_export_put(client->exp);
970 }
971 g_free(client);
972 }
973 }
974
975 static void client_close(NBDClient *client, bool negotiated)
976 {
977 if (client->closing) {
978 return;
979 }
980
981 client->closing = true;
982
983 /* Force requests to finish. They will drop their own references,
984 * then we'll close the socket and free the NBDClient.
985 */
986 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
987 NULL);
988
989 /* Also tell the client, so that they release their reference. */
990 if (client->close_fn) {
991 client->close_fn(client, negotiated);
992 }
993 }
994
995 static NBDRequestData *nbd_request_get(NBDClient *client)
996 {
997 NBDRequestData *req;
998
999 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1000 client->nb_requests++;
1001
1002 req = g_new0(NBDRequestData, 1);
1003 nbd_client_get(client);
1004 req->client = client;
1005 return req;
1006 }
1007
1008 static void nbd_request_put(NBDRequestData *req)
1009 {
1010 NBDClient *client = req->client;
1011
1012 if (req->data) {
1013 qemu_vfree(req->data);
1014 }
1015 g_free(req);
1016
1017 client->nb_requests--;
1018 nbd_client_receive_next_request(client);
1019
1020 nbd_client_put(client);
1021 }
1022
1023 static void blk_aio_attached(AioContext *ctx, void *opaque)
1024 {
1025 NBDExport *exp = opaque;
1026 NBDClient *client;
1027
1028 trace_nbd_blk_aio_attached(exp->name, ctx);
1029
1030 exp->ctx = ctx;
1031
1032 QTAILQ_FOREACH(client, &exp->clients, next) {
1033 qio_channel_attach_aio_context(client->ioc, ctx);
1034 if (client->recv_coroutine) {
1035 aio_co_schedule(ctx, client->recv_coroutine);
1036 }
1037 if (client->send_coroutine) {
1038 aio_co_schedule(ctx, client->send_coroutine);
1039 }
1040 }
1041 }
1042
1043 static void blk_aio_detach(void *opaque)
1044 {
1045 NBDExport *exp = opaque;
1046 NBDClient *client;
1047
1048 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1049
1050 QTAILQ_FOREACH(client, &exp->clients, next) {
1051 qio_channel_detach_aio_context(client->ioc);
1052 }
1053
1054 exp->ctx = NULL;
1055 }
1056
1057 static void nbd_eject_notifier(Notifier *n, void *data)
1058 {
1059 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1060 nbd_export_close(exp);
1061 }
1062
1063 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
1064 uint16_t nbdflags, void (*close)(NBDExport *),
1065 bool writethrough, BlockBackend *on_eject_blk,
1066 Error **errp)
1067 {
1068 AioContext *ctx;
1069 BlockBackend *blk;
1070 NBDExport *exp = g_new0(NBDExport, 1);
1071 uint64_t perm;
1072 int ret;
1073
1074 /*
1075 * NBD exports are used for non-shared storage migration. Make sure
1076 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1077 * access since the export could be available before migration handover.
1078 */
1079 ctx = bdrv_get_aio_context(bs);
1080 aio_context_acquire(ctx);
1081 bdrv_invalidate_cache(bs, NULL);
1082 aio_context_release(ctx);
1083
1084 /* Don't allow resize while the NBD server is running, otherwise we don't
1085 * care what happens with the node. */
1086 perm = BLK_PERM_CONSISTENT_READ;
1087 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1088 perm |= BLK_PERM_WRITE;
1089 }
1090 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1091 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1092 ret = blk_insert_bs(blk, bs, errp);
1093 if (ret < 0) {
1094 goto fail;
1095 }
1096 blk_set_enable_write_cache(blk, !writethrough);
1097
1098 exp->refcount = 1;
1099 QTAILQ_INIT(&exp->clients);
1100 exp->blk = blk;
1101 exp->dev_offset = dev_offset;
1102 exp->nbdflags = nbdflags;
1103 exp->size = size < 0 ? blk_getlength(blk) : size;
1104 if (exp->size < 0) {
1105 error_setg_errno(errp, -exp->size,
1106 "Failed to determine the NBD export's length");
1107 goto fail;
1108 }
1109 exp->size -= exp->size % BDRV_SECTOR_SIZE;
1110
1111 exp->close = close;
1112 exp->ctx = blk_get_aio_context(blk);
1113 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1114
1115 if (on_eject_blk) {
1116 blk_ref(on_eject_blk);
1117 exp->eject_notifier_blk = on_eject_blk;
1118 exp->eject_notifier.notify = nbd_eject_notifier;
1119 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1120 }
1121 return exp;
1122
1123 fail:
1124 blk_unref(blk);
1125 g_free(exp);
1126 return NULL;
1127 }
1128
1129 NBDExport *nbd_export_find(const char *name)
1130 {
1131 NBDExport *exp;
1132 QTAILQ_FOREACH(exp, &exports, next) {
1133 if (strcmp(name, exp->name) == 0) {
1134 return exp;
1135 }
1136 }
1137
1138 return NULL;
1139 }
1140
1141 void nbd_export_set_name(NBDExport *exp, const char *name)
1142 {
1143 if (exp->name == name) {
1144 return;
1145 }
1146
1147 nbd_export_get(exp);
1148 if (exp->name != NULL) {
1149 g_free(exp->name);
1150 exp->name = NULL;
1151 QTAILQ_REMOVE(&exports, exp, next);
1152 nbd_export_put(exp);
1153 }
1154 if (name != NULL) {
1155 nbd_export_get(exp);
1156 exp->name = g_strdup(name);
1157 QTAILQ_INSERT_TAIL(&exports, exp, next);
1158 }
1159 nbd_export_put(exp);
1160 }
1161
1162 void nbd_export_set_description(NBDExport *exp, const char *description)
1163 {
1164 g_free(exp->description);
1165 exp->description = g_strdup(description);
1166 }
1167
1168 void nbd_export_close(NBDExport *exp)
1169 {
1170 NBDClient *client, *next;
1171
1172 nbd_export_get(exp);
1173 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1174 client_close(client, true);
1175 }
1176 nbd_export_set_name(exp, NULL);
1177 nbd_export_set_description(exp, NULL);
1178 nbd_export_put(exp);
1179 }
1180
1181 void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1182 {
1183 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1184 nbd_export_close(exp);
1185 return;
1186 }
1187
1188 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1189
1190 error_setg(errp, "export '%s' still in use", exp->name);
1191 error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1192 }
1193
1194 void nbd_export_get(NBDExport *exp)
1195 {
1196 assert(exp->refcount > 0);
1197 exp->refcount++;
1198 }
1199
1200 void nbd_export_put(NBDExport *exp)
1201 {
1202 assert(exp->refcount > 0);
1203 if (exp->refcount == 1) {
1204 nbd_export_close(exp);
1205 }
1206
1207 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1208 * if someone calls nbd_export_put() on named export not through
1209 * nbd_export_set_name() when refcount is 1. So, let's assert that
1210 * it is > 0.
1211 */
1212 assert(exp->refcount > 0);
1213 if (--exp->refcount == 0) {
1214 assert(exp->name == NULL);
1215 assert(exp->description == NULL);
1216
1217 if (exp->close) {
1218 exp->close(exp);
1219 }
1220
1221 if (exp->blk) {
1222 if (exp->eject_notifier_blk) {
1223 notifier_remove(&exp->eject_notifier);
1224 blk_unref(exp->eject_notifier_blk);
1225 }
1226 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1227 blk_aio_detach, exp);
1228 blk_unref(exp->blk);
1229 exp->blk = NULL;
1230 }
1231
1232 g_free(exp);
1233 }
1234 }
1235
1236 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1237 {
1238 return exp->blk;
1239 }
1240
1241 void nbd_export_close_all(void)
1242 {
1243 NBDExport *exp, *next;
1244
1245 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1246 nbd_export_close(exp);
1247 }
1248 }
1249
1250 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1251 unsigned niov, Error **errp)
1252 {
1253 int ret;
1254
1255 g_assert(qemu_in_coroutine());
1256 qemu_co_mutex_lock(&client->send_lock);
1257 client->send_coroutine = qemu_coroutine_self();
1258
1259 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1260
1261 client->send_coroutine = NULL;
1262 qemu_co_mutex_unlock(&client->send_lock);
1263
1264 return ret;
1265 }
1266
1267 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1268 uint64_t handle)
1269 {
1270 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1271 stl_be_p(&reply->error, error);
1272 stq_be_p(&reply->handle, handle);
1273 }
1274
1275 static int nbd_co_send_simple_reply(NBDClient *client,
1276 uint64_t handle,
1277 uint32_t error,
1278 void *data,
1279 size_t len,
1280 Error **errp)
1281 {
1282 NBDSimpleReply reply;
1283 int nbd_err = system_errno_to_nbd_errno(error);
1284 struct iovec iov[] = {
1285 {.iov_base = &reply, .iov_len = sizeof(reply)},
1286 {.iov_base = data, .iov_len = len}
1287 };
1288
1289 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1290 len);
1291 set_be_simple_reply(&reply, nbd_err, handle);
1292
1293 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1294 }
1295
1296 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1297 uint16_t type, uint64_t handle, uint32_t length)
1298 {
1299 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1300 stw_be_p(&chunk->flags, flags);
1301 stw_be_p(&chunk->type, type);
1302 stq_be_p(&chunk->handle, handle);
1303 stl_be_p(&chunk->length, length);
1304 }
1305
1306 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1307 uint64_t handle,
1308 Error **errp)
1309 {
1310 NBDStructuredReplyChunk chunk;
1311 struct iovec iov[] = {
1312 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1313 };
1314
1315 trace_nbd_co_send_structured_done(handle);
1316 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1317
1318 return nbd_co_send_iov(client, iov, 1, errp);
1319 }
1320
1321 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1322 uint64_t handle,
1323 uint64_t offset,
1324 void *data,
1325 size_t size,
1326 bool final,
1327 Error **errp)
1328 {
1329 NBDStructuredReadData chunk;
1330 struct iovec iov[] = {
1331 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1332 {.iov_base = data, .iov_len = size}
1333 };
1334
1335 assert(size);
1336 trace_nbd_co_send_structured_read(handle, offset, data, size);
1337 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1338 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1339 sizeof(chunk) - sizeof(chunk.h) + size);
1340 stq_be_p(&chunk.offset, offset);
1341
1342 return nbd_co_send_iov(client, iov, 2, errp);
1343 }
1344
1345 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1346 uint64_t handle,
1347 uint32_t error,
1348 const char *msg,
1349 Error **errp)
1350 {
1351 NBDStructuredError chunk;
1352 int nbd_err = system_errno_to_nbd_errno(error);
1353 struct iovec iov[] = {
1354 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1355 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1356 };
1357
1358 assert(nbd_err);
1359 trace_nbd_co_send_structured_error(handle, nbd_err,
1360 nbd_err_lookup(nbd_err), msg ? msg : "");
1361 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1362 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1363 stl_be_p(&chunk.error, nbd_err);
1364 stw_be_p(&chunk.message_length, iov[1].iov_len);
1365
1366 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1367 }
1368
1369 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1370 uint64_t handle,
1371 uint64_t offset,
1372 uint8_t *data,
1373 size_t size,
1374 Error **errp)
1375 {
1376 int ret = 0;
1377 NBDExport *exp = client->exp;
1378 size_t progress = 0;
1379
1380 while (progress < size) {
1381 int64_t pnum;
1382 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1383 offset + progress,
1384 size - progress, &pnum, NULL,
1385 NULL);
1386 bool final;
1387
1388 if (status < 0) {
1389 error_setg_errno(errp, -status, "unable to check for holes");
1390 return status;
1391 }
1392 assert(pnum && pnum <= size - progress);
1393 final = progress + pnum == size;
1394 if (status & BDRV_BLOCK_ZERO) {
1395 NBDStructuredReadHole chunk;
1396 struct iovec iov[] = {
1397 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1398 };
1399
1400 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1401 pnum);
1402 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1403 NBD_REPLY_TYPE_OFFSET_HOLE,
1404 handle, sizeof(chunk) - sizeof(chunk.h));
1405 stq_be_p(&chunk.offset, offset + progress);
1406 stl_be_p(&chunk.length, pnum);
1407 ret = nbd_co_send_iov(client, iov, 1, errp);
1408 } else {
1409 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1410 data + progress, pnum);
1411 if (ret < 0) {
1412 error_setg_errno(errp, -ret, "reading from file failed");
1413 break;
1414 }
1415 ret = nbd_co_send_structured_read(client, handle, offset + progress,
1416 data + progress, pnum, final,
1417 errp);
1418 }
1419
1420 if (ret < 0) {
1421 break;
1422 }
1423 progress += pnum;
1424 }
1425 return ret;
1426 }
1427
1428 /* nbd_co_receive_request
1429 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1430 * connection right away, and any other negative value to report an error to
1431 * the client (although the caller may still need to disconnect after reporting
1432 * the error).
1433 */
1434 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1435 Error **errp)
1436 {
1437 NBDClient *client = req->client;
1438 int valid_flags;
1439
1440 g_assert(qemu_in_coroutine());
1441 assert(client->recv_coroutine == qemu_coroutine_self());
1442 if (nbd_receive_request(client->ioc, request, errp) < 0) {
1443 return -EIO;
1444 }
1445
1446 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
1447 nbd_cmd_lookup(request->type));
1448
1449 if (request->type != NBD_CMD_WRITE) {
1450 /* No payload, we are ready to read the next request. */
1451 req->complete = true;
1452 }
1453
1454 if (request->type == NBD_CMD_DISC) {
1455 /* Special case: we're going to disconnect without a reply,
1456 * whether or not flags, from, or len are bogus */
1457 return -EIO;
1458 }
1459
1460 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
1461 if (request->len > NBD_MAX_BUFFER_SIZE) {
1462 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1463 request->len, NBD_MAX_BUFFER_SIZE);
1464 return -EINVAL;
1465 }
1466
1467 req->data = blk_try_blockalign(client->exp->blk, request->len);
1468 if (req->data == NULL) {
1469 error_setg(errp, "No memory");
1470 return -ENOMEM;
1471 }
1472 }
1473 if (request->type == NBD_CMD_WRITE) {
1474 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1475 error_prepend(errp, "reading from socket failed: ");
1476 return -EIO;
1477 }
1478 req->complete = true;
1479
1480 trace_nbd_co_receive_request_payload_received(request->handle,
1481 request->len);
1482 }
1483
1484 /* Sanity checks. */
1485 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
1486 (request->type == NBD_CMD_WRITE ||
1487 request->type == NBD_CMD_WRITE_ZEROES ||
1488 request->type == NBD_CMD_TRIM)) {
1489 error_setg(errp, "Export is read-only");
1490 return -EROFS;
1491 }
1492 if (request->from > client->exp->size ||
1493 request->from + request->len > client->exp->size) {
1494 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1495 ", Size: %" PRIu64, request->from, request->len,
1496 (uint64_t)client->exp->size);
1497 return (request->type == NBD_CMD_WRITE ||
1498 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
1499 }
1500 valid_flags = NBD_CMD_FLAG_FUA;
1501 if (request->type == NBD_CMD_READ && client->structured_reply) {
1502 valid_flags |= NBD_CMD_FLAG_DF;
1503 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
1504 valid_flags |= NBD_CMD_FLAG_NO_HOLE;
1505 }
1506 if (request->flags & ~valid_flags) {
1507 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
1508 nbd_cmd_lookup(request->type), request->flags);
1509 return -EINVAL;
1510 }
1511
1512 return 0;
1513 }
1514
1515 /* Owns a reference to the NBDClient passed as opaque. */
1516 static coroutine_fn void nbd_trip(void *opaque)
1517 {
1518 NBDClient *client = opaque;
1519 NBDExport *exp = client->exp;
1520 NBDRequestData *req;
1521 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
1522 int ret;
1523 int flags;
1524 int reply_data_len = 0;
1525 Error *local_err = NULL;
1526 char *msg = NULL;
1527
1528 trace_nbd_trip();
1529 if (client->closing) {
1530 nbd_client_put(client);
1531 return;
1532 }
1533
1534 req = nbd_request_get(client);
1535 ret = nbd_co_receive_request(req, &request, &local_err);
1536 client->recv_coroutine = NULL;
1537 nbd_client_receive_next_request(client);
1538 if (ret == -EIO) {
1539 goto disconnect;
1540 }
1541
1542 if (ret < 0) {
1543 goto reply;
1544 }
1545
1546 if (client->closing) {
1547 /*
1548 * The client may be closed when we are blocked in
1549 * nbd_co_receive_request()
1550 */
1551 goto done;
1552 }
1553
1554 switch (request.type) {
1555 case NBD_CMD_READ:
1556 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1557 if (request.flags & NBD_CMD_FLAG_FUA) {
1558 ret = blk_co_flush(exp->blk);
1559 if (ret < 0) {
1560 error_setg_errno(&local_err, -ret, "flush failed");
1561 break;
1562 }
1563 }
1564
1565 if (client->structured_reply && !(request.flags & NBD_CMD_FLAG_DF) &&
1566 request.len) {
1567 ret = nbd_co_send_sparse_read(req->client, request.handle,
1568 request.from, req->data, request.len,
1569 &local_err);
1570 if (ret < 0) {
1571 goto reply;
1572 }
1573 goto done;
1574 }
1575
1576 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1577 req->data, request.len);
1578 if (ret < 0) {
1579 error_setg_errno(&local_err, -ret, "reading from file failed");
1580 break;
1581 }
1582
1583 reply_data_len = request.len;
1584
1585 break;
1586 case NBD_CMD_WRITE:
1587 flags = 0;
1588 if (request.flags & NBD_CMD_FLAG_FUA) {
1589 flags |= BDRV_REQ_FUA;
1590 }
1591 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1592 req->data, request.len, flags);
1593 if (ret < 0) {
1594 error_setg_errno(&local_err, -ret, "writing to file failed");
1595 }
1596
1597 break;
1598 case NBD_CMD_WRITE_ZEROES:
1599 flags = 0;
1600 if (request.flags & NBD_CMD_FLAG_FUA) {
1601 flags |= BDRV_REQ_FUA;
1602 }
1603 if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {
1604 flags |= BDRV_REQ_MAY_UNMAP;
1605 }
1606 ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,
1607 request.len, flags);
1608 if (ret < 0) {
1609 error_setg_errno(&local_err, -ret, "writing to file failed");
1610 }
1611
1612 break;
1613 case NBD_CMD_DISC:
1614 /* unreachable, thanks to special case in nbd_co_receive_request() */
1615 abort();
1616
1617 case NBD_CMD_FLUSH:
1618 ret = blk_co_flush(exp->blk);
1619 if (ret < 0) {
1620 error_setg_errno(&local_err, -ret, "flush failed");
1621 }
1622
1623 break;
1624 case NBD_CMD_TRIM:
1625 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1626 request.len);
1627 if (ret < 0) {
1628 error_setg_errno(&local_err, -ret, "discard failed");
1629 }
1630
1631 break;
1632 default:
1633 error_setg(&local_err, "invalid request type (%" PRIu32 ") received",
1634 request.type);
1635 ret = -EINVAL;
1636 }
1637
1638 reply:
1639 if (local_err) {
1640 /* If we get here, local_err was not a fatal error, and should be sent
1641 * to the client. */
1642 assert(ret < 0);
1643 msg = g_strdup(error_get_pretty(local_err));
1644 error_report_err(local_err);
1645 local_err = NULL;
1646 }
1647
1648 if (client->structured_reply &&
1649 (ret < 0 || request.type == NBD_CMD_READ)) {
1650 if (ret < 0) {
1651 ret = nbd_co_send_structured_error(req->client, request.handle,
1652 -ret, msg, &local_err);
1653 } else if (reply_data_len) {
1654 ret = nbd_co_send_structured_read(req->client, request.handle,
1655 request.from, req->data,
1656 reply_data_len, true,
1657 &local_err);
1658 } else {
1659 ret = nbd_co_send_structured_done(req->client, request.handle,
1660 &local_err);
1661 }
1662 } else {
1663 ret = nbd_co_send_simple_reply(req->client, request.handle,
1664 ret < 0 ? -ret : 0,
1665 req->data, reply_data_len, &local_err);
1666 }
1667 g_free(msg);
1668 if (ret < 0) {
1669 error_prepend(&local_err, "Failed to send reply: ");
1670 goto disconnect;
1671 }
1672
1673 /* We must disconnect after NBD_CMD_WRITE if we did not
1674 * read the payload.
1675 */
1676 if (!req->complete) {
1677 error_setg(&local_err, "Request handling failed in intermediate state");
1678 goto disconnect;
1679 }
1680
1681 done:
1682 nbd_request_put(req);
1683 nbd_client_put(client);
1684 return;
1685
1686 disconnect:
1687 if (local_err) {
1688 error_reportf_err(local_err, "Disconnect client, due to: ");
1689 }
1690 nbd_request_put(req);
1691 client_close(client, true);
1692 nbd_client_put(client);
1693 }
1694
1695 static void nbd_client_receive_next_request(NBDClient *client)
1696 {
1697 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
1698 nbd_client_get(client);
1699 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
1700 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
1701 }
1702 }
1703
1704 static coroutine_fn void nbd_co_client_start(void *opaque)
1705 {
1706 NBDClient *client = opaque;
1707 NBDExport *exp = client->exp;
1708 Error *local_err = NULL;
1709
1710 if (exp) {
1711 nbd_export_get(exp);
1712 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1713 }
1714 qemu_co_mutex_init(&client->send_lock);
1715
1716 if (nbd_negotiate(client, &local_err)) {
1717 if (local_err) {
1718 error_report_err(local_err);
1719 }
1720 client_close(client, false);
1721 return;
1722 }
1723
1724 nbd_client_receive_next_request(client);
1725 }
1726
1727 /*
1728 * Create a new client listener on the given export @exp, using the
1729 * given channel @sioc. Begin servicing it in a coroutine. When the
1730 * connection closes, call @close_fn with an indication of whether the
1731 * client completed negotiation.
1732 */
1733 void nbd_client_new(NBDExport *exp,
1734 QIOChannelSocket *sioc,
1735 QCryptoTLSCreds *tlscreds,
1736 const char *tlsaclname,
1737 void (*close_fn)(NBDClient *, bool))
1738 {
1739 NBDClient *client;
1740 Coroutine *co;
1741
1742 client = g_new0(NBDClient, 1);
1743 client->refcount = 1;
1744 client->exp = exp;
1745 client->tlscreds = tlscreds;
1746 if (tlscreds) {
1747 object_ref(OBJECT(client->tlscreds));
1748 }
1749 client->tlsaclname = g_strdup(tlsaclname);
1750 client->sioc = sioc;
1751 object_ref(OBJECT(client->sioc));
1752 client->ioc = QIO_CHANNEL(sioc);
1753 object_ref(OBJECT(client->ioc));
1754 client->close_fn = close_fn;
1755
1756 co = qemu_coroutine_create(nbd_co_client_start, client);
1757 qemu_coroutine_enter(co);
1758 }