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