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