]> git.proxmox.com Git - mirror_qemu.git/blob - nbd/server.c
nbd: Refactor reply to NBD_OPT_EXPORT_NAME
[mirror_qemu.git] / nbd / server.c
1 /*
2 * Copyright (C) 2016-2017 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 ESHUTDOWN:
44 return NBD_ESHUTDOWN;
45 case EINVAL:
46 default:
47 return NBD_EINVAL;
48 }
49 }
50
51 /* Definitions for opaque data types */
52
53 typedef struct NBDRequestData NBDRequestData;
54
55 struct NBDRequestData {
56 QSIMPLEQ_ENTRY(NBDRequestData) entry;
57 NBDClient *client;
58 uint8_t *data;
59 bool complete;
60 };
61
62 struct NBDExport {
63 int refcount;
64 void (*close)(NBDExport *exp);
65
66 BlockBackend *blk;
67 char *name;
68 char *description;
69 off_t dev_offset;
70 off_t size;
71 uint16_t nbdflags;
72 QTAILQ_HEAD(, NBDClient) clients;
73 QTAILQ_ENTRY(NBDExport) next;
74
75 AioContext *ctx;
76
77 BlockBackend *eject_notifier_blk;
78 Notifier eject_notifier;
79 };
80
81 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
82
83 struct NBDClient {
84 int refcount;
85 void (*close_fn)(NBDClient *client, bool negotiated);
86
87 NBDExport *exp;
88 QCryptoTLSCreds *tlscreds;
89 char *tlsaclname;
90 QIOChannelSocket *sioc; /* The underlying data channel */
91 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
92
93 Coroutine *recv_coroutine;
94
95 CoMutex send_lock;
96 Coroutine *send_coroutine;
97
98 QTAILQ_ENTRY(NBDClient) next;
99 int nb_requests;
100 bool closing;
101 };
102
103 /* That's all folks */
104
105 static void nbd_client_receive_next_request(NBDClient *client);
106
107 /* Basic flow for negotiation
108
109 Server Client
110 Negotiate
111
112 or
113
114 Server Client
115 Negotiate #1
116 Option
117 Negotiate #2
118
119 ----
120
121 followed by
122
123 Server Client
124 Request
125 Response
126 Request
127 Response
128 ...
129 ...
130 Request (type == 2)
131
132 */
133
134 /* Send a reply header, including length, but no payload.
135 * Return -errno on error, 0 on success. */
136 static int nbd_negotiate_send_rep_len(QIOChannel *ioc, uint32_t type,
137 uint32_t opt, uint32_t len, Error **errp)
138 {
139 uint64_t magic;
140
141 trace_nbd_negotiate_send_rep_len(opt, nbd_opt_lookup(opt),
142 type, nbd_rep_lookup(type), len);
143
144 magic = cpu_to_be64(NBD_REP_MAGIC);
145 if (nbd_write(ioc, &magic, sizeof(magic), errp) < 0) {
146 error_prepend(errp, "write failed (rep magic): ");
147 return -EINVAL;
148 }
149
150 opt = cpu_to_be32(opt);
151 if (nbd_write(ioc, &opt, sizeof(opt), errp) < 0) {
152 error_prepend(errp, "write failed (rep opt): ");
153 return -EINVAL;
154 }
155
156 type = cpu_to_be32(type);
157 if (nbd_write(ioc, &type, sizeof(type), errp) < 0) {
158 error_prepend(errp, "write failed (rep type): ");
159 return -EINVAL;
160 }
161
162 len = cpu_to_be32(len);
163 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
164 error_prepend(errp, "write failed (rep data length): ");
165 return -EINVAL;
166 }
167 return 0;
168 }
169
170 /* Send a reply header with default 0 length.
171 * Return -errno on error, 0 on success. */
172 static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt,
173 Error **errp)
174 {
175 return nbd_negotiate_send_rep_len(ioc, type, opt, 0, errp);
176 }
177
178 /* Send an error reply.
179 * Return -errno on error, 0 on success. */
180 static int GCC_FMT_ATTR(5, 6)
181 nbd_negotiate_send_rep_err(QIOChannel *ioc, uint32_t type,
182 uint32_t opt, Error **errp, const char *fmt, ...)
183 {
184 va_list va;
185 char *msg;
186 int ret;
187 size_t len;
188
189 va_start(va, fmt);
190 msg = g_strdup_vprintf(fmt, va);
191 va_end(va);
192 len = strlen(msg);
193 assert(len < 4096);
194 trace_nbd_negotiate_send_rep_err(msg);
195 ret = nbd_negotiate_send_rep_len(ioc, type, opt, len, errp);
196 if (ret < 0) {
197 goto out;
198 }
199 if (nbd_write(ioc, msg, len, errp) < 0) {
200 error_prepend(errp, "write failed (error message): ");
201 ret = -EIO;
202 } else {
203 ret = 0;
204 }
205
206 out:
207 g_free(msg);
208 return ret;
209 }
210
211 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
212 * Return -errno on error, 0 on success. */
213 static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp,
214 Error **errp)
215 {
216 size_t name_len, desc_len;
217 uint32_t len;
218 const char *name = exp->name ? exp->name : "";
219 const char *desc = exp->description ? exp->description : "";
220 int ret;
221
222 trace_nbd_negotiate_send_rep_list(name, desc);
223 name_len = strlen(name);
224 desc_len = strlen(desc);
225 len = name_len + desc_len + sizeof(len);
226 ret = nbd_negotiate_send_rep_len(ioc, NBD_REP_SERVER, NBD_OPT_LIST, len,
227 errp);
228 if (ret < 0) {
229 return ret;
230 }
231
232 len = cpu_to_be32(name_len);
233 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
234 error_prepend(errp, "write failed (name length): ");
235 return -EINVAL;
236 }
237
238 if (nbd_write(ioc, name, name_len, errp) < 0) {
239 error_prepend(errp, "write failed (name buffer): ");
240 return -EINVAL;
241 }
242
243 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
244 error_prepend(errp, "write failed (description buffer): ");
245 return -EINVAL;
246 }
247
248 return 0;
249 }
250
251 /* Process the NBD_OPT_LIST command, with a potential series of replies.
252 * Return -errno on error, 0 on success. */
253 static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length,
254 Error **errp)
255 {
256 NBDExport *exp;
257
258 if (length) {
259 if (nbd_drop(client->ioc, length, errp) < 0) {
260 return -EIO;
261 }
262 return nbd_negotiate_send_rep_err(client->ioc,
263 NBD_REP_ERR_INVALID, NBD_OPT_LIST,
264 errp,
265 "OPT_LIST should not have length");
266 }
267
268 /* For each export, send a NBD_REP_SERVER reply. */
269 QTAILQ_FOREACH(exp, &exports, next) {
270 if (nbd_negotiate_send_rep_list(client->ioc, exp, errp)) {
271 return -EINVAL;
272 }
273 }
274 /* Finish with a NBD_REP_ACK. */
275 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST, errp);
276 }
277
278 static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length,
279 uint16_t myflags, bool no_zeroes,
280 Error **errp)
281 {
282 char name[NBD_MAX_NAME_SIZE + 1];
283 char buf[8 + 4 + 124] = "";
284 size_t len;
285 int ret;
286
287 /* Client sends:
288 [20 .. xx] export name (length bytes)
289 */
290 trace_nbd_negotiate_handle_export_name();
291 if (length >= sizeof(name)) {
292 error_setg(errp, "Bad length received");
293 return -EINVAL;
294 }
295 if (nbd_read(client->ioc, name, length, errp) < 0) {
296 error_prepend(errp, "read failed: ");
297 return -EINVAL;
298 }
299 name[length] = '\0';
300
301 trace_nbd_negotiate_handle_export_name_request(name);
302
303 client->exp = nbd_export_find(name);
304 if (!client->exp) {
305 error_setg(errp, "export not found");
306 return -EINVAL;
307 }
308
309 trace_nbd_negotiate_new_style_size_flags(client->exp->size,
310 client->exp->nbdflags | myflags);
311 stq_be_p(buf, client->exp->size);
312 stw_be_p(buf + 8, client->exp->nbdflags | myflags);
313 len = no_zeroes ? 10 : sizeof(buf);
314 ret = nbd_write(client->ioc, buf, len, errp);
315 if (ret < 0) {
316 error_prepend(errp, "write failed: ");
317 return ret;
318 }
319
320 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
321 nbd_export_get(client->exp);
322
323 return 0;
324 }
325
326 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
327 * new channel for all further (now-encrypted) communication. */
328 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
329 uint32_t length,
330 Error **errp)
331 {
332 QIOChannel *ioc;
333 QIOChannelTLS *tioc;
334 struct NBDTLSHandshakeData data = { 0 };
335
336 trace_nbd_negotiate_handle_starttls();
337 ioc = client->ioc;
338 if (length) {
339 if (nbd_drop(ioc, length, errp) < 0) {
340 return NULL;
341 }
342 nbd_negotiate_send_rep_err(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS,
343 errp,
344 "OPT_STARTTLS should not have length");
345 return NULL;
346 }
347
348 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
349 NBD_OPT_STARTTLS, errp) < 0) {
350 return NULL;
351 }
352
353 tioc = qio_channel_tls_new_server(ioc,
354 client->tlscreds,
355 client->tlsaclname,
356 errp);
357 if (!tioc) {
358 return NULL;
359 }
360
361 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
362 trace_nbd_negotiate_handle_starttls_handshake();
363 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
364 qio_channel_tls_handshake(tioc,
365 nbd_tls_handshake,
366 &data,
367 NULL);
368
369 if (!data.complete) {
370 g_main_loop_run(data.loop);
371 }
372 g_main_loop_unref(data.loop);
373 if (data.error) {
374 object_unref(OBJECT(tioc));
375 error_propagate(errp, data.error);
376 return NULL;
377 }
378
379 return QIO_CHANNEL(tioc);
380 }
381
382 /* nbd_negotiate_options
383 * Process all NBD_OPT_* client option commands.
384 * Return:
385 * -errno on error, errp is set
386 * 0 on successful negotiation, errp is not set
387 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
388 * errp is not set
389 */
390 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
391 Error **errp)
392 {
393 uint32_t flags;
394 bool fixedNewstyle = false;
395 bool no_zeroes = false;
396
397 /* Client sends:
398 [ 0 .. 3] client flags
399
400 Then we loop until NBD_OPT_EXPORT_NAME:
401 [ 0 .. 7] NBD_OPTS_MAGIC
402 [ 8 .. 11] NBD option
403 [12 .. 15] Data length
404 ... Rest of request
405
406 [ 0 .. 7] NBD_OPTS_MAGIC
407 [ 8 .. 11] Second NBD option
408 [12 .. 15] Data length
409 ... Rest of request
410 */
411
412 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
413 error_prepend(errp, "read failed: ");
414 return -EIO;
415 }
416 be32_to_cpus(&flags);
417 trace_nbd_negotiate_options_flags(flags);
418 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
419 fixedNewstyle = true;
420 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
421 }
422 if (flags & NBD_FLAG_C_NO_ZEROES) {
423 no_zeroes = true;
424 flags &= ~NBD_FLAG_C_NO_ZEROES;
425 }
426 if (flags != 0) {
427 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
428 return -EINVAL;
429 }
430
431 while (1) {
432 int ret;
433 uint32_t option, length;
434 uint64_t magic;
435
436 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
437 error_prepend(errp, "read failed: ");
438 return -EINVAL;
439 }
440 magic = be64_to_cpu(magic);
441 trace_nbd_negotiate_options_check_magic(magic);
442 if (magic != NBD_OPTS_MAGIC) {
443 error_setg(errp, "Bad magic received");
444 return -EINVAL;
445 }
446
447 if (nbd_read(client->ioc, &option,
448 sizeof(option), errp) < 0) {
449 error_prepend(errp, "read failed: ");
450 return -EINVAL;
451 }
452 option = be32_to_cpu(option);
453
454 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
455 error_prepend(errp, "read failed: ");
456 return -EINVAL;
457 }
458 length = be32_to_cpu(length);
459
460 trace_nbd_negotiate_options_check_option(option,
461 nbd_opt_lookup(option));
462 if (client->tlscreds &&
463 client->ioc == (QIOChannel *)client->sioc) {
464 QIOChannel *tioc;
465 if (!fixedNewstyle) {
466 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
467 return -EINVAL;
468 }
469 switch (option) {
470 case NBD_OPT_STARTTLS:
471 tioc = nbd_negotiate_handle_starttls(client, length, errp);
472 if (!tioc) {
473 return -EIO;
474 }
475 object_unref(OBJECT(client->ioc));
476 client->ioc = QIO_CHANNEL(tioc);
477 break;
478
479 case NBD_OPT_EXPORT_NAME:
480 /* No way to return an error to client, so drop connection */
481 error_setg(errp, "Option 0x%x not permitted before TLS",
482 option);
483 return -EINVAL;
484
485 default:
486 if (nbd_drop(client->ioc, length, errp) < 0) {
487 return -EIO;
488 }
489 ret = nbd_negotiate_send_rep_err(client->ioc,
490 NBD_REP_ERR_TLS_REQD,
491 option, errp,
492 "Option 0x%" PRIx32
493 "not permitted before TLS",
494 option);
495 if (ret < 0) {
496 return ret;
497 }
498 /* Let the client keep trying, unless they asked to
499 * quit. In this mode, we've already sent an error, so
500 * we can't ack the abort. */
501 if (option == NBD_OPT_ABORT) {
502 return 1;
503 }
504 break;
505 }
506 } else if (fixedNewstyle) {
507 switch (option) {
508 case NBD_OPT_LIST:
509 ret = nbd_negotiate_handle_list(client, length, errp);
510 if (ret < 0) {
511 return ret;
512 }
513 break;
514
515 case NBD_OPT_ABORT:
516 /* NBD spec says we must try to reply before
517 * disconnecting, but that we must also tolerate
518 * guests that don't wait for our reply. */
519 nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, option, NULL);
520 return 1;
521
522 case NBD_OPT_EXPORT_NAME:
523 return nbd_negotiate_handle_export_name(client, length,
524 myflags, no_zeroes,
525 errp);
526
527 case NBD_OPT_STARTTLS:
528 if (nbd_drop(client->ioc, length, errp) < 0) {
529 return -EIO;
530 }
531 if (client->tlscreds) {
532 ret = nbd_negotiate_send_rep_err(client->ioc,
533 NBD_REP_ERR_INVALID,
534 option, errp,
535 "TLS already enabled");
536 } else {
537 ret = nbd_negotiate_send_rep_err(client->ioc,
538 NBD_REP_ERR_POLICY,
539 option, errp,
540 "TLS not configured");
541 }
542 if (ret < 0) {
543 return ret;
544 }
545 break;
546 default:
547 if (nbd_drop(client->ioc, length, errp) < 0) {
548 return -EIO;
549 }
550 ret = nbd_negotiate_send_rep_err(client->ioc,
551 NBD_REP_ERR_UNSUP,
552 option, errp,
553 "Unsupported option 0x%"
554 PRIx32 " (%s)", option,
555 nbd_opt_lookup(option));
556 if (ret < 0) {
557 return ret;
558 }
559 break;
560 }
561 } else {
562 /*
563 * If broken new-style we should drop the connection
564 * for anything except NBD_OPT_EXPORT_NAME
565 */
566 switch (option) {
567 case NBD_OPT_EXPORT_NAME:
568 return nbd_negotiate_handle_export_name(client, length,
569 myflags, no_zeroes,
570 errp);
571
572 default:
573 error_setg(errp, "Unsupported option 0x%" PRIx32 " (%s)",
574 option, nbd_opt_lookup(option));
575 return -EINVAL;
576 }
577 }
578 }
579 }
580
581 /* nbd_negotiate
582 * Return:
583 * -errno on error, errp is set
584 * 0 on successful negotiation, errp is not set
585 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
586 * errp is not set
587 */
588 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
589 {
590 char buf[8 + 8 + 8 + 128];
591 int ret;
592 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
593 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
594 NBD_FLAG_SEND_WRITE_ZEROES);
595 bool oldStyle;
596
597 /* Old style negotiation header without options
598 [ 0 .. 7] passwd ("NBDMAGIC")
599 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
600 [16 .. 23] size
601 [24 .. 25] server flags (0)
602 [26 .. 27] export flags
603 [28 .. 151] reserved (0)
604
605 New style negotiation header with options
606 [ 0 .. 7] passwd ("NBDMAGIC")
607 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
608 [16 .. 17] server flags (0)
609 ....options sent, ending in NBD_OPT_EXPORT_NAME....
610 */
611
612 qio_channel_set_blocking(client->ioc, false, NULL);
613
614 trace_nbd_negotiate_begin();
615 memset(buf, 0, sizeof(buf));
616 memcpy(buf, "NBDMAGIC", 8);
617
618 oldStyle = client->exp != NULL && !client->tlscreds;
619 if (oldStyle) {
620 trace_nbd_negotiate_old_style(client->exp->size,
621 client->exp->nbdflags | myflags);
622 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
623 stq_be_p(buf + 16, client->exp->size);
624 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
625
626 if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
627 error_prepend(errp, "write failed: ");
628 return -EINVAL;
629 }
630 } else {
631 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
632 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
633
634 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
635 error_prepend(errp, "write failed: ");
636 return -EINVAL;
637 }
638 ret = nbd_negotiate_options(client, myflags, errp);
639 if (ret != 0) {
640 if (ret < 0) {
641 error_prepend(errp, "option negotiation failed: ");
642 }
643 return ret;
644 }
645 }
646
647 trace_nbd_negotiate_success();
648
649 return 0;
650 }
651
652 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
653 Error **errp)
654 {
655 uint8_t buf[NBD_REQUEST_SIZE];
656 uint32_t magic;
657 int ret;
658
659 ret = nbd_read(ioc, buf, sizeof(buf), errp);
660 if (ret < 0) {
661 return ret;
662 }
663
664 /* Request
665 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
666 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
667 [ 6 .. 7] type (NBD_CMD_READ, ...)
668 [ 8 .. 15] handle
669 [16 .. 23] from
670 [24 .. 27] len
671 */
672
673 magic = ldl_be_p(buf);
674 request->flags = lduw_be_p(buf + 4);
675 request->type = lduw_be_p(buf + 6);
676 request->handle = ldq_be_p(buf + 8);
677 request->from = ldq_be_p(buf + 16);
678 request->len = ldl_be_p(buf + 24);
679
680 trace_nbd_receive_request(magic, request->flags, request->type,
681 request->from, request->len);
682
683 if (magic != NBD_REQUEST_MAGIC) {
684 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
685 return -EINVAL;
686 }
687 return 0;
688 }
689
690 static int nbd_send_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
691 {
692 uint8_t buf[NBD_REPLY_SIZE];
693
694 reply->error = system_errno_to_nbd_errno(reply->error);
695
696 trace_nbd_send_reply(reply->error, reply->handle);
697
698 /* Reply
699 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
700 [ 4 .. 7] error (0 == no error)
701 [ 7 .. 15] handle
702 */
703 stl_be_p(buf, NBD_REPLY_MAGIC);
704 stl_be_p(buf + 4, reply->error);
705 stq_be_p(buf + 8, reply->handle);
706
707 return nbd_write(ioc, buf, sizeof(buf), errp);
708 }
709
710 #define MAX_NBD_REQUESTS 16
711
712 void nbd_client_get(NBDClient *client)
713 {
714 client->refcount++;
715 }
716
717 void nbd_client_put(NBDClient *client)
718 {
719 if (--client->refcount == 0) {
720 /* The last reference should be dropped by client->close,
721 * which is called by client_close.
722 */
723 assert(client->closing);
724
725 qio_channel_detach_aio_context(client->ioc);
726 object_unref(OBJECT(client->sioc));
727 object_unref(OBJECT(client->ioc));
728 if (client->tlscreds) {
729 object_unref(OBJECT(client->tlscreds));
730 }
731 g_free(client->tlsaclname);
732 if (client->exp) {
733 QTAILQ_REMOVE(&client->exp->clients, client, next);
734 nbd_export_put(client->exp);
735 }
736 g_free(client);
737 }
738 }
739
740 static void client_close(NBDClient *client, bool negotiated)
741 {
742 if (client->closing) {
743 return;
744 }
745
746 client->closing = true;
747
748 /* Force requests to finish. They will drop their own references,
749 * then we'll close the socket and free the NBDClient.
750 */
751 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
752 NULL);
753
754 /* Also tell the client, so that they release their reference. */
755 if (client->close_fn) {
756 client->close_fn(client, negotiated);
757 }
758 }
759
760 static NBDRequestData *nbd_request_get(NBDClient *client)
761 {
762 NBDRequestData *req;
763
764 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
765 client->nb_requests++;
766
767 req = g_new0(NBDRequestData, 1);
768 nbd_client_get(client);
769 req->client = client;
770 return req;
771 }
772
773 static void nbd_request_put(NBDRequestData *req)
774 {
775 NBDClient *client = req->client;
776
777 if (req->data) {
778 qemu_vfree(req->data);
779 }
780 g_free(req);
781
782 client->nb_requests--;
783 nbd_client_receive_next_request(client);
784
785 nbd_client_put(client);
786 }
787
788 static void blk_aio_attached(AioContext *ctx, void *opaque)
789 {
790 NBDExport *exp = opaque;
791 NBDClient *client;
792
793 trace_nbd_blk_aio_attached(exp->name, ctx);
794
795 exp->ctx = ctx;
796
797 QTAILQ_FOREACH(client, &exp->clients, next) {
798 qio_channel_attach_aio_context(client->ioc, ctx);
799 if (client->recv_coroutine) {
800 aio_co_schedule(ctx, client->recv_coroutine);
801 }
802 if (client->send_coroutine) {
803 aio_co_schedule(ctx, client->send_coroutine);
804 }
805 }
806 }
807
808 static void blk_aio_detach(void *opaque)
809 {
810 NBDExport *exp = opaque;
811 NBDClient *client;
812
813 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
814
815 QTAILQ_FOREACH(client, &exp->clients, next) {
816 qio_channel_detach_aio_context(client->ioc);
817 }
818
819 exp->ctx = NULL;
820 }
821
822 static void nbd_eject_notifier(Notifier *n, void *data)
823 {
824 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
825 nbd_export_close(exp);
826 }
827
828 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
829 uint16_t nbdflags, void (*close)(NBDExport *),
830 bool writethrough, BlockBackend *on_eject_blk,
831 Error **errp)
832 {
833 BlockBackend *blk;
834 NBDExport *exp = g_malloc0(sizeof(NBDExport));
835 uint64_t perm;
836 int ret;
837
838 /* Don't allow resize while the NBD server is running, otherwise we don't
839 * care what happens with the node. */
840 perm = BLK_PERM_CONSISTENT_READ;
841 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
842 perm |= BLK_PERM_WRITE;
843 }
844 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
845 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
846 ret = blk_insert_bs(blk, bs, errp);
847 if (ret < 0) {
848 goto fail;
849 }
850 blk_set_enable_write_cache(blk, !writethrough);
851
852 exp->refcount = 1;
853 QTAILQ_INIT(&exp->clients);
854 exp->blk = blk;
855 exp->dev_offset = dev_offset;
856 exp->nbdflags = nbdflags;
857 exp->size = size < 0 ? blk_getlength(blk) : size;
858 if (exp->size < 0) {
859 error_setg_errno(errp, -exp->size,
860 "Failed to determine the NBD export's length");
861 goto fail;
862 }
863 exp->size -= exp->size % BDRV_SECTOR_SIZE;
864
865 exp->close = close;
866 exp->ctx = blk_get_aio_context(blk);
867 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
868
869 if (on_eject_blk) {
870 blk_ref(on_eject_blk);
871 exp->eject_notifier_blk = on_eject_blk;
872 exp->eject_notifier.notify = nbd_eject_notifier;
873 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
874 }
875
876 /*
877 * NBD exports are used for non-shared storage migration. Make sure
878 * that BDRV_O_INACTIVE is cleared and the image is ready for write
879 * access since the export could be available before migration handover.
880 */
881 aio_context_acquire(exp->ctx);
882 blk_invalidate_cache(blk, NULL);
883 aio_context_release(exp->ctx);
884 return exp;
885
886 fail:
887 blk_unref(blk);
888 g_free(exp);
889 return NULL;
890 }
891
892 NBDExport *nbd_export_find(const char *name)
893 {
894 NBDExport *exp;
895 QTAILQ_FOREACH(exp, &exports, next) {
896 if (strcmp(name, exp->name) == 0) {
897 return exp;
898 }
899 }
900
901 return NULL;
902 }
903
904 void nbd_export_set_name(NBDExport *exp, const char *name)
905 {
906 if (exp->name == name) {
907 return;
908 }
909
910 nbd_export_get(exp);
911 if (exp->name != NULL) {
912 g_free(exp->name);
913 exp->name = NULL;
914 QTAILQ_REMOVE(&exports, exp, next);
915 nbd_export_put(exp);
916 }
917 if (name != NULL) {
918 nbd_export_get(exp);
919 exp->name = g_strdup(name);
920 QTAILQ_INSERT_TAIL(&exports, exp, next);
921 }
922 nbd_export_put(exp);
923 }
924
925 void nbd_export_set_description(NBDExport *exp, const char *description)
926 {
927 g_free(exp->description);
928 exp->description = g_strdup(description);
929 }
930
931 void nbd_export_close(NBDExport *exp)
932 {
933 NBDClient *client, *next;
934
935 nbd_export_get(exp);
936 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
937 client_close(client, true);
938 }
939 nbd_export_set_name(exp, NULL);
940 nbd_export_set_description(exp, NULL);
941 nbd_export_put(exp);
942 }
943
944 void nbd_export_get(NBDExport *exp)
945 {
946 assert(exp->refcount > 0);
947 exp->refcount++;
948 }
949
950 void nbd_export_put(NBDExport *exp)
951 {
952 assert(exp->refcount > 0);
953 if (exp->refcount == 1) {
954 nbd_export_close(exp);
955 }
956
957 if (--exp->refcount == 0) {
958 assert(exp->name == NULL);
959 assert(exp->description == NULL);
960
961 if (exp->close) {
962 exp->close(exp);
963 }
964
965 if (exp->blk) {
966 if (exp->eject_notifier_blk) {
967 notifier_remove(&exp->eject_notifier);
968 blk_unref(exp->eject_notifier_blk);
969 }
970 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
971 blk_aio_detach, exp);
972 blk_unref(exp->blk);
973 exp->blk = NULL;
974 }
975
976 g_free(exp);
977 }
978 }
979
980 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
981 {
982 return exp->blk;
983 }
984
985 void nbd_export_close_all(void)
986 {
987 NBDExport *exp, *next;
988
989 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
990 nbd_export_close(exp);
991 }
992 }
993
994 static int nbd_co_send_reply(NBDRequestData *req, NBDReply *reply, int len,
995 Error **errp)
996 {
997 NBDClient *client = req->client;
998 int ret;
999
1000 g_assert(qemu_in_coroutine());
1001
1002 trace_nbd_co_send_reply(reply->handle, reply->error, len);
1003
1004 qemu_co_mutex_lock(&client->send_lock);
1005 client->send_coroutine = qemu_coroutine_self();
1006
1007 if (!len) {
1008 ret = nbd_send_reply(client->ioc, reply, errp);
1009 } else {
1010 qio_channel_set_cork(client->ioc, true);
1011 ret = nbd_send_reply(client->ioc, reply, errp);
1012 if (ret == 0) {
1013 ret = nbd_write(client->ioc, req->data, len, errp);
1014 if (ret < 0) {
1015 ret = -EIO;
1016 }
1017 }
1018 qio_channel_set_cork(client->ioc, false);
1019 }
1020
1021 client->send_coroutine = NULL;
1022 qemu_co_mutex_unlock(&client->send_lock);
1023 return ret;
1024 }
1025
1026 /* nbd_co_receive_request
1027 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1028 * connection right away, and any other negative value to report an error to
1029 * the client (although the caller may still need to disconnect after reporting
1030 * the error).
1031 */
1032 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1033 Error **errp)
1034 {
1035 NBDClient *client = req->client;
1036
1037 g_assert(qemu_in_coroutine());
1038 assert(client->recv_coroutine == qemu_coroutine_self());
1039 if (nbd_receive_request(client->ioc, request, errp) < 0) {
1040 return -EIO;
1041 }
1042
1043 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
1044 nbd_cmd_lookup(request->type));
1045
1046 if (request->type != NBD_CMD_WRITE) {
1047 /* No payload, we are ready to read the next request. */
1048 req->complete = true;
1049 }
1050
1051 if (request->type == NBD_CMD_DISC) {
1052 /* Special case: we're going to disconnect without a reply,
1053 * whether or not flags, from, or len are bogus */
1054 return -EIO;
1055 }
1056
1057 /* Check for sanity in the parameters, part 1. Defer as many
1058 * checks as possible until after reading any NBD_CMD_WRITE
1059 * payload, so we can try and keep the connection alive. */
1060 if ((request->from + request->len) < request->from) {
1061 error_setg(errp,
1062 "integer overflow detected, you're probably being attacked");
1063 return -EINVAL;
1064 }
1065
1066 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
1067 if (request->len > NBD_MAX_BUFFER_SIZE) {
1068 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1069 request->len, NBD_MAX_BUFFER_SIZE);
1070 return -EINVAL;
1071 }
1072
1073 req->data = blk_try_blockalign(client->exp->blk, request->len);
1074 if (req->data == NULL) {
1075 error_setg(errp, "No memory");
1076 return -ENOMEM;
1077 }
1078 }
1079 if (request->type == NBD_CMD_WRITE) {
1080 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1081 error_prepend(errp, "reading from socket failed: ");
1082 return -EIO;
1083 }
1084 req->complete = true;
1085
1086 trace_nbd_co_receive_request_payload_received(request->handle,
1087 request->len);
1088 }
1089
1090 /* Sanity checks, part 2. */
1091 if (request->from + request->len > client->exp->size) {
1092 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1093 ", Size: %" PRIu64, request->from, request->len,
1094 (uint64_t)client->exp->size);
1095 return request->type == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;
1096 }
1097 if (request->flags & ~(NBD_CMD_FLAG_FUA | NBD_CMD_FLAG_NO_HOLE)) {
1098 error_setg(errp, "unsupported flags (got 0x%x)", request->flags);
1099 return -EINVAL;
1100 }
1101 if (request->type != NBD_CMD_WRITE_ZEROES &&
1102 (request->flags & NBD_CMD_FLAG_NO_HOLE)) {
1103 error_setg(errp, "unexpected flags (got 0x%x)", request->flags);
1104 return -EINVAL;
1105 }
1106
1107 return 0;
1108 }
1109
1110 /* Owns a reference to the NBDClient passed as opaque. */
1111 static coroutine_fn void nbd_trip(void *opaque)
1112 {
1113 NBDClient *client = opaque;
1114 NBDExport *exp = client->exp;
1115 NBDRequestData *req;
1116 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
1117 NBDReply reply;
1118 int ret;
1119 int flags;
1120 int reply_data_len = 0;
1121 Error *local_err = NULL;
1122
1123 trace_nbd_trip();
1124 if (client->closing) {
1125 nbd_client_put(client);
1126 return;
1127 }
1128
1129 req = nbd_request_get(client);
1130 ret = nbd_co_receive_request(req, &request, &local_err);
1131 client->recv_coroutine = NULL;
1132 nbd_client_receive_next_request(client);
1133 if (ret == -EIO) {
1134 goto disconnect;
1135 }
1136
1137 reply.handle = request.handle;
1138 reply.error = 0;
1139
1140 if (ret < 0) {
1141 reply.error = -ret;
1142 goto reply;
1143 }
1144
1145 if (client->closing) {
1146 /*
1147 * The client may be closed when we are blocked in
1148 * nbd_co_receive_request()
1149 */
1150 goto done;
1151 }
1152
1153 switch (request.type) {
1154 case NBD_CMD_READ:
1155 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1156 if (request.flags & NBD_CMD_FLAG_FUA) {
1157 ret = blk_co_flush(exp->blk);
1158 if (ret < 0) {
1159 error_setg_errno(&local_err, -ret, "flush failed");
1160 reply.error = -ret;
1161 break;
1162 }
1163 }
1164
1165 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1166 req->data, request.len);
1167 if (ret < 0) {
1168 error_setg_errno(&local_err, -ret, "reading from file failed");
1169 reply.error = -ret;
1170 break;
1171 }
1172
1173 reply_data_len = request.len;
1174
1175 break;
1176 case NBD_CMD_WRITE:
1177 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1178 reply.error = EROFS;
1179 break;
1180 }
1181
1182 flags = 0;
1183 if (request.flags & NBD_CMD_FLAG_FUA) {
1184 flags |= BDRV_REQ_FUA;
1185 }
1186 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1187 req->data, request.len, flags);
1188 if (ret < 0) {
1189 error_setg_errno(&local_err, -ret, "writing to file failed");
1190 reply.error = -ret;
1191 }
1192
1193 break;
1194 case NBD_CMD_WRITE_ZEROES:
1195 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1196 error_setg(&local_err, "Server is read-only, return error");
1197 reply.error = EROFS;
1198 break;
1199 }
1200
1201 flags = 0;
1202 if (request.flags & NBD_CMD_FLAG_FUA) {
1203 flags |= BDRV_REQ_FUA;
1204 }
1205 if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {
1206 flags |= BDRV_REQ_MAY_UNMAP;
1207 }
1208 ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,
1209 request.len, flags);
1210 if (ret < 0) {
1211 error_setg_errno(&local_err, -ret, "writing to file failed");
1212 reply.error = -ret;
1213 }
1214
1215 break;
1216 case NBD_CMD_DISC:
1217 /* unreachable, thanks to special case in nbd_co_receive_request() */
1218 abort();
1219
1220 case NBD_CMD_FLUSH:
1221 ret = blk_co_flush(exp->blk);
1222 if (ret < 0) {
1223 error_setg_errno(&local_err, -ret, "flush failed");
1224 reply.error = -ret;
1225 }
1226
1227 break;
1228 case NBD_CMD_TRIM:
1229 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1230 request.len);
1231 if (ret < 0) {
1232 error_setg_errno(&local_err, -ret, "discard failed");
1233 reply.error = -ret;
1234 }
1235
1236 break;
1237 default:
1238 error_setg(&local_err, "invalid request type (%" PRIu32 ") received",
1239 request.type);
1240 reply.error = EINVAL;
1241 }
1242
1243 reply:
1244 if (local_err) {
1245 /* If we are here local_err is not fatal error, already stored in
1246 * reply.error */
1247 error_report_err(local_err);
1248 local_err = NULL;
1249 }
1250
1251 if (nbd_co_send_reply(req, &reply, reply_data_len, &local_err) < 0) {
1252 error_prepend(&local_err, "Failed to send reply: ");
1253 goto disconnect;
1254 }
1255
1256 /* We must disconnect after NBD_CMD_WRITE if we did not
1257 * read the payload.
1258 */
1259 if (!req->complete) {
1260 error_setg(&local_err, "Request handling failed in intermediate state");
1261 goto disconnect;
1262 }
1263
1264 done:
1265 nbd_request_put(req);
1266 nbd_client_put(client);
1267 return;
1268
1269 disconnect:
1270 if (local_err) {
1271 error_reportf_err(local_err, "Disconnect client, due to: ");
1272 }
1273 nbd_request_put(req);
1274 client_close(client, true);
1275 nbd_client_put(client);
1276 }
1277
1278 static void nbd_client_receive_next_request(NBDClient *client)
1279 {
1280 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
1281 nbd_client_get(client);
1282 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
1283 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
1284 }
1285 }
1286
1287 static coroutine_fn void nbd_co_client_start(void *opaque)
1288 {
1289 NBDClient *client = opaque;
1290 NBDExport *exp = client->exp;
1291 Error *local_err = NULL;
1292
1293 if (exp) {
1294 nbd_export_get(exp);
1295 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1296 }
1297 qemu_co_mutex_init(&client->send_lock);
1298
1299 if (nbd_negotiate(client, &local_err)) {
1300 if (local_err) {
1301 error_report_err(local_err);
1302 }
1303 client_close(client, false);
1304 return;
1305 }
1306
1307 nbd_client_receive_next_request(client);
1308 }
1309
1310 /*
1311 * Create a new client listener on the given export @exp, using the
1312 * given channel @sioc. Begin servicing it in a coroutine. When the
1313 * connection closes, call @close_fn with an indication of whether the
1314 * client completed negotiation.
1315 */
1316 void nbd_client_new(NBDExport *exp,
1317 QIOChannelSocket *sioc,
1318 QCryptoTLSCreds *tlscreds,
1319 const char *tlsaclname,
1320 void (*close_fn)(NBDClient *, bool))
1321 {
1322 NBDClient *client;
1323 Coroutine *co;
1324
1325 client = g_malloc0(sizeof(NBDClient));
1326 client->refcount = 1;
1327 client->exp = exp;
1328 client->tlscreds = tlscreds;
1329 if (tlscreds) {
1330 object_ref(OBJECT(client->tlscreds));
1331 }
1332 client->tlsaclname = g_strdup(tlsaclname);
1333 client->sioc = sioc;
1334 object_ref(OBJECT(client->sioc));
1335 client->ioc = QIO_CHANNEL(sioc);
1336 object_ref(OBJECT(client->ioc));
1337 client->close_fn = close_fn;
1338
1339 co = qemu_coroutine_create(nbd_co_client_start, client);
1340 qemu_coroutine_enter(co);
1341 }