2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
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.
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.
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/>.
19 #include "qemu/osdep.h"
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"
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"
51 #include <selinux/selinux.h>
55 #define HAVE_NBD_DEVICE 1
57 #define HAVE_NBD_DEVICE 0
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
76 static int persistent = 0;
77 static enum { RUNNING, TERMINATE, TERMINATED } state;
78 static int shared = 1;
80 static QIONetListener *server;
81 static QCryptoTLSCreds *tlscreds;
82 static const char *tlsauthz;
84 static void usage(const char *name)
87 "Usage: %s [OPTIONS] FILE\n"
88 " or: %s -L [OPTIONS]\n"
89 "QEMU Disk Network Block Device Utility\n"
91 " -h, --help display this help and exit\n"
92 " -V, --version output version information and exit\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"
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"
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"
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"
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"
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"
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"
152 QEMU_HELP_BOTTOM "\n"
153 , name, name, NBD_DEFAULT_PORT, "DEVICE");
156 static void version(const char *name)
159 "%s " QEMU_FULL_VERSION "\n"
160 "Written by Anthony Liguori.\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"
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.
173 void qemu_system_killed(int signum, pid_t pid)
175 qatomic_cmpxchg(&state, RUNNING, TERMINATE);
178 #endif /* CONFIG_POSIX */
180 static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
181 const char *hostname)
183 int ret = EXIT_FAILURE;
186 QIOChannelSocket *sioc;
190 sioc = qio_channel_socket_new();
191 if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
192 error_report_err(err);
195 rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
199 error_report_err(err);
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);
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 [NBD_FLAG_BLOCK_STAT_PAYLOAD_BIT] = "block-status-payload",
225 printf(" size: %" PRIu64 "\n", list[i].size);
226 printf(" flags: 0x%x (", list[i].flags);
227 for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
228 if (flag_names[bit] && (list[i].flags & (1 << bit))) {
229 printf(" %s", flag_names[bit]);
234 if (list[i].min_block) {
235 printf(" min block: %u\n", list[i].min_block);
236 printf(" opt block: %u\n", list[i].opt_block);
237 printf(" max block: %u\n", list[i].max_block);
239 printf(" transaction size: %s\n",
240 list[i].mode >= NBD_MODE_EXTENDED ?
241 "64-bit" : "32-bit");
242 if (list[i].n_contexts) {
243 printf(" available meta contexts: %d\n", list[i].n_contexts);
244 for (j = 0; j < list[i].n_contexts; j++) {
245 printf(" %s\n", list[i].contexts[j]);
249 nbd_free_export_list(list, rc);
253 object_unref(OBJECT(sioc));
258 struct NbdClientOpts {
261 SocketAddress *saddr;
267 static void nbd_client_release_pipe(int old_stderr)
269 /* Close stderr so that the qemu-nbd process exits. */
270 if (dup2(old_stderr, STDERR_FILENO) < 0) {
271 error_report("Could not release pipe to parent: %s",
275 if (old_stderr != STDOUT_FILENO && close(old_stderr) < 0) {
276 error_report("Could not release qemu-nbd: %s", strerror(errno));
282 static void *show_parts(void *arg)
287 /* linux just needs an open() to trigger
288 * the partition table update
289 * but remember to load the module with max_part != 0 :
290 * modprobe nbd max_part=63
292 nbd = open(device, O_RDWR);
299 static void *nbd_client_thread(void *arg)
301 struct NbdClientOpts *opts = arg;
302 /* TODO: Revisit this if nbd.ko ever gains support for structured reply */
303 NBDExportInfo info = { .request_sizes = false, .name = g_strdup(""),
304 .mode = NBD_MODE_SIMPLE };
305 QIOChannelSocket *sioc;
307 int ret = EXIT_FAILURE;
308 pthread_t show_parts_thread;
309 Error *local_error = NULL;
311 sioc = qio_channel_socket_new();
312 if (qio_channel_socket_connect_sync(sioc,
315 error_report_err(local_error);
319 if (nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, NULL, NULL,
320 &info, &local_error) < 0) {
322 error_report_err(local_error);
327 fd = open(opts->device, O_RDWR);
329 /* Linux-only, we can use %m in printf. */
330 error_report("Failed to open %s: %m", opts->device);
334 if (nbd_init(fd, sioc, &info, &local_error) < 0) {
335 error_report_err(local_error);
339 /* update partition table */
340 pthread_create(&show_parts_thread, NULL, show_parts, opts->device);
342 if (opts->verbose && !opts->fork_process) {
343 fprintf(stderr, "NBD device %s is now connected to %s\n",
344 opts->device, opts->srcpath);
346 nbd_client_release_pipe(opts->old_stderr);
349 if (nbd_client(fd) < 0) {
359 object_unref(OBJECT(sioc));
361 kill(getpid(), SIGTERM);
362 return (void *) (intptr_t) ret;
364 #endif /* HAVE_NBD_DEVICE */
366 static int nbd_can_accept(void)
368 return state == RUNNING && (shared == 0 || nb_fds < shared);
371 static void nbd_update_server_watch(void);
373 static void nbd_client_closed(NBDClient *client, bool negotiated)
376 if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
379 nbd_update_server_watch();
380 nbd_client_put(client);
383 static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
386 if (state >= TERMINATE) {
391 nbd_update_server_watch();
392 nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
395 static void nbd_update_server_watch(void)
397 if (nbd_can_accept()) {
398 qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
400 qio_net_listener_set_client_func(server, NULL, NULL, NULL);
405 static SocketAddress *nbd_build_socket_address(const char *sockpath,
409 SocketAddress *saddr;
411 saddr = g_new0(SocketAddress, 1);
413 saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
414 saddr->u.q_unix.path = g_strdup(sockpath);
416 InetSocketAddress *inet;
417 saddr->type = SOCKET_ADDRESS_TYPE_INET;
418 inet = &saddr->u.inet;
419 inet->host = g_strdup(bindto);
421 inet->port = g_strdup(port);
423 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
431 static QemuOptsList file_opts = {
433 .implied_opt_name = "file",
434 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
436 /* no elements => accept any params */
437 { /* end of list */ }
441 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
445 QCryptoTLSCreds *creds;
447 obj = object_resolve_path_component(
448 object_get_objects_root(), id);
450 error_setg(errp, "No TLS credentials with id '%s'",
454 creds = (QCryptoTLSCreds *)
455 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
457 error_setg(errp, "Object with id '%s' is not TLS credentials",
462 if (!qcrypto_tls_creds_check_endpoint(creds,
464 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
465 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
473 static void setup_address_and_port(const char **address, const char **port)
475 if (*address == NULL) {
476 *address = "0.0.0.0";
480 *port = stringify(NBD_DEFAULT_PORT);
485 * Check socket parameters compatibility when socket activation is used.
487 static const char *socket_activation_validate_opts(const char *device,
488 const char *sockpath,
494 if (device != NULL) {
495 return "NBD device can't be set when using socket activation";
498 if (sockpath != NULL) {
499 return "Unix socket can't be set when using socket activation";
502 if (address != NULL) {
503 return "The interface can't be set when using socket activation";
507 return "TCP port number can't be set when using socket activation";
510 if (selinux != NULL) {
511 return "SELinux label can't be set when using socket activation";
515 return "List mode is incompatible with socket activation";
521 static void qemu_nbd_shutdown(void)
523 job_cancel_sync_all();
528 int main(int argc, char **argv)
531 BlockDriverState *bs;
532 uint64_t dev_offset = 0;
533 bool readonly = false;
534 bool disconnect = false;
535 const char *bindto = NULL;
536 const char *port = NULL;
537 char *sockpath = NULL;
538 QemuOpts *sn_opts = NULL;
539 const char *sn_id_or_name = NULL;
540 const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
541 struct option lopt[] = {
542 { "help", no_argument, NULL, 'h' },
543 { "version", no_argument, NULL, 'V' },
544 { "bind", required_argument, NULL, 'b' },
545 { "port", required_argument, NULL, 'p' },
546 { "socket", required_argument, NULL, 'k' },
547 { "offset", required_argument, NULL, 'o' },
548 { "read-only", no_argument, NULL, 'r' },
549 { "allocation-depth", no_argument, NULL, 'A' },
550 { "bitmap", required_argument, NULL, 'B' },
551 { "connect", required_argument, NULL, 'c' },
552 { "disconnect", no_argument, NULL, 'd' },
553 { "list", no_argument, NULL, 'L' },
554 { "snapshot", no_argument, NULL, 's' },
555 { "load-snapshot", required_argument, NULL, 'l' },
556 { "nocache", no_argument, NULL, 'n' },
557 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
558 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
559 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
560 { "detect-zeroes", required_argument, NULL,
561 QEMU_NBD_OPT_DETECT_ZEROES },
562 { "shared", required_argument, NULL, 'e' },
563 { "format", required_argument, NULL, 'f' },
564 { "persistent", no_argument, NULL, 't' },
565 { "verbose", no_argument, NULL, 'v' },
566 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
567 { "export-name", required_argument, NULL, 'x' },
568 { "description", required_argument, NULL, 'D' },
569 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
570 { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
571 { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
572 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
573 { "trace", required_argument, NULL, 'T' },
574 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
575 { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
576 { "selinux-label", required_argument, NULL,
577 QEMU_NBD_OPT_SELINUX_LABEL },
582 int flags = BDRV_O_RDWR;
584 bool seen_cache = false;
585 bool seen_discard = false;
586 bool seen_aio = false;
587 pthread_t client_thread;
588 const char *fmt = NULL;
589 Error *local_err = NULL;
590 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
591 QDict *options = NULL;
592 const char *export_name = NULL; /* defaults to "" later for server mode */
593 const char *export_description = NULL;
594 BlockDirtyBitmapOrStrList *bitmaps = NULL;
595 bool alloc_depth = false;
596 const char *tlscredsid = NULL;
597 const char *tlshostname = NULL;
598 bool imageOpts = false;
599 bool writethrough = false; /* Client will flush as needed. */
601 unsigned socket_activation;
602 const char *pid_file_name = NULL;
603 const char *selinux_label = NULL;
604 BlockExportOptions *export_opts;
605 struct NbdClientOpts opts = {
606 .fork_process = false,
611 .old_stderr = STDOUT_FILENO,
615 os_setup_early_signal_handling();
616 os_setup_signal_handling();
621 module_call_init(MODULE_INIT_TRACE);
622 qcrypto_init(&error_fatal);
624 module_call_init(MODULE_INIT_QOM);
625 qemu_add_opts(&qemu_trace_opts);
626 qemu_init_exec_dir(argv[0]);
628 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
631 flags |= BDRV_O_SNAPSHOT;
634 optarg = (char *) "none";
636 case QEMU_NBD_OPT_CACHE:
638 error_report("-n and --cache can only be specified once");
642 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
643 error_report("Invalid cache mode `%s'", optarg);
647 case QEMU_NBD_OPT_AIO:
649 error_report("--aio can only be specified once");
653 if (bdrv_parse_aio(optarg, &flags) < 0) {
654 error_report("Invalid aio mode '%s'", optarg);
658 case QEMU_NBD_OPT_DISCARD:
660 error_report("--discard can only be specified once");
664 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
665 error_report("Invalid discard mode `%s'", optarg);
669 case QEMU_NBD_OPT_DETECT_ZEROES:
671 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
673 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
676 error_reportf_err(local_err,
677 "Failed to parse detect_zeroes mode: ");
680 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
681 !(flags & BDRV_O_UNMAP)) {
682 error_report("setting detect-zeroes to unmap is not allowed "
683 "without setting discard operation to unmap");
694 if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
695 error_report("Invalid offset '%s'", optarg);
700 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
701 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
704 error_report("Failed in parsing snapshot param `%s'",
709 sn_id_or_name = optarg;
714 flags &= ~BDRV_O_RDWR;
721 BlockDirtyBitmapOrStr *el = g_new(BlockDirtyBitmapOrStr, 1);
722 *el = (BlockDirtyBitmapOrStr) {
723 .type = QTYPE_QSTRING,
724 .u.local = g_strdup(optarg),
726 QAPI_LIST_PREPEND(bitmaps, el);
731 if (sockpath[0] != '/') {
732 error_report("socket path must be absolute");
740 opts.device = optarg;
743 if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
745 error_report("Invalid shared device number '%s'", optarg);
756 export_name = optarg;
757 if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
758 error_report("export name '%s' too long", export_name);
763 export_description = optarg;
764 if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
765 error_report("export description '%s' too long",
782 error_report("Try `%s --help' for more information.", argv[0]);
784 case QEMU_NBD_OPT_OBJECT:
785 user_creatable_process_cmdline(optarg);
787 case QEMU_NBD_OPT_TLSCREDS:
790 case QEMU_NBD_OPT_TLSHOSTNAME:
791 tlshostname = optarg;
793 case QEMU_NBD_OPT_IMAGE_OPTS:
797 trace_opt_parse(optarg);
799 case QEMU_NBD_OPT_TLSAUTHZ:
802 case QEMU_NBD_OPT_FORK:
803 opts.fork_process = true;
808 case QEMU_NBD_OPT_PID_FILE:
809 pid_file_name = optarg;
811 case QEMU_NBD_OPT_SELINUX_LABEL:
812 selinux_label = optarg;
818 if (argc != optind) {
819 error_report("List mode is incompatible with a file name");
822 if (export_name || export_description || dev_offset ||
823 opts.device || disconnect || fmt || sn_id_or_name || bitmaps ||
824 alloc_depth || seen_aio || seen_discard || seen_cache) {
825 error_report("List mode is incompatible with per-device settings");
828 if (opts.fork_process) {
829 error_report("List mode is incompatible with forking");
832 } else if ((argc - optind) != 1) {
833 error_report("Invalid number of arguments");
834 error_printf("Try `%s --help' for more information.\n", argv[0]);
836 } else if (!export_name) {
840 if (!trace_init_backends()) {
844 qemu_set_log(LOG_TRACE, &error_fatal);
846 socket_activation = check_socket_activation();
847 if (socket_activation == 0) {
849 setup_address_and_port(&bindto, &port);
852 /* Using socket activation - check user didn't use -p etc. */
853 const char *err_msg = socket_activation_validate_opts(opts.device,
858 if (err_msg != NULL) {
859 error_report("%s", err_msg);
863 /* qemu-nbd can only listen on a single socket. */
864 if (socket_activation > 1) {
865 error_report("qemu-nbd does not support socket activation with %s > 1",
873 error_report("TLS is not supported with a host device");
876 if (tlsauthz && list) {
877 error_report("TLS authorization is incompatible with export list");
880 if (tlshostname && !list) {
881 error_report("TLS hostname is only supported with export list");
884 tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
886 error_reportf_err(local_err, "Failed to get TLS creds: ");
891 error_report("--tls-authz is not permitted without --tls-creds");
895 error_report("--tls-hostname is not permitted without --tls-creds");
901 #ifdef CONFIG_SELINUX
902 if (sockpath == NULL && opts.device == NULL) {
903 error_report("--selinux-label is not permitted without --socket");
907 error_report("SELinux support not enabled in this binary");
913 opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
914 return qemu_nbd_client_list(opts.saddr, tlscreds,
915 tlshostname ? tlshostname : bindto);
919 if (disconnect || opts.device) {
920 error_report("Kernel /dev/nbdN support not available");
923 #else /* HAVE_NBD_DEVICE */
925 int nbdfd = open(argv[optind], O_RDWR);
927 error_report("Cannot open %s: %s", argv[optind],
931 nbd_disconnect(nbdfd);
935 printf("%s disconnected\n", argv[optind]);
941 if ((opts.device && !opts.verbose) || opts.fork_process) {
943 g_autoptr(GError) err = NULL;
947 if (!g_unix_open_pipe(stderr_fd, FD_CLOEXEC, &err)) {
948 error_report("Error setting up communication pipe: %s",
953 /* Now daemonize, but keep a communication channel open to
954 * print errors and exit with the proper status code.
958 error_report("Failed to fork: %s", strerror(errno));
960 } else if (pid == 0) {
965 /* Remember parent's stderr if we will be restoring it. */
966 if (opts.verbose /* fork_process is set */) {
967 opts.old_stderr = dup(STDERR_FILENO);
968 if (opts.old_stderr < 0) {
969 error_report("Could not dup original stderr: %s",
975 ret = qemu_daemon(1, 0);
976 saved_errno = errno; /* dup2 will overwrite error below */
978 /* Temporarily redirect stderr to the parent's pipe... */
979 if (dup2(stderr_fd[1], STDERR_FILENO) < 0) {
981 snprintf(str, sizeof(str),
982 "%s: Failed to link stderr to the pipe: %s\n",
983 g_get_prgname(), strerror(errno));
985 * We are unable to use error_report() here as we need to get
986 * stderr pointed to the parent's pipe. Write to that pipe
989 ret = write(stderr_fd[1], str, strlen(str));
994 error_report("Failed to daemonize: %s", strerror(saved_errno));
998 /* ... close the descriptor we inherited and go on. */
1001 bool errors = false;
1004 /* In the parent. Print error messages from the child until
1005 * it closes the pipe.
1007 close(stderr_fd[1]);
1008 buf = g_malloc(1024);
1009 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
1011 ret = qemu_write_full(STDERR_FILENO, buf, ret);
1017 error_report("Cannot read from daemon: %s",
1022 /* Usually the daemon should not print any message.
1023 * Exit with zero status in that case.
1028 error_report("Unable to fork into background on Windows hosts");
1033 if (opts.device != NULL && sockpath == NULL) {
1034 sockpath = g_malloc(128);
1035 snprintf(sockpath, 128, SOCKET_PATH, basename(opts.device));
1038 server = qio_net_listener_new();
1039 if (socket_activation == 0) {
1042 if (persistent || shared == 0) {
1043 backlog = SOMAXCONN;
1045 backlog = MIN(shared, SOMAXCONN);
1047 #ifdef CONFIG_SELINUX
1048 if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
1049 error_report("Cannot set SELinux socket create context to %s: %s",
1050 selinux_label, strerror(errno));
1054 opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
1055 if (qio_net_listener_open_sync(server, opts.saddr, backlog,
1057 object_unref(OBJECT(server));
1058 error_report_err(local_err);
1061 #ifdef CONFIG_SELINUX
1062 if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
1063 error_report("Cannot clear SELinux socket create context: %s",
1070 /* See comment in check_socket_activation above. */
1071 for (i = 0; i < socket_activation; i++) {
1072 QIOChannelSocket *sioc;
1073 sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
1076 object_unref(OBJECT(server));
1077 error_reportf_err(local_err,
1078 "Failed to use socket activation: ");
1081 qio_net_listener_add(server, sioc);
1082 object_unref(OBJECT(sioc));
1086 qemu_init_main_loop(&error_fatal);
1088 atexit(qemu_nbd_shutdown);
1090 opts.srcpath = argv[optind];
1094 error_report("--image-opts and -f are mutually exclusive");
1097 o = qemu_opts_parse_noisily(&file_opts, opts.srcpath, true);
1099 qemu_opts_reset(&file_opts);
1102 options = qemu_opts_to_qdict(o, NULL);
1103 qemu_opts_reset(&file_opts);
1104 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
1107 options = qdict_new();
1108 qdict_put_str(options, "driver", fmt);
1110 blk = blk_new_open(opts.srcpath, NULL, options, flags, &local_err);
1114 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1121 QDict *raw_opts = qdict_new();
1122 qdict_put_str(raw_opts, "driver", "raw");
1123 qdict_put_str(raw_opts, "file", bs->node_name);
1124 qdict_put_int(raw_opts, "offset", dev_offset);
1126 aio_context_acquire(qemu_get_aio_context());
1127 bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
1128 aio_context_release(qemu_get_aio_context());
1131 blk_insert_bs(blk, bs, &error_fatal);
1135 blk_set_enable_write_cache(blk, !writethrough);
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),
1142 } else if (sn_id_or_name) {
1143 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1147 error_reportf_err(local_err, "Failed to load snapshot: ");
1151 bs->detect_zeroes = detect_zeroes;
1153 nbd_server_is_qemu_nbd(shared);
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,
1165 .name = g_strdup(export_name),
1166 .description = g_strdup(export_description),
1167 .has_bitmaps = !!bitmaps,
1169 .has_allocation_depth = alloc_depth,
1170 .allocation_depth = alloc_depth,
1173 blk_exp_add(export_opts, &error_fatal);
1174 qapi_free_BlockExportOptions(export_opts);
1178 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &opts);
1180 error_report("Failed to create client thread: %s", strerror(ret));
1185 /* Shut up GCC warnings. */
1186 memset(&client_thread, 0, sizeof(client_thread));
1189 nbd_update_server_watch();
1191 if (pid_file_name) {
1192 qemu_write_pidfile(pid_file_name, &error_fatal);
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",
1203 if (opts.fork_process) {
1204 nbd_client_release_pipe(opts.old_stderr);
1209 main_loop_wait(false);
1210 if (state == TERMINATE) {
1211 blk_exp_close_all();
1214 } while (state != TERMINATED);
1221 qemu_opts_del(sn_opts);
1225 pthread_join(client_thread, &result);
1226 ret = (intptr_t)result;