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