OSDN Git Service

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