xref: /openbmc/qemu/qemu-nbd.c (revision b4b9a0e3)
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 <getopt.h>
21 #include <libgen.h>
22 #include <pthread.h>
23 
24 #include "qemu-common.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "sysemu/block-backend.h"
28 #include "sysemu/runstate.h" /* for qemu_system_killed() prototype */
29 #include "block/block_int.h"
30 #include "block/nbd.h"
31 #include "qemu/main-loop.h"
32 #include "qemu/module.h"
33 #include "qemu/option.h"
34 #include "qemu/error-report.h"
35 #include "qemu/config-file.h"
36 #include "qemu/bswap.h"
37 #include "qemu/log.h"
38 #include "qemu/systemd.h"
39 #include "block/snapshot.h"
40 #include "qapi/qmp/qdict.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qom/object_interfaces.h"
43 #include "io/channel-socket.h"
44 #include "io/net-listener.h"
45 #include "crypto/init.h"
46 #include "crypto/tlscreds.h"
47 #include "trace/control.h"
48 #include "qemu-version.h"
49 
50 #ifdef __linux__
51 #define HAVE_NBD_DEVICE 1
52 #else
53 #define HAVE_NBD_DEVICE 0
54 #endif
55 
56 #define SOCKET_PATH                "/var/lock/qemu-nbd-%s"
57 #define QEMU_NBD_OPT_CACHE         256
58 #define QEMU_NBD_OPT_AIO           257
59 #define QEMU_NBD_OPT_DISCARD       258
60 #define QEMU_NBD_OPT_DETECT_ZEROES 259
61 #define QEMU_NBD_OPT_OBJECT        260
62 #define QEMU_NBD_OPT_TLSCREDS      261
63 #define QEMU_NBD_OPT_IMAGE_OPTS    262
64 #define QEMU_NBD_OPT_FORK          263
65 #define QEMU_NBD_OPT_TLSAUTHZ      264
66 #define QEMU_NBD_OPT_PID_FILE      265
67 
68 #define MBR_SIZE 512
69 
70 static int verbose;
71 static char *srcpath;
72 static SocketAddress *saddr;
73 static int persistent = 0;
74 static enum { RUNNING, TERMINATE, TERMINATED } state;
75 static int shared = 1;
76 static int nb_fds;
77 static QIONetListener *server;
78 static QCryptoTLSCreds *tlscreds;
79 static const char *tlsauthz;
80 
81 static void usage(const char *name)
82 {
83     (printf) (
84 "Usage: %s [OPTIONS] FILE\n"
85 "  or:  %s -L [OPTIONS]\n"
86 "QEMU Disk Network Block Device Utility\n"
87 "\n"
88 "  -h, --help                display this help and exit\n"
89 "  -V, --version             output version information and exit\n"
90 "\n"
91 "Connection properties:\n"
92 "  -p, --port=PORT           port to listen on (default `%d')\n"
93 "  -b, --bind=IFACE          interface to bind to (default `0.0.0.0')\n"
94 "  -k, --socket=PATH         path to the unix socket\n"
95 "                            (default '"SOCKET_PATH"')\n"
96 "  -e, --shared=NUM          device can be shared by NUM clients (default '1')\n"
97 "  -t, --persistent          don't exit on the last connection\n"
98 "  -v, --verbose             display extra debugging information\n"
99 "  -x, --export-name=NAME    expose export by name (default is empty string)\n"
100 "  -D, --description=TEXT    export a human-readable description\n"
101 "\n"
102 "Exposing part of the image:\n"
103 "  -o, --offset=OFFSET       offset into the image\n"
104 "  -A, --allocation-depth    expose the allocation depth\n"
105 "  -B, --bitmap=NAME         expose a persistent dirty bitmap\n"
106 "\n"
107 "General purpose options:\n"
108 "  -L, --list                list exports available from another NBD server\n"
109 "  --object type,id=ID,...   define an object such as 'secret' for providing\n"
110 "                            passwords and/or encryption keys\n"
111 "  --tls-creds=ID            use id of an earlier --object to provide TLS\n"
112 "  --tls-authz=ID            use id of an earlier --object to provide\n"
113 "                            authorization\n"
114 "  -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
115 "                            specify tracing options\n"
116 "  --fork                    fork off the server process and exit the parent\n"
117 "                            once the server is running\n"
118 "  --pid-file=PATH           store the server's process ID in the given file\n"
119 #if HAVE_NBD_DEVICE
120 "\n"
121 "Kernel NBD client support:\n"
122 "  -c, --connect=DEV         connect FILE to the local NBD device DEV\n"
123 "  -d, --disconnect          disconnect the specified device\n"
124 #endif
125 "\n"
126 "Block device options:\n"
127 "  -f, --format=FORMAT       set image format (raw, qcow2, ...)\n"
128 "  -r, --read-only           export read-only\n"
129 "  -s, --snapshot            use FILE as an external snapshot, create a temporary\n"
130 "                            file with backing_file=FILE, redirect the write to\n"
131 "                            the temporary one\n"
132 "  -l, --load-snapshot=SNAPSHOT_PARAM\n"
133 "                            load an internal snapshot inside FILE and export it\n"
134 "                            as an read-only device, SNAPSHOT_PARAM format is\n"
135 "                            'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
136 "                            '[ID_OR_NAME]'\n"
137 "  -n, --nocache             disable host cache\n"
138 "      --cache=MODE          set cache mode used to access the disk image, the\n"
139 "                            valid options are: 'none', 'writeback' (default),\n"
140 "                            'writethrough', 'directsync' and 'unsafe'\n"
141 "      --aio=MODE            set AIO mode (native, io_uring or threads)\n"
142 "      --discard=MODE        set discard mode (ignore, unmap)\n"
143 "      --detect-zeroes=MODE  set detect-zeroes mode (off, on, unmap)\n"
144 "      --image-opts          treat FILE as a full set of image options\n"
145 "\n"
146 QEMU_HELP_BOTTOM "\n"
147     , name, name, NBD_DEFAULT_PORT, "DEVICE");
148 }
149 
150 static void version(const char *name)
151 {
152     printf(
153 "%s " QEMU_FULL_VERSION "\n"
154 "Written by Anthony Liguori.\n"
155 "\n"
156 QEMU_COPYRIGHT "\n"
157 "This is free software; see the source for copying conditions.  There is NO\n"
158 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
159     , name);
160 }
161 
162 #ifdef CONFIG_POSIX
163 /*
164  * The client thread uses SIGTERM to interrupt the server.  A signal
165  * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
166  */
167 void qemu_system_killed(int signum, pid_t pid)
168 {
169     qatomic_cmpxchg(&state, RUNNING, TERMINATE);
170     qemu_notify_event();
171 }
172 #endif /* CONFIG_POSIX */
173 
174 static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
175                                 const char *hostname)
176 {
177     int ret = EXIT_FAILURE;
178     int rc;
179     Error *err = NULL;
180     QIOChannelSocket *sioc;
181     NBDExportInfo *list;
182     int i, j;
183 
184     sioc = qio_channel_socket_new();
185     if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
186         error_report_err(err);
187         goto out;
188     }
189     rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
190                                  &err);
191     if (rc < 0) {
192         if (err) {
193             error_report_err(err);
194         }
195         goto out;
196     }
197     printf("exports available: %d\n", rc);
198     for (i = 0; i < rc; i++) {
199         printf(" export: '%s'\n", list[i].name);
200         if (list[i].description && *list[i].description) {
201             printf("  description: %s\n", list[i].description);
202         }
203         if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
204             static const char *const flag_names[] = {
205                 [NBD_FLAG_READ_ONLY_BIT]            = "readonly",
206                 [NBD_FLAG_SEND_FLUSH_BIT]           = "flush",
207                 [NBD_FLAG_SEND_FUA_BIT]             = "fua",
208                 [NBD_FLAG_ROTATIONAL_BIT]           = "rotational",
209                 [NBD_FLAG_SEND_TRIM_BIT]            = "trim",
210                 [NBD_FLAG_SEND_WRITE_ZEROES_BIT]    = "zeroes",
211                 [NBD_FLAG_SEND_DF_BIT]              = "df",
212                 [NBD_FLAG_CAN_MULTI_CONN_BIT]       = "multi",
213                 [NBD_FLAG_SEND_RESIZE_BIT]          = "resize",
214                 [NBD_FLAG_SEND_CACHE_BIT]           = "cache",
215                 [NBD_FLAG_SEND_FAST_ZERO_BIT]       = "fast-zero",
216             };
217 
218             printf("  size:  %" PRIu64 "\n", list[i].size);
219             printf("  flags: 0x%x (", list[i].flags);
220             for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
221                 if (flag_names[bit] && (list[i].flags & (1 << bit))) {
222                     printf(" %s", flag_names[bit]);
223                 }
224             }
225             printf(" )\n");
226         }
227         if (list[i].min_block) {
228             printf("  min block: %u\n", list[i].min_block);
229             printf("  opt block: %u\n", list[i].opt_block);
230             printf("  max block: %u\n", list[i].max_block);
231         }
232         if (list[i].n_contexts) {
233             printf("  available meta contexts: %d\n", list[i].n_contexts);
234             for (j = 0; j < list[i].n_contexts; j++) {
235                 printf("   %s\n", list[i].contexts[j]);
236             }
237         }
238     }
239     nbd_free_export_list(list, rc);
240 
241     ret = EXIT_SUCCESS;
242  out:
243     object_unref(OBJECT(sioc));
244     return ret;
245 }
246 
247 
248 #if HAVE_NBD_DEVICE
249 static void *show_parts(void *arg)
250 {
251     char *device = arg;
252     int nbd;
253 
254     /* linux just needs an open() to trigger
255      * the partition table update
256      * but remember to load the module with max_part != 0 :
257      *     modprobe nbd max_part=63
258      */
259     nbd = open(device, O_RDWR);
260     if (nbd >= 0) {
261         close(nbd);
262     }
263     return NULL;
264 }
265 
266 static void *nbd_client_thread(void *arg)
267 {
268     char *device = arg;
269     NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
270     QIOChannelSocket *sioc;
271     int fd = -1;
272     int ret = EXIT_FAILURE;
273     pthread_t show_parts_thread;
274     Error *local_error = NULL;
275 
276     sioc = qio_channel_socket_new();
277     if (qio_channel_socket_connect_sync(sioc,
278                                         saddr,
279                                         &local_error) < 0) {
280         error_report_err(local_error);
281         goto out;
282     }
283 
284     if (nbd_receive_negotiate(NULL, QIO_CHANNEL(sioc),
285                               NULL, NULL, NULL, &info, &local_error) < 0) {
286         if (local_error) {
287             error_report_err(local_error);
288         }
289         goto out;
290     }
291 
292     fd = open(device, O_RDWR);
293     if (fd < 0) {
294         /* Linux-only, we can use %m in printf.  */
295         error_report("Failed to open %s: %m", device);
296         goto out;
297     }
298 
299     if (nbd_init(fd, sioc, &info, &local_error) < 0) {
300         error_report_err(local_error);
301         goto out;
302     }
303 
304     /* update partition table */
305     pthread_create(&show_parts_thread, NULL, show_parts, device);
306 
307     if (verbose) {
308         fprintf(stderr, "NBD device %s is now connected to %s\n",
309                 device, srcpath);
310     } else {
311         /* Close stderr so that the qemu-nbd process exits.  */
312         dup2(STDOUT_FILENO, STDERR_FILENO);
313     }
314 
315     if (nbd_client(fd) < 0) {
316         goto out;
317     }
318 
319     ret = EXIT_SUCCESS;
320 
321  out:
322     if (fd >= 0) {
323         close(fd);
324     }
325     object_unref(OBJECT(sioc));
326     g_free(info.name);
327     kill(getpid(), SIGTERM);
328     return (void *) (intptr_t) ret;
329 }
330 #endif /* HAVE_NBD_DEVICE */
331 
332 static int nbd_can_accept(void)
333 {
334     return state == RUNNING && (shared == 0 || nb_fds < shared);
335 }
336 
337 static void nbd_update_server_watch(void);
338 
339 static void nbd_client_closed(NBDClient *client, bool negotiated)
340 {
341     nb_fds--;
342     if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
343         state = TERMINATE;
344     }
345     nbd_update_server_watch();
346     nbd_client_put(client);
347 }
348 
349 static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
350                        gpointer opaque)
351 {
352     if (state >= TERMINATE) {
353         return;
354     }
355 
356     nb_fds++;
357     nbd_update_server_watch();
358     nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
359 }
360 
361 static void nbd_update_server_watch(void)
362 {
363     if (nbd_can_accept()) {
364         qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
365     } else {
366         qio_net_listener_set_client_func(server, NULL, NULL, NULL);
367     }
368 }
369 
370 
371 static SocketAddress *nbd_build_socket_address(const char *sockpath,
372                                                const char *bindto,
373                                                const char *port)
374 {
375     SocketAddress *saddr;
376 
377     saddr = g_new0(SocketAddress, 1);
378     if (sockpath) {
379         saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
380         saddr->u.q_unix.path = g_strdup(sockpath);
381     } else {
382         InetSocketAddress *inet;
383         saddr->type = SOCKET_ADDRESS_TYPE_INET;
384         inet = &saddr->u.inet;
385         inet->host = g_strdup(bindto);
386         if (port) {
387             inet->port = g_strdup(port);
388         } else  {
389             inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
390         }
391     }
392 
393     return saddr;
394 }
395 
396 
397 static QemuOptsList file_opts = {
398     .name = "file",
399     .implied_opt_name = "file",
400     .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
401     .desc = {
402         /* no elements => accept any params */
403         { /* end of list */ }
404     },
405 };
406 
407 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
408                                           Error **errp)
409 {
410     Object *obj;
411     QCryptoTLSCreds *creds;
412 
413     obj = object_resolve_path_component(
414         object_get_objects_root(), id);
415     if (!obj) {
416         error_setg(errp, "No TLS credentials with id '%s'",
417                    id);
418         return NULL;
419     }
420     creds = (QCryptoTLSCreds *)
421         object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
422     if (!creds) {
423         error_setg(errp, "Object with id '%s' is not TLS credentials",
424                    id);
425         return NULL;
426     }
427 
428     if (!qcrypto_tls_creds_check_endpoint(creds,
429                                           list
430                                           ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
431                                           : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
432                                           errp)) {
433         return NULL;
434     }
435     object_ref(obj);
436     return creds;
437 }
438 
439 static void setup_address_and_port(const char **address, const char **port)
440 {
441     if (*address == NULL) {
442         *address = "0.0.0.0";
443     }
444 
445     if (*port == NULL) {
446         *port = stringify(NBD_DEFAULT_PORT);
447     }
448 }
449 
450 /*
451  * Check socket parameters compatibility when socket activation is used.
452  */
453 static const char *socket_activation_validate_opts(const char *device,
454                                                    const char *sockpath,
455                                                    const char *address,
456                                                    const char *port,
457                                                    bool list)
458 {
459     if (device != NULL) {
460         return "NBD device can't be set when using socket activation";
461     }
462 
463     if (sockpath != NULL) {
464         return "Unix socket can't be set when using socket activation";
465     }
466 
467     if (address != NULL) {
468         return "The interface can't be set when using socket activation";
469     }
470 
471     if (port != NULL) {
472         return "TCP port number can't be set when using socket activation";
473     }
474 
475     if (list) {
476         return "List mode is incompatible with socket activation";
477     }
478 
479     return NULL;
480 }
481 
482 static void qemu_nbd_shutdown(void)
483 {
484     job_cancel_sync_all();
485     blk_exp_close_all();
486     bdrv_close_all();
487 }
488 
489 int main(int argc, char **argv)
490 {
491     BlockBackend *blk;
492     BlockDriverState *bs;
493     uint64_t dev_offset = 0;
494     bool readonly = false;
495     bool disconnect = false;
496     const char *bindto = NULL;
497     const char *port = NULL;
498     char *sockpath = NULL;
499     char *device = NULL;
500     QemuOpts *sn_opts = NULL;
501     const char *sn_id_or_name = NULL;
502     const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
503     struct option lopt[] = {
504         { "help", no_argument, NULL, 'h' },
505         { "version", no_argument, NULL, 'V' },
506         { "bind", required_argument, NULL, 'b' },
507         { "port", required_argument, NULL, 'p' },
508         { "socket", required_argument, NULL, 'k' },
509         { "offset", required_argument, NULL, 'o' },
510         { "read-only", no_argument, NULL, 'r' },
511         { "allocation-depth", no_argument, NULL, 'A' },
512         { "bitmap", required_argument, NULL, 'B' },
513         { "connect", required_argument, NULL, 'c' },
514         { "disconnect", no_argument, NULL, 'd' },
515         { "list", no_argument, NULL, 'L' },
516         { "snapshot", no_argument, NULL, 's' },
517         { "load-snapshot", required_argument, NULL, 'l' },
518         { "nocache", no_argument, NULL, 'n' },
519         { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
520         { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
521         { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
522         { "detect-zeroes", required_argument, NULL,
523           QEMU_NBD_OPT_DETECT_ZEROES },
524         { "shared", required_argument, NULL, 'e' },
525         { "format", required_argument, NULL, 'f' },
526         { "persistent", no_argument, NULL, 't' },
527         { "verbose", no_argument, NULL, 'v' },
528         { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
529         { "export-name", required_argument, NULL, 'x' },
530         { "description", required_argument, NULL, 'D' },
531         { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
532         { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
533         { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
534         { "trace", required_argument, NULL, 'T' },
535         { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
536         { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
537         { NULL, 0, NULL, 0 }
538     };
539     int ch;
540     int opt_ind = 0;
541     int flags = BDRV_O_RDWR;
542     int ret = 0;
543     bool seen_cache = false;
544     bool seen_discard = false;
545     bool seen_aio = false;
546     pthread_t client_thread;
547     const char *fmt = NULL;
548     Error *local_err = NULL;
549     BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
550     QDict *options = NULL;
551     const char *export_name = NULL; /* defaults to "" later for server mode */
552     const char *export_description = NULL;
553     strList *bitmaps = NULL;
554     bool alloc_depth = false;
555     const char *tlscredsid = NULL;
556     bool imageOpts = false;
557     bool writethrough = false; /* Client will flush as needed. */
558     bool fork_process = false;
559     bool list = false;
560     int old_stderr = -1;
561     unsigned socket_activation;
562     const char *pid_file_name = NULL;
563     BlockExportOptions *export_opts;
564 
565 #ifdef CONFIG_POSIX
566     os_setup_early_signal_handling();
567     os_setup_signal_handling();
568 #endif
569 
570     socket_init();
571     error_init(argv[0]);
572     module_call_init(MODULE_INIT_TRACE);
573     qcrypto_init(&error_fatal);
574 
575     module_call_init(MODULE_INIT_QOM);
576     qemu_add_opts(&qemu_trace_opts);
577     qemu_init_exec_dir(argv[0]);
578 
579     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
580         switch (ch) {
581         case 's':
582             flags |= BDRV_O_SNAPSHOT;
583             break;
584         case 'n':
585             optarg = (char *) "none";
586             /* fallthrough */
587         case QEMU_NBD_OPT_CACHE:
588             if (seen_cache) {
589                 error_report("-n and --cache can only be specified once");
590                 exit(EXIT_FAILURE);
591             }
592             seen_cache = true;
593             if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
594                 error_report("Invalid cache mode `%s'", optarg);
595                 exit(EXIT_FAILURE);
596             }
597             break;
598         case QEMU_NBD_OPT_AIO:
599             if (seen_aio) {
600                 error_report("--aio can only be specified once");
601                 exit(EXIT_FAILURE);
602             }
603             seen_aio = true;
604             if (bdrv_parse_aio(optarg, &flags) < 0) {
605                 error_report("Invalid aio mode '%s'", optarg);
606                 exit(EXIT_FAILURE);
607             }
608             break;
609         case QEMU_NBD_OPT_DISCARD:
610             if (seen_discard) {
611                 error_report("--discard can only be specified once");
612                 exit(EXIT_FAILURE);
613             }
614             seen_discard = true;
615             if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
616                 error_report("Invalid discard mode `%s'", optarg);
617                 exit(EXIT_FAILURE);
618             }
619             break;
620         case QEMU_NBD_OPT_DETECT_ZEROES:
621             detect_zeroes =
622                 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
623                                 optarg,
624                                 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
625                                 &local_err);
626             if (local_err) {
627                 error_reportf_err(local_err,
628                                   "Failed to parse detect_zeroes mode: ");
629                 exit(EXIT_FAILURE);
630             }
631             if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
632                 !(flags & BDRV_O_UNMAP)) {
633                 error_report("setting detect-zeroes to unmap is not allowed "
634                              "without setting discard operation to unmap");
635                 exit(EXIT_FAILURE);
636             }
637             break;
638         case 'b':
639             bindto = optarg;
640             break;
641         case 'p':
642             port = optarg;
643             break;
644         case 'o':
645             if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
646                 error_report("Invalid offset '%s'", optarg);
647                 exit(EXIT_FAILURE);
648             }
649             break;
650         case 'l':
651             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
652                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
653                                                   optarg, false);
654                 if (!sn_opts) {
655                     error_report("Failed in parsing snapshot param `%s'",
656                                  optarg);
657                     exit(EXIT_FAILURE);
658                 }
659             } else {
660                 sn_id_or_name = optarg;
661             }
662             /* fall through */
663         case 'r':
664             readonly = true;
665             flags &= ~BDRV_O_RDWR;
666             break;
667         case 'A':
668             alloc_depth = true;
669             break;
670         case 'B':
671             QAPI_LIST_PREPEND(bitmaps, g_strdup(optarg));
672             break;
673         case 'k':
674             sockpath = optarg;
675             if (sockpath[0] != '/') {
676                 error_report("socket path must be absolute");
677                 exit(EXIT_FAILURE);
678             }
679             break;
680         case 'd':
681             disconnect = true;
682             break;
683         case 'c':
684             device = optarg;
685             break;
686         case 'e':
687             if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
688                 shared < 0) {
689                 error_report("Invalid shared device number '%s'", optarg);
690                 exit(EXIT_FAILURE);
691             }
692             break;
693         case 'f':
694             fmt = optarg;
695             break;
696         case 't':
697             persistent = 1;
698             break;
699         case 'x':
700             export_name = optarg;
701             if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
702                 error_report("export name '%s' too long", export_name);
703                 exit(EXIT_FAILURE);
704             }
705             break;
706         case 'D':
707             export_description = optarg;
708             if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
709                 error_report("export description '%s' too long",
710                              export_description);
711                 exit(EXIT_FAILURE);
712             }
713             break;
714         case 'v':
715             verbose = 1;
716             break;
717         case 'V':
718             version(argv[0]);
719             exit(0);
720             break;
721         case 'h':
722             usage(argv[0]);
723             exit(0);
724             break;
725         case '?':
726             error_report("Try `%s --help' for more information.", argv[0]);
727             exit(EXIT_FAILURE);
728         case QEMU_NBD_OPT_OBJECT:
729             user_creatable_process_cmdline(optarg);
730             break;
731         case QEMU_NBD_OPT_TLSCREDS:
732             tlscredsid = optarg;
733             break;
734         case QEMU_NBD_OPT_IMAGE_OPTS:
735             imageOpts = true;
736             break;
737         case 'T':
738             trace_opt_parse(optarg);
739             break;
740         case QEMU_NBD_OPT_TLSAUTHZ:
741             tlsauthz = optarg;
742             break;
743         case QEMU_NBD_OPT_FORK:
744             fork_process = true;
745             break;
746         case 'L':
747             list = true;
748             break;
749         case QEMU_NBD_OPT_PID_FILE:
750             pid_file_name = optarg;
751             break;
752         }
753     }
754 
755     if (list) {
756         if (argc != optind) {
757             error_report("List mode is incompatible with a file name");
758             exit(EXIT_FAILURE);
759         }
760         if (export_name || export_description || dev_offset ||
761             device || disconnect || fmt || sn_id_or_name || bitmaps ||
762             alloc_depth || seen_aio || seen_discard || seen_cache) {
763             error_report("List mode is incompatible with per-device settings");
764             exit(EXIT_FAILURE);
765         }
766         if (fork_process) {
767             error_report("List mode is incompatible with forking");
768             exit(EXIT_FAILURE);
769         }
770     } else if ((argc - optind) != 1) {
771         error_report("Invalid number of arguments");
772         error_printf("Try `%s --help' for more information.\n", argv[0]);
773         exit(EXIT_FAILURE);
774     } else if (!export_name) {
775         export_name = "";
776     }
777 
778     if (!trace_init_backends()) {
779         exit(1);
780     }
781     trace_init_file();
782     qemu_set_log(LOG_TRACE);
783 
784     socket_activation = check_socket_activation();
785     if (socket_activation == 0) {
786         setup_address_and_port(&bindto, &port);
787     } else {
788         /* Using socket activation - check user didn't use -p etc. */
789         const char *err_msg = socket_activation_validate_opts(device, sockpath,
790                                                               bindto, port,
791                                                               list);
792         if (err_msg != NULL) {
793             error_report("%s", err_msg);
794             exit(EXIT_FAILURE);
795         }
796 
797         /* qemu-nbd can only listen on a single socket.  */
798         if (socket_activation > 1) {
799             error_report("qemu-nbd does not support socket activation with %s > 1",
800                          "LISTEN_FDS");
801             exit(EXIT_FAILURE);
802         }
803     }
804 
805     if (tlscredsid) {
806         if (sockpath) {
807             error_report("TLS is only supported with IPv4/IPv6");
808             exit(EXIT_FAILURE);
809         }
810         if (device) {
811             error_report("TLS is not supported with a host device");
812             exit(EXIT_FAILURE);
813         }
814         if (tlsauthz && list) {
815             error_report("TLS authorization is incompatible with export list");
816             exit(EXIT_FAILURE);
817         }
818         tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
819         if (local_err) {
820             error_reportf_err(local_err, "Failed to get TLS creds: ");
821             exit(EXIT_FAILURE);
822         }
823     } else {
824         if (tlsauthz) {
825             error_report("--tls-authz is not permitted without --tls-creds");
826             exit(EXIT_FAILURE);
827         }
828     }
829 
830     if (list) {
831         saddr = nbd_build_socket_address(sockpath, bindto, port);
832         return qemu_nbd_client_list(saddr, tlscreds, bindto);
833     }
834 
835 #if !HAVE_NBD_DEVICE
836     if (disconnect || device) {
837         error_report("Kernel /dev/nbdN support not available");
838         exit(EXIT_FAILURE);
839     }
840 #else /* HAVE_NBD_DEVICE */
841     if (disconnect) {
842         int nbdfd = open(argv[optind], O_RDWR);
843         if (nbdfd < 0) {
844             error_report("Cannot open %s: %s", argv[optind],
845                          strerror(errno));
846             exit(EXIT_FAILURE);
847         }
848         nbd_disconnect(nbdfd);
849 
850         close(nbdfd);
851 
852         printf("%s disconnected\n", argv[optind]);
853 
854         return 0;
855     }
856 #endif
857 
858     if ((device && !verbose) || fork_process) {
859 #ifndef WIN32
860         int stderr_fd[2];
861         pid_t pid;
862         int ret;
863 
864         if (qemu_pipe(stderr_fd) < 0) {
865             error_report("Error setting up communication pipe: %s",
866                          strerror(errno));
867             exit(EXIT_FAILURE);
868         }
869 
870         /* Now daemonize, but keep a communication channel open to
871          * print errors and exit with the proper status code.
872          */
873         pid = fork();
874         if (pid < 0) {
875             error_report("Failed to fork: %s", strerror(errno));
876             exit(EXIT_FAILURE);
877         } else if (pid == 0) {
878             close(stderr_fd[0]);
879 
880             /* Remember parent's stderr if we will be restoring it. */
881             if (fork_process) {
882                 old_stderr = dup(STDERR_FILENO);
883             }
884 
885             ret = qemu_daemon(1, 0);
886 
887             /* Temporarily redirect stderr to the parent's pipe...  */
888             dup2(stderr_fd[1], STDERR_FILENO);
889             if (ret < 0) {
890                 error_report("Failed to daemonize: %s", strerror(errno));
891                 exit(EXIT_FAILURE);
892             }
893 
894             /* ... close the descriptor we inherited and go on.  */
895             close(stderr_fd[1]);
896         } else {
897             bool errors = false;
898             char *buf;
899 
900             /* In the parent.  Print error messages from the child until
901              * it closes the pipe.
902              */
903             close(stderr_fd[1]);
904             buf = g_malloc(1024);
905             while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
906                 errors = true;
907                 ret = qemu_write_full(STDERR_FILENO, buf, ret);
908                 if (ret < 0) {
909                     exit(EXIT_FAILURE);
910                 }
911             }
912             if (ret < 0) {
913                 error_report("Cannot read from daemon: %s",
914                              strerror(errno));
915                 exit(EXIT_FAILURE);
916             }
917 
918             /* Usually the daemon should not print any message.
919              * Exit with zero status in that case.
920              */
921             exit(errors);
922         }
923 #else /* WIN32 */
924         error_report("Unable to fork into background on Windows hosts");
925         exit(EXIT_FAILURE);
926 #endif /* WIN32 */
927     }
928 
929     if (device != NULL && sockpath == NULL) {
930         sockpath = g_malloc(128);
931         snprintf(sockpath, 128, SOCKET_PATH, basename(device));
932     }
933 
934     server = qio_net_listener_new();
935     if (socket_activation == 0) {
936         int backlog;
937 
938         if (persistent || shared == 0) {
939             backlog = SOMAXCONN;
940         } else {
941             backlog = MIN(shared, SOMAXCONN);
942         }
943         saddr = nbd_build_socket_address(sockpath, bindto, port);
944         if (qio_net_listener_open_sync(server, saddr, backlog,
945                                        &local_err) < 0) {
946             object_unref(OBJECT(server));
947             error_report_err(local_err);
948             exit(EXIT_FAILURE);
949         }
950     } else {
951         size_t i;
952         /* See comment in check_socket_activation above. */
953         for (i = 0; i < socket_activation; i++) {
954             QIOChannelSocket *sioc;
955             sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
956                                              &local_err);
957             if (sioc == NULL) {
958                 object_unref(OBJECT(server));
959                 error_reportf_err(local_err,
960                                   "Failed to use socket activation: ");
961                 exit(EXIT_FAILURE);
962             }
963             qio_net_listener_add(server, sioc);
964             object_unref(OBJECT(sioc));
965         }
966     }
967 
968     qemu_init_main_loop(&error_fatal);
969     bdrv_init();
970     atexit(qemu_nbd_shutdown);
971 
972     srcpath = argv[optind];
973     if (imageOpts) {
974         QemuOpts *opts;
975         if (fmt) {
976             error_report("--image-opts and -f are mutually exclusive");
977             exit(EXIT_FAILURE);
978         }
979         opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
980         if (!opts) {
981             qemu_opts_reset(&file_opts);
982             exit(EXIT_FAILURE);
983         }
984         options = qemu_opts_to_qdict(opts, NULL);
985         qemu_opts_reset(&file_opts);
986         blk = blk_new_open(NULL, NULL, options, flags, &local_err);
987     } else {
988         if (fmt) {
989             options = qdict_new();
990             qdict_put_str(options, "driver", fmt);
991         }
992         blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
993     }
994 
995     if (!blk) {
996         error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
997                           argv[optind]);
998         exit(EXIT_FAILURE);
999     }
1000     bs = blk_bs(blk);
1001 
1002     if (dev_offset) {
1003         QDict *raw_opts = qdict_new();
1004         qdict_put_str(raw_opts, "driver", "raw");
1005         qdict_put_str(raw_opts, "file", bs->node_name);
1006         qdict_put_int(raw_opts, "offset", dev_offset);
1007         bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
1008         blk_remove_bs(blk);
1009         blk_insert_bs(blk, bs, &error_fatal);
1010         bdrv_unref(bs);
1011     }
1012 
1013     blk_set_enable_write_cache(blk, !writethrough);
1014 
1015     if (sn_opts) {
1016         ret = bdrv_snapshot_load_tmp(bs,
1017                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1018                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1019                                      &local_err);
1020     } else if (sn_id_or_name) {
1021         ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1022                                                    &local_err);
1023     }
1024     if (ret < 0) {
1025         error_reportf_err(local_err, "Failed to load snapshot: ");
1026         exit(EXIT_FAILURE);
1027     }
1028 
1029     bs->detect_zeroes = detect_zeroes;
1030 
1031     nbd_server_is_qemu_nbd(true);
1032 
1033     export_opts = g_new(BlockExportOptions, 1);
1034     *export_opts = (BlockExportOptions) {
1035         .type               = BLOCK_EXPORT_TYPE_NBD,
1036         .id                 = g_strdup("qemu-nbd-export"),
1037         .node_name          = g_strdup(bdrv_get_node_name(bs)),
1038         .has_writethrough   = true,
1039         .writethrough       = writethrough,
1040         .has_writable       = true,
1041         .writable           = !readonly,
1042         .u.nbd = {
1043             .has_name             = true,
1044             .name                 = g_strdup(export_name),
1045             .has_description      = !!export_description,
1046             .description          = g_strdup(export_description),
1047             .has_bitmaps          = !!bitmaps,
1048             .bitmaps              = bitmaps,
1049             .has_allocation_depth = alloc_depth,
1050             .allocation_depth     = alloc_depth,
1051         },
1052     };
1053     blk_exp_add(export_opts, &error_fatal);
1054     qapi_free_BlockExportOptions(export_opts);
1055 
1056     if (device) {
1057 #if HAVE_NBD_DEVICE
1058         int ret;
1059 
1060         ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
1061         if (ret != 0) {
1062             error_report("Failed to create client thread: %s", strerror(ret));
1063             exit(EXIT_FAILURE);
1064         }
1065 #endif
1066     } else {
1067         /* Shut up GCC warnings.  */
1068         memset(&client_thread, 0, sizeof(client_thread));
1069     }
1070 
1071     nbd_update_server_watch();
1072 
1073     if (pid_file_name) {
1074         qemu_write_pidfile(pid_file_name, &error_fatal);
1075     }
1076 
1077     /* now when the initialization is (almost) complete, chdir("/")
1078      * to free any busy filesystems */
1079     if (chdir("/") < 0) {
1080         error_report("Could not chdir to root directory: %s",
1081                      strerror(errno));
1082         exit(EXIT_FAILURE);
1083     }
1084 
1085     if (fork_process) {
1086         dup2(old_stderr, STDERR_FILENO);
1087         close(old_stderr);
1088     }
1089 
1090     state = RUNNING;
1091     do {
1092         main_loop_wait(false);
1093         if (state == TERMINATE) {
1094             blk_exp_close_all();
1095             state = TERMINATED;
1096         }
1097     } while (state != TERMINATED);
1098 
1099     blk_unref(blk);
1100     if (sockpath) {
1101         unlink(sockpath);
1102     }
1103 
1104     qemu_opts_del(sn_opts);
1105 
1106     if (device) {
1107         void *ret;
1108         pthread_join(client_thread, &ret);
1109         exit(ret != NULL);
1110     } else {
1111         exit(EXIT_SUCCESS);
1112     }
1113 }
1114