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