xref: /openbmc/qemu/nbd/client.c (revision 1ff7b531)
1 /*
2  *  Copyright (C) 2016-2017 Red Hat, Inc.
3  *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
4  *
5  *  Network Block Device Client 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 nbd_errno_to_system_errno(int err)
26 {
27     int ret;
28     switch (err) {
29     case NBD_SUCCESS:
30         ret = 0;
31         break;
32     case NBD_EPERM:
33         ret = EPERM;
34         break;
35     case NBD_EIO:
36         ret = EIO;
37         break;
38     case NBD_ENOMEM:
39         ret = ENOMEM;
40         break;
41     case NBD_ENOSPC:
42         ret = ENOSPC;
43         break;
44     case NBD_ESHUTDOWN:
45         ret = ESHUTDOWN;
46         break;
47     default:
48         trace_nbd_unknown_error(err);
49         /* fallthrough */
50     case NBD_EINVAL:
51         ret = EINVAL;
52         break;
53     }
54     return ret;
55 }
56 
57 /* Definitions for opaque data types */
58 
59 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
60 
61 /* That's all folks */
62 
63 /* Basic flow for negotiation
64 
65    Server         Client
66    Negotiate
67 
68    or
69 
70    Server         Client
71    Negotiate #1
72                   Option
73    Negotiate #2
74 
75    ----
76 
77    followed by
78 
79    Server         Client
80                   Request
81    Response
82                   Request
83    Response
84                   ...
85    ...
86                   Request (type == 2)
87 
88 */
89 
90 /* Send an option request.
91  *
92  * The request is for option @opt, with @data containing @len bytes of
93  * additional payload for the request (@len may be -1 to treat @data as
94  * a C string; and @data may be NULL if @len is 0).
95  * Return 0 if successful, -1 with errp set if it is impossible to
96  * continue. */
97 static int nbd_send_option_request(QIOChannel *ioc, uint32_t opt,
98                                    uint32_t len, const char *data,
99                                    Error **errp)
100 {
101     nbd_option req;
102     QEMU_BUILD_BUG_ON(sizeof(req) != 16);
103 
104     if (len == -1) {
105         req.length = len = strlen(data);
106     }
107     trace_nbd_send_option_request(opt, nbd_opt_lookup(opt), len);
108 
109     stq_be_p(&req.magic, NBD_OPTS_MAGIC);
110     stl_be_p(&req.option, opt);
111     stl_be_p(&req.length, len);
112 
113     if (nbd_write(ioc, &req, sizeof(req), errp) < 0) {
114         error_prepend(errp, "Failed to send option request header");
115         return -1;
116     }
117 
118     if (len && nbd_write(ioc, (char *) data, len, errp) < 0) {
119         error_prepend(errp, "Failed to send option request data");
120         return -1;
121     }
122 
123     return 0;
124 }
125 
126 /* Send NBD_OPT_ABORT as a courtesy to let the server know that we are
127  * not going to attempt further negotiation. */
128 static void nbd_send_opt_abort(QIOChannel *ioc)
129 {
130     /* Technically, a compliant server is supposed to reply to us; but
131      * older servers disconnected instead. At any rate, we're allowed
132      * to disconnect without waiting for the server reply, so we don't
133      * even care if the request makes it to the server, let alone
134      * waiting around for whether the server replies. */
135     nbd_send_option_request(ioc, NBD_OPT_ABORT, 0, NULL, NULL);
136 }
137 
138 
139 /* Receive the header of an option reply, which should match the given
140  * opt.  Read through the length field, but NOT the length bytes of
141  * payload. Return 0 if successful, -1 with errp set if it is
142  * impossible to continue. */
143 static int nbd_receive_option_reply(QIOChannel *ioc, uint32_t opt,
144                                     nbd_opt_reply *reply, Error **errp)
145 {
146     QEMU_BUILD_BUG_ON(sizeof(*reply) != 20);
147     if (nbd_read(ioc, reply, sizeof(*reply), errp) < 0) {
148         error_prepend(errp, "failed to read option reply");
149         nbd_send_opt_abort(ioc);
150         return -1;
151     }
152     be64_to_cpus(&reply->magic);
153     be32_to_cpus(&reply->option);
154     be32_to_cpus(&reply->type);
155     be32_to_cpus(&reply->length);
156 
157     trace_nbd_receive_option_reply(reply->option, nbd_opt_lookup(reply->option),
158                                    reply->type, nbd_rep_lookup(reply->type),
159                                    reply->length);
160 
161     if (reply->magic != NBD_REP_MAGIC) {
162         error_setg(errp, "Unexpected option reply magic");
163         nbd_send_opt_abort(ioc);
164         return -1;
165     }
166     if (reply->option != opt) {
167         error_setg(errp, "Unexpected option type %x expected %x",
168                    reply->option, opt);
169         nbd_send_opt_abort(ioc);
170         return -1;
171     }
172     return 0;
173 }
174 
175 /* If reply represents success, return 1 without further action.
176  * If reply represents an error, consume the optional payload of
177  * the packet on ioc.  Then return 0 for unsupported (so the client
178  * can fall back to other approaches), or -1 with errp set for other
179  * errors.
180  */
181 static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,
182                                 Error **errp)
183 {
184     char *msg = NULL;
185     int result = -1;
186 
187     if (!(reply->type & (1 << 31))) {
188         return 1;
189     }
190 
191     if (reply->length) {
192         if (reply->length > NBD_MAX_BUFFER_SIZE) {
193             error_setg(errp, "server error 0x%" PRIx32
194                        " (%s) message is too long",
195                        reply->type, nbd_rep_lookup(reply->type));
196             goto cleanup;
197         }
198         msg = g_malloc(reply->length + 1);
199         if (nbd_read(ioc, msg, reply->length, errp) < 0) {
200             error_prepend(errp, "failed to read option error 0x%" PRIx32
201                           " (%s) message",
202                           reply->type, nbd_rep_lookup(reply->type));
203             goto cleanup;
204         }
205         msg[reply->length] = '\0';
206     }
207 
208     switch (reply->type) {
209     case NBD_REP_ERR_UNSUP:
210         trace_nbd_reply_err_unsup(reply->option, nbd_opt_lookup(reply->option));
211         result = 0;
212         goto cleanup;
213 
214     case NBD_REP_ERR_POLICY:
215         error_setg(errp, "Denied by server for option %" PRIx32 " (%s)",
216                    reply->option, nbd_opt_lookup(reply->option));
217         break;
218 
219     case NBD_REP_ERR_INVALID:
220         error_setg(errp, "Invalid data length for option %" PRIx32 " (%s)",
221                    reply->option, nbd_opt_lookup(reply->option));
222         break;
223 
224     case NBD_REP_ERR_PLATFORM:
225         error_setg(errp, "Server lacks support for option %" PRIx32 " (%s)",
226                    reply->option, nbd_opt_lookup(reply->option));
227         break;
228 
229     case NBD_REP_ERR_TLS_REQD:
230         error_setg(errp, "TLS negotiation required before option %" PRIx32
231                    " (%s)", reply->option, nbd_opt_lookup(reply->option));
232         break;
233 
234     case NBD_REP_ERR_UNKNOWN:
235         error_setg(errp, "Requested export not available for option %" PRIx32
236                    " (%s)", reply->option, nbd_opt_lookup(reply->option));
237         break;
238 
239     case NBD_REP_ERR_SHUTDOWN:
240         error_setg(errp, "Server shutting down before option %" PRIx32 " (%s)",
241                    reply->option, nbd_opt_lookup(reply->option));
242         break;
243 
244     case NBD_REP_ERR_BLOCK_SIZE_REQD:
245         error_setg(errp, "Server requires INFO_BLOCK_SIZE for option %" PRIx32
246                    " (%s)", reply->option, nbd_opt_lookup(reply->option));
247         break;
248 
249     default:
250         error_setg(errp, "Unknown error code when asking for option %" PRIx32
251                    " (%s)", reply->option, nbd_opt_lookup(reply->option));
252         break;
253     }
254 
255     if (msg) {
256         error_append_hint(errp, "%s\n", msg);
257     }
258 
259  cleanup:
260     g_free(msg);
261     if (result < 0) {
262         nbd_send_opt_abort(ioc);
263     }
264     return result;
265 }
266 
267 /* Process another portion of the NBD_OPT_LIST reply.  Set *@match if
268  * the current reply matches @want or if the server does not support
269  * NBD_OPT_LIST, otherwise leave @match alone.  Return 0 if iteration
270  * is complete, positive if more replies are expected, or negative
271  * with @errp set if an unrecoverable error occurred. */
272 static int nbd_receive_list(QIOChannel *ioc, const char *want, bool *match,
273                             Error **errp)
274 {
275     nbd_opt_reply reply;
276     uint32_t len;
277     uint32_t namelen;
278     char name[NBD_MAX_NAME_SIZE + 1];
279     int error;
280 
281     if (nbd_receive_option_reply(ioc, NBD_OPT_LIST, &reply, errp) < 0) {
282         return -1;
283     }
284     error = nbd_handle_reply_err(ioc, &reply, errp);
285     if (error <= 0) {
286         /* The server did not support NBD_OPT_LIST, so set *match on
287          * the assumption that any name will be accepted.  */
288         *match = true;
289         return error;
290     }
291     len = reply.length;
292 
293     if (reply.type == NBD_REP_ACK) {
294         if (len != 0) {
295             error_setg(errp, "length too long for option end");
296             nbd_send_opt_abort(ioc);
297             return -1;
298         }
299         return 0;
300     } else if (reply.type != NBD_REP_SERVER) {
301         error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",
302                    reply.type, NBD_REP_SERVER);
303         nbd_send_opt_abort(ioc);
304         return -1;
305     }
306 
307     if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {
308         error_setg(errp, "incorrect option length %" PRIu32, len);
309         nbd_send_opt_abort(ioc);
310         return -1;
311     }
312     if (nbd_read(ioc, &namelen, sizeof(namelen), errp) < 0) {
313         error_prepend(errp, "failed to read option name length");
314         nbd_send_opt_abort(ioc);
315         return -1;
316     }
317     namelen = be32_to_cpu(namelen);
318     len -= sizeof(namelen);
319     if (len < namelen) {
320         error_setg(errp, "incorrect option name length");
321         nbd_send_opt_abort(ioc);
322         return -1;
323     }
324     if (namelen != strlen(want)) {
325         if (nbd_drop(ioc, len, errp) < 0) {
326             error_prepend(errp, "failed to skip export name with wrong length");
327             nbd_send_opt_abort(ioc);
328             return -1;
329         }
330         return 1;
331     }
332 
333     assert(namelen < sizeof(name));
334     if (nbd_read(ioc, name, namelen, errp) < 0) {
335         error_prepend(errp, "failed to read export name");
336         nbd_send_opt_abort(ioc);
337         return -1;
338     }
339     name[namelen] = '\0';
340     len -= namelen;
341     if (nbd_drop(ioc, len, errp) < 0) {
342         error_prepend(errp, "failed to read export description");
343         nbd_send_opt_abort(ioc);
344         return -1;
345     }
346     if (!strcmp(name, want)) {
347         *match = true;
348     }
349     return 1;
350 }
351 
352 
353 /* Returns -1 if NBD_OPT_GO proves the export @wantname cannot be
354  * used, 0 if NBD_OPT_GO is unsupported (fall back to NBD_OPT_LIST and
355  * NBD_OPT_EXPORT_NAME in that case), and > 0 if the export is good to
356  * go (with @info populated). */
357 static int nbd_opt_go(QIOChannel *ioc, const char *wantname,
358                       NBDExportInfo *info, Error **errp)
359 {
360     nbd_opt_reply reply;
361     uint32_t len = strlen(wantname);
362     uint16_t type;
363     int error;
364     char *buf;
365 
366     /* The protocol requires that the server send NBD_INFO_EXPORT with
367      * a non-zero flags (at least NBD_FLAG_HAS_FLAGS must be set); so
368      * flags still 0 is a witness of a broken server. */
369     info->flags = 0;
370 
371     trace_nbd_opt_go_start(wantname);
372     buf = g_malloc(4 + len + 2 + 2 * info->request_sizes + 1);
373     stl_be_p(buf, len);
374     memcpy(buf + 4, wantname, len);
375     /* At most one request, everything else up to server */
376     stw_be_p(buf + 4 + len, info->request_sizes);
377     if (info->request_sizes) {
378         stw_be_p(buf + 4 + len + 2, NBD_INFO_BLOCK_SIZE);
379     }
380     if (nbd_send_option_request(ioc, NBD_OPT_GO,
381                                 4 + len + 2 + 2 * info->request_sizes, buf,
382                                 errp) < 0) {
383         return -1;
384     }
385 
386     while (1) {
387         if (nbd_receive_option_reply(ioc, NBD_OPT_GO, &reply, errp) < 0) {
388             return -1;
389         }
390         error = nbd_handle_reply_err(ioc, &reply, errp);
391         if (error <= 0) {
392             return error;
393         }
394         len = reply.length;
395 
396         if (reply.type == NBD_REP_ACK) {
397             /* Server is done sending info and moved into transmission
398                phase, but make sure it sent flags */
399             if (len) {
400                 error_setg(errp, "server sent invalid NBD_REP_ACK");
401                 nbd_send_opt_abort(ioc);
402                 return -1;
403             }
404             if (!info->flags) {
405                 error_setg(errp, "broken server omitted NBD_INFO_EXPORT");
406                 nbd_send_opt_abort(ioc);
407                 return -1;
408             }
409             trace_nbd_opt_go_success();
410             return 1;
411         }
412         if (reply.type != NBD_REP_INFO) {
413             error_setg(errp, "unexpected reply type %" PRIx32
414                        " (%s), expected %x",
415                        reply.type, nbd_rep_lookup(reply.type), NBD_REP_INFO);
416             nbd_send_opt_abort(ioc);
417             return -1;
418         }
419         if (len < sizeof(type)) {
420             error_setg(errp, "NBD_REP_INFO length %" PRIu32 " is too short",
421                        len);
422             nbd_send_opt_abort(ioc);
423             return -1;
424         }
425         if (nbd_read(ioc, &type, sizeof(type), errp) < 0) {
426             error_prepend(errp, "failed to read info type");
427             nbd_send_opt_abort(ioc);
428             return -1;
429         }
430         len -= sizeof(type);
431         be16_to_cpus(&type);
432         switch (type) {
433         case NBD_INFO_EXPORT:
434             if (len != sizeof(info->size) + sizeof(info->flags)) {
435                 error_setg(errp, "remaining export info len %" PRIu32
436                            " is unexpected size", len);
437                 nbd_send_opt_abort(ioc);
438                 return -1;
439             }
440             if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {
441                 error_prepend(errp, "failed to read info size");
442                 nbd_send_opt_abort(ioc);
443                 return -1;
444             }
445             be64_to_cpus(&info->size);
446             if (nbd_read(ioc, &info->flags, sizeof(info->flags), errp) < 0) {
447                 error_prepend(errp, "failed to read info flags");
448                 nbd_send_opt_abort(ioc);
449                 return -1;
450             }
451             be16_to_cpus(&info->flags);
452             trace_nbd_receive_negotiate_size_flags(info->size, info->flags);
453             break;
454 
455         case NBD_INFO_BLOCK_SIZE:
456             if (len != sizeof(info->min_block) * 3) {
457                 error_setg(errp, "remaining export info len %" PRIu32
458                            " is unexpected size", len);
459                 nbd_send_opt_abort(ioc);
460                 return -1;
461             }
462             if (nbd_read(ioc, &info->min_block, sizeof(info->min_block),
463                          errp) < 0) {
464                 error_prepend(errp, "failed to read info minimum block size");
465                 nbd_send_opt_abort(ioc);
466                 return -1;
467             }
468             be32_to_cpus(&info->min_block);
469             if (!is_power_of_2(info->min_block)) {
470                 error_setg(errp, "server minimum block size %" PRId32
471                            "is not a power of two", info->min_block);
472                 nbd_send_opt_abort(ioc);
473                 return -1;
474             }
475             if (nbd_read(ioc, &info->opt_block, sizeof(info->opt_block),
476                          errp) < 0) {
477                 error_prepend(errp, "failed to read info preferred block size");
478                 nbd_send_opt_abort(ioc);
479                 return -1;
480             }
481             be32_to_cpus(&info->opt_block);
482             if (!is_power_of_2(info->opt_block) ||
483                 info->opt_block < info->min_block) {
484                 error_setg(errp, "server preferred block size %" PRId32
485                            "is not valid", info->opt_block);
486                 nbd_send_opt_abort(ioc);
487                 return -1;
488             }
489             if (nbd_read(ioc, &info->max_block, sizeof(info->max_block),
490                          errp) < 0) {
491                 error_prepend(errp, "failed to read info maximum block size");
492                 nbd_send_opt_abort(ioc);
493                 return -1;
494             }
495             be32_to_cpus(&info->max_block);
496             trace_nbd_opt_go_info_block_size(info->min_block, info->opt_block,
497                                              info->max_block);
498             break;
499 
500         default:
501             trace_nbd_opt_go_info_unknown(type, nbd_info_lookup(type));
502             if (nbd_drop(ioc, len, errp) < 0) {
503                 error_prepend(errp, "Failed to read info payload");
504                 nbd_send_opt_abort(ioc);
505                 return -1;
506             }
507             break;
508         }
509     }
510 }
511 
512 /* Return -1 on failure, 0 if wantname is an available export. */
513 static int nbd_receive_query_exports(QIOChannel *ioc,
514                                      const char *wantname,
515                                      Error **errp)
516 {
517     bool foundExport = false;
518 
519     trace_nbd_receive_query_exports_start(wantname);
520     if (nbd_send_option_request(ioc, NBD_OPT_LIST, 0, NULL, errp) < 0) {
521         return -1;
522     }
523 
524     while (1) {
525         int ret = nbd_receive_list(ioc, wantname, &foundExport, errp);
526 
527         if (ret < 0) {
528             /* Server gave unexpected reply */
529             return -1;
530         } else if (ret == 0) {
531             /* Done iterating. */
532             if (!foundExport) {
533                 error_setg(errp, "No export with name '%s' available",
534                            wantname);
535                 nbd_send_opt_abort(ioc);
536                 return -1;
537             }
538             trace_nbd_receive_query_exports_success(wantname);
539             return 0;
540         }
541     }
542 }
543 
544 static QIOChannel *nbd_receive_starttls(QIOChannel *ioc,
545                                         QCryptoTLSCreds *tlscreds,
546                                         const char *hostname, Error **errp)
547 {
548     nbd_opt_reply reply;
549     QIOChannelTLS *tioc;
550     struct NBDTLSHandshakeData data = { 0 };
551 
552     trace_nbd_receive_starttls_request();
553     if (nbd_send_option_request(ioc, NBD_OPT_STARTTLS, 0, NULL, errp) < 0) {
554         return NULL;
555     }
556 
557     trace_nbd_receive_starttls_reply();
558     if (nbd_receive_option_reply(ioc, NBD_OPT_STARTTLS, &reply, errp) < 0) {
559         return NULL;
560     }
561 
562     if (reply.type != NBD_REP_ACK) {
563         error_setg(errp, "Server rejected request to start TLS %" PRIx32,
564                    reply.type);
565         nbd_send_opt_abort(ioc);
566         return NULL;
567     }
568 
569     if (reply.length != 0) {
570         error_setg(errp, "Start TLS response was not zero %" PRIu32,
571                    reply.length);
572         nbd_send_opt_abort(ioc);
573         return NULL;
574     }
575 
576     trace_nbd_receive_starttls_new_client();
577     tioc = qio_channel_tls_new_client(ioc, tlscreds, hostname, errp);
578     if (!tioc) {
579         return NULL;
580     }
581     qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-client-tls");
582     data.loop = g_main_loop_new(g_main_context_default(), FALSE);
583     trace_nbd_receive_starttls_tls_handshake();
584     qio_channel_tls_handshake(tioc,
585                               nbd_tls_handshake,
586                               &data,
587                               NULL);
588 
589     if (!data.complete) {
590         g_main_loop_run(data.loop);
591     }
592     g_main_loop_unref(data.loop);
593     if (data.error) {
594         error_propagate(errp, data.error);
595         object_unref(OBJECT(tioc));
596         return NULL;
597     }
598 
599     return QIO_CHANNEL(tioc);
600 }
601 
602 
603 int nbd_receive_negotiate(QIOChannel *ioc, const char *name,
604                           QCryptoTLSCreds *tlscreds, const char *hostname,
605                           QIOChannel **outioc, NBDExportInfo *info,
606                           Error **errp)
607 {
608     char buf[256];
609     uint64_t magic;
610     int rc;
611     bool zeroes = true;
612 
613     trace_nbd_receive_negotiate(tlscreds, hostname ? hostname : "<null>");
614 
615     rc = -EINVAL;
616 
617     if (outioc) {
618         *outioc = NULL;
619     }
620     if (tlscreds && !outioc) {
621         error_setg(errp, "Output I/O channel required for TLS");
622         goto fail;
623     }
624 
625     if (nbd_read(ioc, buf, 8, errp) < 0) {
626         error_prepend(errp, "Failed to read data");
627         goto fail;
628     }
629 
630     buf[8] = '\0';
631     if (strlen(buf) == 0) {
632         error_setg(errp, "Server connection closed unexpectedly");
633         goto fail;
634     }
635 
636     magic = ldq_be_p(buf);
637     trace_nbd_receive_negotiate_magic(magic);
638 
639     if (memcmp(buf, "NBDMAGIC", 8) != 0) {
640         error_setg(errp, "Invalid magic received");
641         goto fail;
642     }
643 
644     if (nbd_read(ioc, &magic, sizeof(magic), errp) < 0) {
645         error_prepend(errp, "Failed to read magic");
646         goto fail;
647     }
648     magic = be64_to_cpu(magic);
649     trace_nbd_receive_negotiate_magic(magic);
650 
651     if (magic == NBD_OPTS_MAGIC) {
652         uint32_t clientflags = 0;
653         uint16_t globalflags;
654         bool fixedNewStyle = false;
655 
656         if (nbd_read(ioc, &globalflags, sizeof(globalflags), errp) < 0) {
657             error_prepend(errp, "Failed to read server flags");
658             goto fail;
659         }
660         globalflags = be16_to_cpu(globalflags);
661         trace_nbd_receive_negotiate_server_flags(globalflags);
662         if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {
663             fixedNewStyle = true;
664             clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;
665         }
666         if (globalflags & NBD_FLAG_NO_ZEROES) {
667             zeroes = false;
668             clientflags |= NBD_FLAG_C_NO_ZEROES;
669         }
670         /* client requested flags */
671         clientflags = cpu_to_be32(clientflags);
672         if (nbd_write(ioc, &clientflags, sizeof(clientflags), errp) < 0) {
673             error_prepend(errp, "Failed to send clientflags field");
674             goto fail;
675         }
676         if (tlscreds) {
677             if (fixedNewStyle) {
678                 *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);
679                 if (!*outioc) {
680                     goto fail;
681                 }
682                 ioc = *outioc;
683             } else {
684                 error_setg(errp, "Server does not support STARTTLS");
685                 goto fail;
686             }
687         }
688         if (!name) {
689             trace_nbd_receive_negotiate_default_name();
690             name = "";
691         }
692         if (fixedNewStyle) {
693             int result;
694 
695             /* Try NBD_OPT_GO first - if it works, we are done (it
696              * also gives us a good message if the server requires
697              * TLS).  If it is not available, fall back to
698              * NBD_OPT_LIST for nicer error messages about a missing
699              * export, then use NBD_OPT_EXPORT_NAME.  */
700             result = nbd_opt_go(ioc, name, info, errp);
701             if (result < 0) {
702                 goto fail;
703             }
704             if (result > 0) {
705                 return 0;
706             }
707             /* Check our desired export is present in the
708              * server export list. Since NBD_OPT_EXPORT_NAME
709              * cannot return an error message, running this
710              * query gives us better error reporting if the
711              * export name is not available.
712              */
713             if (nbd_receive_query_exports(ioc, name, errp) < 0) {
714                 goto fail;
715             }
716         }
717         /* write the export name request */
718         if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,
719                                     errp) < 0) {
720             goto fail;
721         }
722 
723         /* Read the response */
724         if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {
725             error_prepend(errp, "Failed to read export length");
726             goto fail;
727         }
728         be64_to_cpus(&info->size);
729 
730         if (nbd_read(ioc, &info->flags, sizeof(info->flags), errp) < 0) {
731             error_prepend(errp, "Failed to read export flags");
732             goto fail;
733         }
734         be16_to_cpus(&info->flags);
735     } else if (magic == NBD_CLIENT_MAGIC) {
736         uint32_t oldflags;
737 
738         if (name) {
739             error_setg(errp, "Server does not support export names");
740             goto fail;
741         }
742         if (tlscreds) {
743             error_setg(errp, "Server does not support STARTTLS");
744             goto fail;
745         }
746 
747         if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {
748             error_prepend(errp, "Failed to read export length");
749             goto fail;
750         }
751         be64_to_cpus(&info->size);
752 
753         if (nbd_read(ioc, &oldflags, sizeof(oldflags), errp) < 0) {
754             error_prepend(errp, "Failed to read export flags");
755             goto fail;
756         }
757         be32_to_cpus(&oldflags);
758         if (oldflags & ~0xffff) {
759             error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);
760             goto fail;
761         }
762         info->flags = oldflags;
763     } else {
764         error_setg(errp, "Bad magic received");
765         goto fail;
766     }
767 
768     trace_nbd_receive_negotiate_size_flags(info->size, info->flags);
769     if (zeroes && nbd_drop(ioc, 124, errp) < 0) {
770         error_prepend(errp, "Failed to read reserved block");
771         goto fail;
772     }
773     rc = 0;
774 
775 fail:
776     return rc;
777 }
778 
779 #ifdef __linux__
780 int nbd_init(int fd, QIOChannelSocket *sioc, NBDExportInfo *info,
781              Error **errp)
782 {
783     unsigned long sector_size = MAX(BDRV_SECTOR_SIZE, info->min_block);
784     unsigned long sectors = info->size / sector_size;
785 
786     /* FIXME: Once the kernel module is patched to honor block sizes,
787      * and to advertise that fact to user space, we should update the
788      * hand-off to the kernel to use any block sizes we learned. */
789     assert(!info->request_sizes);
790     if (info->size / sector_size != sectors) {
791         error_setg(errp, "Export size %" PRIu64 " too large for 32-bit kernel",
792                    info->size);
793         return -E2BIG;
794     }
795 
796     trace_nbd_init_set_socket();
797 
798     if (ioctl(fd, NBD_SET_SOCK, (unsigned long) sioc->fd) < 0) {
799         int serrno = errno;
800         error_setg(errp, "Failed to set NBD socket");
801         return -serrno;
802     }
803 
804     trace_nbd_init_set_block_size(sector_size);
805 
806     if (ioctl(fd, NBD_SET_BLKSIZE, sector_size) < 0) {
807         int serrno = errno;
808         error_setg(errp, "Failed setting NBD block size");
809         return -serrno;
810     }
811 
812     trace_nbd_init_set_size(sectors);
813     if (info->size % sector_size) {
814         trace_nbd_init_trailing_bytes(info->size % sector_size);
815     }
816 
817     if (ioctl(fd, NBD_SET_SIZE_BLOCKS, sectors) < 0) {
818         int serrno = errno;
819         error_setg(errp, "Failed setting size (in blocks)");
820         return -serrno;
821     }
822 
823     if (ioctl(fd, NBD_SET_FLAGS, (unsigned long) info->flags) < 0) {
824         if (errno == ENOTTY) {
825             int read_only = (info->flags & NBD_FLAG_READ_ONLY) != 0;
826             trace_nbd_init_set_readonly();
827 
828             if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
829                 int serrno = errno;
830                 error_setg(errp, "Failed setting read-only attribute");
831                 return -serrno;
832             }
833         } else {
834             int serrno = errno;
835             error_setg(errp, "Failed setting flags");
836             return -serrno;
837         }
838     }
839 
840     trace_nbd_init_finish();
841 
842     return 0;
843 }
844 
845 int nbd_client(int fd)
846 {
847     int ret;
848     int serrno;
849 
850     trace_nbd_client_loop();
851 
852     ret = ioctl(fd, NBD_DO_IT);
853     if (ret < 0 && errno == EPIPE) {
854         /* NBD_DO_IT normally returns EPIPE when someone has disconnected
855          * the socket via NBD_DISCONNECT.  We do not want to return 1 in
856          * that case.
857          */
858         ret = 0;
859     }
860     serrno = errno;
861 
862     trace_nbd_client_loop_ret(ret, strerror(serrno));
863 
864     trace_nbd_client_clear_queue();
865     ioctl(fd, NBD_CLEAR_QUE);
866 
867     trace_nbd_client_clear_socket();
868     ioctl(fd, NBD_CLEAR_SOCK);
869 
870     errno = serrno;
871     return ret;
872 }
873 
874 int nbd_disconnect(int fd)
875 {
876     ioctl(fd, NBD_CLEAR_QUE);
877     ioctl(fd, NBD_DISCONNECT);
878     ioctl(fd, NBD_CLEAR_SOCK);
879     return 0;
880 }
881 
882 #else
883 int nbd_init(int fd, QIOChannelSocket *ioc, NBDExportInfo *info,
884 	     Error **errp)
885 {
886     error_setg(errp, "nbd_init is only supported on Linux");
887     return -ENOTSUP;
888 }
889 
890 int nbd_client(int fd)
891 {
892     return -ENOTSUP;
893 }
894 int nbd_disconnect(int fd)
895 {
896     return -ENOTSUP;
897 }
898 #endif
899 
900 ssize_t nbd_send_request(QIOChannel *ioc, NBDRequest *request)
901 {
902     uint8_t buf[NBD_REQUEST_SIZE];
903 
904     trace_nbd_send_request(request->from, request->len, request->handle,
905                            request->flags, request->type);
906 
907     stl_be_p(buf, NBD_REQUEST_MAGIC);
908     stw_be_p(buf + 4, request->flags);
909     stw_be_p(buf + 6, request->type);
910     stq_be_p(buf + 8, request->handle);
911     stq_be_p(buf + 16, request->from);
912     stl_be_p(buf + 24, request->len);
913 
914     return nbd_write(ioc, buf, sizeof(buf), NULL);
915 }
916 
917 ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
918 {
919     uint8_t buf[NBD_REPLY_SIZE];
920     uint32_t magic;
921     ssize_t ret;
922 
923     ret = nbd_read_eof(ioc, buf, sizeof(buf), errp);
924     if (ret <= 0) {
925         return ret;
926     }
927 
928     if (ret != sizeof(buf)) {
929         error_setg(errp, "read failed");
930         return -EINVAL;
931     }
932 
933     /* Reply
934        [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
935        [ 4 ..  7]    error   (0 == no error)
936        [ 7 .. 15]    handle
937      */
938 
939     magic = ldl_be_p(buf);
940     reply->error  = ldl_be_p(buf + 4);
941     reply->handle = ldq_be_p(buf + 8);
942 
943     reply->error = nbd_errno_to_system_errno(reply->error);
944 
945     if (reply->error == ESHUTDOWN) {
946         /* This works even on mingw which lacks a native ESHUTDOWN */
947         error_setg(errp, "server shutting down");
948         return -EINVAL;
949     }
950     trace_nbd_receive_reply(magic, reply->error, reply->handle);
951 
952     if (magic != NBD_REPLY_MAGIC) {
953         error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
954         return -EINVAL;
955     }
956     return sizeof(buf);
957 }
958 
959