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