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