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