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