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