xref: /qemu/qemu-nbd.c (revision d046c51d)
1 /*
2  *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
3  *
4  *  Network Block Device
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; under version 2 of the License.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
21 #include "qemu-common.h"
22 #include "qemu/cutils.h"
23 #include "sysemu/block-backend.h"
24 #include "block/block_int.h"
25 #include "block/nbd.h"
26 #include "qemu/main-loop.h"
27 #include "qemu/error-report.h"
28 #include "qemu/config-file.h"
29 #include "block/snapshot.h"
30 #include "qapi/util.h"
31 #include "qapi/qmp/qstring.h"
32 #include "qom/object_interfaces.h"
33 #include "io/channel-socket.h"
34 #include "crypto/init.h"
35 
36 #include <getopt.h>
37 #include <libgen.h>
38 #include <pthread.h>
39 
40 #define SOCKET_PATH                "/var/lock/qemu-nbd-%s"
41 #define QEMU_NBD_OPT_CACHE         256
42 #define QEMU_NBD_OPT_AIO           257
43 #define QEMU_NBD_OPT_DISCARD       258
44 #define QEMU_NBD_OPT_DETECT_ZEROES 259
45 #define QEMU_NBD_OPT_OBJECT        260
46 #define QEMU_NBD_OPT_TLSCREDS      261
47 #define QEMU_NBD_OPT_IMAGE_OPTS    262
48 
49 #define MBR_SIZE 512
50 
51 static NBDExport *exp;
52 static bool newproto;
53 static int verbose;
54 static char *srcpath;
55 static SocketAddress *saddr;
56 static int persistent = 0;
57 static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
58 static int shared = 1;
59 static int nb_fds;
60 static QIOChannelSocket *server_ioc;
61 static int server_watch = -1;
62 static QCryptoTLSCreds *tlscreds;
63 
64 static void usage(const char *name)
65 {
66     (printf) (
67 "Usage: %s [OPTIONS] FILE\n"
68 "QEMU Disk Network Block Device Server\n"
69 "\n"
70 "  -h, --help                display this help and exit\n"
71 "  -V, --version             output version information and exit\n"
72 "\n"
73 "Connection properties:\n"
74 "  -p, --port=PORT           port to listen on (default `%d')\n"
75 "  -b, --bind=IFACE          interface to bind to (default `0.0.0.0')\n"
76 "  -k, --socket=PATH         path to the unix socket\n"
77 "                            (default '"SOCKET_PATH"')\n"
78 "  -e, --shared=NUM          device can be shared by NUM clients (default '1')\n"
79 "  -t, --persistent          don't exit on the last connection\n"
80 "  -v, --verbose             display extra debugging information\n"
81 "  -x, --export-name=NAME    expose export by name\n"
82 "\n"
83 "Exposing part of the image:\n"
84 "  -o, --offset=OFFSET       offset into the image\n"
85 "  -P, --partition=NUM       only expose partition NUM\n"
86 "\n"
87 "General purpose options:\n"
88 "  --object type,id=ID,...   define an object such as 'secret' for providing\n"
89 "                            passwords and/or encryption keys\n"
90 #ifdef __linux__
91 "Kernel NBD client support:\n"
92 "  -c, --connect=DEV         connect FILE to the local NBD device DEV\n"
93 "  -d, --disconnect          disconnect the specified device\n"
94 "\n"
95 #endif
96 "\n"
97 "Block device options:\n"
98 "  -f, --format=FORMAT       set image format (raw, qcow2, ...)\n"
99 "  -r, --read-only           export read-only\n"
100 "  -s, --snapshot            use FILE as an external snapshot, create a temporary\n"
101 "                            file with backing_file=FILE, redirect the write to\n"
102 "                            the temporary one\n"
103 "  -l, --load-snapshot=SNAPSHOT_PARAM\n"
104 "                            load an internal snapshot inside FILE and export it\n"
105 "                            as an read-only device, SNAPSHOT_PARAM format is\n"
106 "                            'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
107 "                            '[ID_OR_NAME]'\n"
108 "  -n, --nocache             disable host cache\n"
109 "      --cache=MODE          set cache mode (none, writeback, ...)\n"
110 "      --aio=MODE            set AIO mode (native or threads)\n"
111 "      --discard=MODE        set discard mode (ignore, unmap)\n"
112 "      --detect-zeroes=MODE  set detect-zeroes mode (off, on, unmap)\n"
113 "      --image-opts          treat FILE as a full set of image options\n"
114 "\n"
115 "Report bugs to <qemu-devel@nongnu.org>\n"
116     , name, NBD_DEFAULT_PORT, "DEVICE");
117 }
118 
119 static void version(const char *name)
120 {
121     printf(
122 "%s version 0.0.1\n"
123 "Written by Anthony Liguori.\n"
124 "\n"
125 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
126 "This is free software; see the source for copying conditions.  There is NO\n"
127 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
128     , name);
129 }
130 
131 struct partition_record
132 {
133     uint8_t bootable;
134     uint8_t start_head;
135     uint32_t start_cylinder;
136     uint8_t start_sector;
137     uint8_t system;
138     uint8_t end_head;
139     uint8_t end_cylinder;
140     uint8_t end_sector;
141     uint32_t start_sector_abs;
142     uint32_t nb_sectors_abs;
143 };
144 
145 static void read_partition(uint8_t *p, struct partition_record *r)
146 {
147     r->bootable = p[0];
148     r->start_head = p[1];
149     r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
150     r->start_sector = p[2] & 0x3f;
151     r->system = p[4];
152     r->end_head = p[5];
153     r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
154     r->end_sector = p[6] & 0x3f;
155 
156     r->start_sector_abs = le32_to_cpup((uint32_t *)(p +  8));
157     r->nb_sectors_abs   = le32_to_cpup((uint32_t *)(p + 12));
158 }
159 
160 static int find_partition(BlockBackend *blk, int partition,
161                           off_t *offset, off_t *size)
162 {
163     struct partition_record mbr[4];
164     uint8_t data[MBR_SIZE];
165     int i;
166     int ext_partnum = 4;
167     int ret;
168 
169     ret = blk_pread(blk, 0, data, sizeof(data));
170     if (ret < 0) {
171         error_report("error while reading: %s", strerror(-ret));
172         exit(EXIT_FAILURE);
173     }
174 
175     if (data[510] != 0x55 || data[511] != 0xaa) {
176         return -EINVAL;
177     }
178 
179     for (i = 0; i < 4; i++) {
180         read_partition(&data[446 + 16 * i], &mbr[i]);
181 
182         if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
183             continue;
184         }
185 
186         if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
187             struct partition_record ext[4];
188             uint8_t data1[MBR_SIZE];
189             int j;
190 
191             ret = blk_pread(blk, mbr[i].start_sector_abs * MBR_SIZE,
192                             data1, sizeof(data1));
193             if (ret < 0) {
194                 error_report("error while reading: %s", strerror(-ret));
195                 exit(EXIT_FAILURE);
196             }
197 
198             for (j = 0; j < 4; j++) {
199                 read_partition(&data1[446 + 16 * j], &ext[j]);
200                 if (!ext[j].system || !ext[j].nb_sectors_abs) {
201                     continue;
202                 }
203 
204                 if ((ext_partnum + j + 1) == partition) {
205                     *offset = (uint64_t)ext[j].start_sector_abs << 9;
206                     *size = (uint64_t)ext[j].nb_sectors_abs << 9;
207                     return 0;
208                 }
209             }
210             ext_partnum += 4;
211         } else if ((i + 1) == partition) {
212             *offset = (uint64_t)mbr[i].start_sector_abs << 9;
213             *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
214             return 0;
215         }
216     }
217 
218     return -ENOENT;
219 }
220 
221 static void termsig_handler(int signum)
222 {
223     atomic_cmpxchg(&state, RUNNING, TERMINATE);
224     qemu_notify_event();
225 }
226 
227 
228 static void *show_parts(void *arg)
229 {
230     char *device = arg;
231     int nbd;
232 
233     /* linux just needs an open() to trigger
234      * the partition table update
235      * but remember to load the module with max_part != 0 :
236      *     modprobe nbd max_part=63
237      */
238     nbd = open(device, O_RDWR);
239     if (nbd >= 0) {
240         close(nbd);
241     }
242     return NULL;
243 }
244 
245 static void *nbd_client_thread(void *arg)
246 {
247     char *device = arg;
248     off_t size;
249     uint32_t nbdflags;
250     QIOChannelSocket *sioc;
251     int fd;
252     int ret;
253     pthread_t show_parts_thread;
254     Error *local_error = NULL;
255 
256     sioc = qio_channel_socket_new();
257     if (qio_channel_socket_connect_sync(sioc,
258                                         saddr,
259                                         &local_error) < 0) {
260         error_report_err(local_error);
261         goto out;
262     }
263 
264     ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, &nbdflags,
265                                 NULL, NULL, NULL,
266                                 &size, &local_error);
267     if (ret < 0) {
268         if (local_error) {
269             error_report_err(local_error);
270         }
271         goto out_socket;
272     }
273 
274     fd = open(device, O_RDWR);
275     if (fd < 0) {
276         /* Linux-only, we can use %m in printf.  */
277         error_report("Failed to open %s: %m", device);
278         goto out_socket;
279     }
280 
281     ret = nbd_init(fd, sioc, nbdflags, size);
282     if (ret < 0) {
283         goto out_fd;
284     }
285 
286     /* update partition table */
287     pthread_create(&show_parts_thread, NULL, show_parts, device);
288 
289     if (verbose) {
290         fprintf(stderr, "NBD device %s is now connected to %s\n",
291                 device, srcpath);
292     } else {
293         /* Close stderr so that the qemu-nbd process exits.  */
294         dup2(STDOUT_FILENO, STDERR_FILENO);
295     }
296 
297     ret = nbd_client(fd);
298     if (ret) {
299         goto out_fd;
300     }
301     close(fd);
302     object_unref(OBJECT(sioc));
303     kill(getpid(), SIGTERM);
304     return (void *) EXIT_SUCCESS;
305 
306 out_fd:
307     close(fd);
308 out_socket:
309     object_unref(OBJECT(sioc));
310 out:
311     kill(getpid(), SIGTERM);
312     return (void *) EXIT_FAILURE;
313 }
314 
315 static int nbd_can_accept(void)
316 {
317     return nb_fds < shared;
318 }
319 
320 static void nbd_export_closed(NBDExport *exp)
321 {
322     assert(state == TERMINATING);
323     state = TERMINATED;
324 }
325 
326 static void nbd_update_server_watch(void);
327 
328 static void nbd_client_closed(NBDClient *client)
329 {
330     nb_fds--;
331     if (nb_fds == 0 && !persistent && state == RUNNING) {
332         state = TERMINATE;
333     }
334     nbd_update_server_watch();
335     nbd_client_put(client);
336 }
337 
338 static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
339 {
340     QIOChannelSocket *cioc;
341 
342     cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
343                                      NULL);
344     if (!cioc) {
345         return TRUE;
346     }
347 
348     if (state >= TERMINATE) {
349         object_unref(OBJECT(cioc));
350         return TRUE;
351     }
352 
353     nb_fds++;
354     nbd_update_server_watch();
355     nbd_client_new(newproto ? NULL : exp, cioc,
356                    tlscreds, NULL, nbd_client_closed);
357     object_unref(OBJECT(cioc));
358 
359     return TRUE;
360 }
361 
362 static void nbd_update_server_watch(void)
363 {
364     if (nbd_can_accept()) {
365         if (server_watch == -1) {
366             server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
367                                                  G_IO_IN,
368                                                  nbd_accept,
369                                                  NULL, NULL);
370         }
371     } else {
372         if (server_watch != -1) {
373             g_source_remove(server_watch);
374             server_watch = -1;
375         }
376     }
377 }
378 
379 
380 static SocketAddress *nbd_build_socket_address(const char *sockpath,
381                                                const char *bindto,
382                                                const char *port)
383 {
384     SocketAddress *saddr;
385 
386     saddr = g_new0(SocketAddress, 1);
387     if (sockpath) {
388         saddr->type = SOCKET_ADDRESS_KIND_UNIX;
389         saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
390         saddr->u.q_unix.data->path = g_strdup(sockpath);
391     } else {
392         InetSocketAddress *inet;
393         saddr->type = SOCKET_ADDRESS_KIND_INET;
394         inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
395         inet->host = g_strdup(bindto);
396         if (port) {
397             inet->port = g_strdup(port);
398         } else  {
399             inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
400         }
401     }
402 
403     return saddr;
404 }
405 
406 
407 static QemuOptsList file_opts = {
408     .name = "file",
409     .implied_opt_name = "file",
410     .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
411     .desc = {
412         /* no elements => accept any params */
413         { /* end of list */ }
414     },
415 };
416 
417 static QemuOptsList qemu_object_opts = {
418     .name = "object",
419     .implied_opt_name = "qom-type",
420     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
421     .desc = {
422         { }
423     },
424 };
425 
426 
427 
428 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
429 {
430     Object *obj;
431     QCryptoTLSCreds *creds;
432 
433     obj = object_resolve_path_component(
434         object_get_objects_root(), id);
435     if (!obj) {
436         error_setg(errp, "No TLS credentials with id '%s'",
437                    id);
438         return NULL;
439     }
440     creds = (QCryptoTLSCreds *)
441         object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
442     if (!creds) {
443         error_setg(errp, "Object with id '%s' is not TLS credentials",
444                    id);
445         return NULL;
446     }
447 
448     if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
449         error_setg(errp,
450                    "Expecting TLS credentials with a server endpoint");
451         return NULL;
452     }
453     object_ref(obj);
454     return creds;
455 }
456 
457 
458 int main(int argc, char **argv)
459 {
460     BlockBackend *blk;
461     BlockDriverState *bs;
462     off_t dev_offset = 0;
463     uint32_t nbdflags = 0;
464     bool disconnect = false;
465     const char *bindto = "0.0.0.0";
466     const char *port = NULL;
467     char *sockpath = NULL;
468     char *device = NULL;
469     off_t fd_size;
470     QemuOpts *sn_opts = NULL;
471     const char *sn_id_or_name = NULL;
472     const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:";
473     struct option lopt[] = {
474         { "help", no_argument, NULL, 'h' },
475         { "version", no_argument, NULL, 'V' },
476         { "bind", required_argument, NULL, 'b' },
477         { "port", required_argument, NULL, 'p' },
478         { "socket", required_argument, NULL, 'k' },
479         { "offset", required_argument, NULL, 'o' },
480         { "read-only", no_argument, NULL, 'r' },
481         { "partition", required_argument, NULL, 'P' },
482         { "connect", required_argument, NULL, 'c' },
483         { "disconnect", no_argument, NULL, 'd' },
484         { "snapshot", no_argument, NULL, 's' },
485         { "load-snapshot", required_argument, NULL, 'l' },
486         { "nocache", no_argument, NULL, 'n' },
487         { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
488         { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
489         { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
490         { "detect-zeroes", required_argument, NULL,
491           QEMU_NBD_OPT_DETECT_ZEROES },
492         { "shared", required_argument, NULL, 'e' },
493         { "format", required_argument, NULL, 'f' },
494         { "persistent", no_argument, NULL, 't' },
495         { "verbose", no_argument, NULL, 'v' },
496         { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
497         { "export-name", required_argument, NULL, 'x' },
498         { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
499         { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
500         { NULL, 0, NULL, 0 }
501     };
502     int ch;
503     int opt_ind = 0;
504     char *end;
505     int flags = BDRV_O_RDWR;
506     int partition = -1;
507     int ret = 0;
508     bool seen_cache = false;
509     bool seen_discard = false;
510     bool seen_aio = false;
511     pthread_t client_thread;
512     const char *fmt = NULL;
513     Error *local_err = NULL;
514     BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
515     QDict *options = NULL;
516     const char *export_name = NULL;
517     const char *tlscredsid = NULL;
518     bool imageOpts = false;
519     bool writethrough = true;
520 
521     /* The client thread uses SIGTERM to interrupt the server.  A signal
522      * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
523      */
524     struct sigaction sa_sigterm;
525     memset(&sa_sigterm, 0, sizeof(sa_sigterm));
526     sa_sigterm.sa_handler = termsig_handler;
527     sigaction(SIGTERM, &sa_sigterm, NULL);
528 
529     if (qcrypto_init(&local_err) < 0) {
530         error_reportf_err(local_err, "cannot initialize crypto: ");
531         exit(1);
532     }
533 
534     module_call_init(MODULE_INIT_QOM);
535     qemu_add_opts(&qemu_object_opts);
536     qemu_init_exec_dir(argv[0]);
537 
538     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
539         switch (ch) {
540         case 's':
541             flags |= BDRV_O_SNAPSHOT;
542             break;
543         case 'n':
544             optarg = (char *) "none";
545             /* fallthrough */
546         case QEMU_NBD_OPT_CACHE:
547             if (seen_cache) {
548                 error_report("-n and --cache can only be specified once");
549                 exit(EXIT_FAILURE);
550             }
551             seen_cache = true;
552             if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
553                 error_report("Invalid cache mode `%s'", optarg);
554                 exit(EXIT_FAILURE);
555             }
556             break;
557         case QEMU_NBD_OPT_AIO:
558             if (seen_aio) {
559                 error_report("--aio can only be specified once");
560                 exit(EXIT_FAILURE);
561             }
562             seen_aio = true;
563             if (!strcmp(optarg, "native")) {
564                 flags |= BDRV_O_NATIVE_AIO;
565             } else if (!strcmp(optarg, "threads")) {
566                 /* this is the default */
567             } else {
568                error_report("invalid aio mode `%s'", optarg);
569                exit(EXIT_FAILURE);
570             }
571             break;
572         case QEMU_NBD_OPT_DISCARD:
573             if (seen_discard) {
574                 error_report("--discard can only be specified once");
575                 exit(EXIT_FAILURE);
576             }
577             seen_discard = true;
578             if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
579                 error_report("Invalid discard mode `%s'", optarg);
580                 exit(EXIT_FAILURE);
581             }
582             break;
583         case QEMU_NBD_OPT_DETECT_ZEROES:
584             detect_zeroes =
585                 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
586                                 optarg,
587                                 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
588                                 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
589                                 &local_err);
590             if (local_err) {
591                 error_reportf_err(local_err,
592                                   "Failed to parse detect_zeroes mode: ");
593                 exit(EXIT_FAILURE);
594             }
595             if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
596                 !(flags & BDRV_O_UNMAP)) {
597                 error_report("setting detect-zeroes to unmap is not allowed "
598                              "without setting discard operation to unmap");
599                 exit(EXIT_FAILURE);
600             }
601             break;
602         case 'b':
603             bindto = optarg;
604             break;
605         case 'p':
606             port = optarg;
607             break;
608         case 'o':
609                 dev_offset = strtoll (optarg, &end, 0);
610             if (*end) {
611                 error_report("Invalid offset `%s'", optarg);
612                 exit(EXIT_FAILURE);
613             }
614             if (dev_offset < 0) {
615                 error_report("Offset must be positive `%s'", optarg);
616                 exit(EXIT_FAILURE);
617             }
618             break;
619         case 'l':
620             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
621                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
622                                                   optarg, false);
623                 if (!sn_opts) {
624                     error_report("Failed in parsing snapshot param `%s'",
625                                  optarg);
626                     exit(EXIT_FAILURE);
627                 }
628             } else {
629                 sn_id_or_name = optarg;
630             }
631             /* fall through */
632         case 'r':
633             nbdflags |= NBD_FLAG_READ_ONLY;
634             flags &= ~BDRV_O_RDWR;
635             break;
636         case 'P':
637             partition = strtol(optarg, &end, 0);
638             if (*end) {
639                 error_report("Invalid partition `%s'", optarg);
640                 exit(EXIT_FAILURE);
641             }
642             if (partition < 1 || partition > 8) {
643                 error_report("Invalid partition %d", partition);
644                 exit(EXIT_FAILURE);
645             }
646             break;
647         case 'k':
648             sockpath = optarg;
649             if (sockpath[0] != '/') {
650                 error_report("socket path must be absolute");
651                 exit(EXIT_FAILURE);
652             }
653             break;
654         case 'd':
655             disconnect = true;
656             break;
657         case 'c':
658             device = optarg;
659             break;
660         case 'e':
661             shared = strtol(optarg, &end, 0);
662             if (*end) {
663                 error_report("Invalid shared device number '%s'", optarg);
664                 exit(EXIT_FAILURE);
665             }
666             if (shared < 1) {
667                 error_report("Shared device number must be greater than 0");
668                 exit(EXIT_FAILURE);
669             }
670             break;
671         case 'f':
672             fmt = optarg;
673             break;
674         case 't':
675             persistent = 1;
676             break;
677         case 'x':
678             export_name = optarg;
679             break;
680         case 'v':
681             verbose = 1;
682             break;
683         case 'V':
684             version(argv[0]);
685             exit(0);
686             break;
687         case 'h':
688             usage(argv[0]);
689             exit(0);
690             break;
691         case '?':
692             error_report("Try `%s --help' for more information.", argv[0]);
693             exit(EXIT_FAILURE);
694         case QEMU_NBD_OPT_OBJECT: {
695             QemuOpts *opts;
696             opts = qemu_opts_parse_noisily(&qemu_object_opts,
697                                            optarg, true);
698             if (!opts) {
699                 exit(EXIT_FAILURE);
700             }
701         }   break;
702         case QEMU_NBD_OPT_TLSCREDS:
703             tlscredsid = optarg;
704             break;
705         case QEMU_NBD_OPT_IMAGE_OPTS:
706             imageOpts = true;
707             break;
708         }
709     }
710 
711     if ((argc - optind) != 1) {
712         error_report("Invalid number of arguments");
713         error_printf("Try `%s --help' for more information.\n", argv[0]);
714         exit(EXIT_FAILURE);
715     }
716 
717     if (qemu_opts_foreach(&qemu_object_opts,
718                           user_creatable_add_opts_foreach,
719                           NULL, NULL)) {
720         exit(EXIT_FAILURE);
721     }
722 
723     if (tlscredsid) {
724         if (sockpath) {
725             error_report("TLS is only supported with IPv4/IPv6");
726             exit(EXIT_FAILURE);
727         }
728         if (device) {
729             error_report("TLS is not supported with a host device");
730             exit(EXIT_FAILURE);
731         }
732         if (!export_name) {
733             /* Set the default NBD protocol export name, since
734              * we *must* use new style protocol for TLS */
735             export_name = "";
736         }
737         tlscreds = nbd_get_tls_creds(tlscredsid, &local_err);
738         if (local_err) {
739             error_report("Failed to get TLS creds %s",
740                          error_get_pretty(local_err));
741             exit(EXIT_FAILURE);
742         }
743     }
744 
745     if (disconnect) {
746         int nbdfd = open(argv[optind], O_RDWR);
747         if (nbdfd < 0) {
748             error_report("Cannot open %s: %s", argv[optind],
749                          strerror(errno));
750             exit(EXIT_FAILURE);
751         }
752         nbd_disconnect(nbdfd);
753 
754         close(nbdfd);
755 
756         printf("%s disconnected\n", argv[optind]);
757 
758         return 0;
759     }
760 
761     if (device && !verbose) {
762         int stderr_fd[2];
763         pid_t pid;
764         int ret;
765 
766         if (qemu_pipe(stderr_fd) < 0) {
767             error_report("Error setting up communication pipe: %s",
768                          strerror(errno));
769             exit(EXIT_FAILURE);
770         }
771 
772         /* Now daemonize, but keep a communication channel open to
773          * print errors and exit with the proper status code.
774          */
775         pid = fork();
776         if (pid < 0) {
777             error_report("Failed to fork: %s", strerror(errno));
778             exit(EXIT_FAILURE);
779         } else if (pid == 0) {
780             close(stderr_fd[0]);
781             ret = qemu_daemon(1, 0);
782 
783             /* Temporarily redirect stderr to the parent's pipe...  */
784             dup2(stderr_fd[1], STDERR_FILENO);
785             if (ret < 0) {
786                 error_report("Failed to daemonize: %s", strerror(errno));
787                 exit(EXIT_FAILURE);
788             }
789 
790             /* ... close the descriptor we inherited and go on.  */
791             close(stderr_fd[1]);
792         } else {
793             bool errors = false;
794             char *buf;
795 
796             /* In the parent.  Print error messages from the child until
797              * it closes the pipe.
798              */
799             close(stderr_fd[1]);
800             buf = g_malloc(1024);
801             while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
802                 errors = true;
803                 ret = qemu_write_full(STDERR_FILENO, buf, ret);
804                 if (ret < 0) {
805                     exit(EXIT_FAILURE);
806                 }
807             }
808             if (ret < 0) {
809                 error_report("Cannot read from daemon: %s",
810                              strerror(errno));
811                 exit(EXIT_FAILURE);
812             }
813 
814             /* Usually the daemon should not print any message.
815              * Exit with zero status in that case.
816              */
817             exit(errors);
818         }
819     }
820 
821     if (device != NULL && sockpath == NULL) {
822         sockpath = g_malloc(128);
823         snprintf(sockpath, 128, SOCKET_PATH, basename(device));
824     }
825 
826     saddr = nbd_build_socket_address(sockpath, bindto, port);
827 
828     if (qemu_init_main_loop(&local_err)) {
829         error_report_err(local_err);
830         exit(EXIT_FAILURE);
831     }
832     bdrv_init();
833     atexit(bdrv_close_all);
834 
835     srcpath = argv[optind];
836     if (imageOpts) {
837         QemuOpts *opts;
838         if (fmt) {
839             error_report("--image-opts and -f are mutually exclusive");
840             exit(EXIT_FAILURE);
841         }
842         opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
843         if (!opts) {
844             qemu_opts_reset(&file_opts);
845             exit(EXIT_FAILURE);
846         }
847         options = qemu_opts_to_qdict(opts, NULL);
848         qemu_opts_reset(&file_opts);
849         blk = blk_new_open(NULL, NULL, options, flags, &local_err);
850     } else {
851         if (fmt) {
852             options = qdict_new();
853             qdict_put(options, "driver", qstring_from_str(fmt));
854         }
855         blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
856     }
857 
858     if (!blk) {
859         error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
860                           argv[optind]);
861         exit(EXIT_FAILURE);
862     }
863     bs = blk_bs(blk);
864 
865     blk_set_enable_write_cache(blk, !writethrough);
866 
867     if (sn_opts) {
868         ret = bdrv_snapshot_load_tmp(bs,
869                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
870                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
871                                      &local_err);
872     } else if (sn_id_or_name) {
873         ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
874                                                    &local_err);
875     }
876     if (ret < 0) {
877         error_reportf_err(local_err, "Failed to load snapshot: ");
878         exit(EXIT_FAILURE);
879     }
880 
881     bs->detect_zeroes = detect_zeroes;
882     fd_size = blk_getlength(blk);
883     if (fd_size < 0) {
884         error_report("Failed to determine the image length: %s",
885                      strerror(-fd_size));
886         exit(EXIT_FAILURE);
887     }
888 
889     if (partition != -1) {
890         ret = find_partition(blk, partition, &dev_offset, &fd_size);
891         if (ret < 0) {
892             error_report("Could not find partition %d: %s", partition,
893                          strerror(-ret));
894             exit(EXIT_FAILURE);
895         }
896     }
897 
898     exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
899                          &local_err);
900     if (!exp) {
901         error_report_err(local_err);
902         exit(EXIT_FAILURE);
903     }
904     if (export_name) {
905         nbd_export_set_name(exp, export_name);
906         newproto = true;
907     }
908 
909     server_ioc = qio_channel_socket_new();
910     if (qio_channel_socket_listen_sync(server_ioc, saddr, &local_err) < 0) {
911         object_unref(OBJECT(server_ioc));
912         error_report_err(local_err);
913         return 1;
914     }
915 
916     if (device) {
917         int ret;
918 
919         ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
920         if (ret != 0) {
921             error_report("Failed to create client thread: %s", strerror(ret));
922             exit(EXIT_FAILURE);
923         }
924     } else {
925         /* Shut up GCC warnings.  */
926         memset(&client_thread, 0, sizeof(client_thread));
927     }
928 
929     nbd_update_server_watch();
930 
931     /* now when the initialization is (almost) complete, chdir("/")
932      * to free any busy filesystems */
933     if (chdir("/") < 0) {
934         error_report("Could not chdir to root directory: %s",
935                      strerror(errno));
936         exit(EXIT_FAILURE);
937     }
938 
939     state = RUNNING;
940     do {
941         main_loop_wait(false);
942         if (state == TERMINATE) {
943             state = TERMINATING;
944             nbd_export_close(exp);
945             nbd_export_put(exp);
946             exp = NULL;
947         }
948     } while (state != TERMINATED);
949 
950     blk_unref(blk);
951     if (sockpath) {
952         unlink(sockpath);
953     }
954 
955     qemu_opts_del(sn_opts);
956 
957     if (device) {
958         void *ret;
959         pthread_join(client_thread, &ret);
960         exit(ret != NULL);
961     } else {
962         exit(EXIT_SUCCESS);
963     }
964 }
965