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