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 "qapi/error.h"
25 #include "qemu/cutils.h"
26 #include "sysemu/block-backend.h"
27 #include "block/block_int.h"
28 #include "block/nbd.h"
29 #include "qemu/main-loop.h"
30 #include "qemu/option.h"
31 #include "qemu/error-report.h"
32 #include "qemu/config-file.h"
33 #include "qemu/bswap.h"
35 #include "qemu/systemd.h"
36 #include "block/snapshot.h"
37 #include "qapi/qmp/qdict.h"
38 #include "qapi/qmp/qstring.h"
39 #include "qom/object_interfaces.h"
40 #include "io/channel-socket.h"
41 #include "io/net-listener.h"
42 #include "crypto/init.h"
43 #include "trace/control.h"
44 #include "qemu-version.h"
47 #define HAVE_NBD_DEVICE 1
49 #define HAVE_NBD_DEVICE 0
52 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
53 #define QEMU_NBD_OPT_CACHE 256
54 #define QEMU_NBD_OPT_AIO 257
55 #define QEMU_NBD_OPT_DISCARD 258
56 #define QEMU_NBD_OPT_DETECT_ZEROES 259
57 #define QEMU_NBD_OPT_OBJECT 260
58 #define QEMU_NBD_OPT_TLSCREDS 261
59 #define QEMU_NBD_OPT_IMAGE_OPTS 262
60 #define QEMU_NBD_OPT_FORK 263
64 static NBDExport *export;
67 static SocketAddress *saddr;
68 static int persistent = 0;
69 static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
70 static int shared = 1;
72 static QIONetListener *server;
73 static QCryptoTLSCreds *tlscreds;
75 static void usage(const char *name)
78 "Usage: %s [OPTIONS] FILE\n"
79 " or: %s -L [OPTIONS]\n"
80 "QEMU Disk Network Block Device Utility\n"
82 " -h, --help display this help and exit\n"
83 " -V, --version output version information and exit\n"
85 "Connection properties:\n"
86 " -p, --port=PORT port to listen on (default `%d')\n"
87 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
88 " -k, --socket=PATH path to the unix socket\n"
89 " (default '"SOCKET_PATH"')\n"
90 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
91 " -t, --persistent don't exit on the last connection\n"
92 " -v, --verbose display extra debugging information\n"
93 " -x, --export-name=NAME expose export by name (default is empty string)\n"
94 " -D, --description=TEXT export a human-readable description\n"
96 "Exposing part of the image:\n"
97 " -o, --offset=OFFSET offset into the image\n"
98 " -P, --partition=NUM only expose partition NUM\n"
99 " -B, --bitmap=NAME expose a persistent dirty bitmap\n"
101 "General purpose options:\n"
102 " -L, --list list exports available from another NBD server\n"
103 " --object type,id=ID,... define an object such as 'secret' for providing\n"
104 " passwords and/or encryption keys\n"
105 " --tls-creds=ID use id of an earlier --object to provide TLS\n"
106 " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
107 " specify tracing options\n"
108 " --fork fork off the server process and exit the parent\n"
109 " once the server is running\n"
112 "Kernel NBD client support:\n"
113 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
114 " -d, --disconnect disconnect the specified device\n"
117 "Block device options:\n"
118 " -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
119 " -r, --read-only export read-only\n"
120 " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
121 " file with backing_file=FILE, redirect the write to\n"
122 " the temporary one\n"
123 " -l, --load-snapshot=SNAPSHOT_PARAM\n"
124 " load an internal snapshot inside FILE and export it\n"
125 " as an read-only device, SNAPSHOT_PARAM format is\n"
126 " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
128 " -n, --nocache disable host cache\n"
129 " --cache=MODE set cache mode (none, writeback, ...)\n"
130 " --aio=MODE set AIO mode (native or threads)\n"
131 " --discard=MODE set discard mode (ignore, unmap)\n"
132 " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
133 " --image-opts treat FILE as a full set of image options\n"
135 QEMU_HELP_BOTTOM "\n"
136 , name, name, NBD_DEFAULT_PORT, "DEVICE");
139 static void version(const char *name)
142 "%s " QEMU_FULL_VERSION "\n"
143 "Written by Anthony Liguori.\n"
146 "This is free software; see the source for copying conditions. There is NO\n"
147 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
151 struct partition_record
155 uint32_t start_cylinder;
156 uint8_t start_sector;
159 uint8_t end_cylinder;
161 uint32_t start_sector_abs;
162 uint32_t nb_sectors_abs;
165 static void read_partition(uint8_t *p, struct partition_record *r)
168 r->start_head = p[1];
169 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
170 r->start_sector = p[2] & 0x3f;
173 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
174 r->end_sector = p[6] & 0x3f;
176 r->start_sector_abs = ldl_le_p(p + 8);
177 r->nb_sectors_abs = ldl_le_p(p + 12);
180 static int find_partition(BlockBackend *blk, int partition,
181 uint64_t *offset, uint64_t *size)
183 struct partition_record mbr[4];
184 uint8_t data[MBR_SIZE];
189 ret = blk_pread(blk, 0, data, sizeof(data));
191 error_report("error while reading: %s", strerror(-ret));
195 if (data[510] != 0x55 || data[511] != 0xaa) {
199 for (i = 0; i < 4; i++) {
200 read_partition(&data[446 + 16 * i], &mbr[i]);
202 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
206 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
207 struct partition_record ext[4];
208 uint8_t data1[MBR_SIZE];
211 ret = blk_pread(blk, mbr[i].start_sector_abs * MBR_SIZE,
212 data1, sizeof(data1));
214 error_report("error while reading: %s", strerror(-ret));
218 for (j = 0; j < 4; j++) {
219 read_partition(&data1[446 + 16 * j], &ext[j]);
220 if (!ext[j].system || !ext[j].nb_sectors_abs) {
224 if ((ext_partnum + j + 1) == partition) {
225 *offset = (uint64_t)ext[j].start_sector_abs << 9;
226 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
231 } else if ((i + 1) == partition) {
232 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
233 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
241 static void termsig_handler(int signum)
243 atomic_cmpxchg(&state, RUNNING, TERMINATE);
248 static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
249 const char *hostname)
251 int ret = EXIT_FAILURE;
254 QIOChannelSocket *sioc;
258 sioc = qio_channel_socket_new();
259 if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
260 error_report_err(err);
263 rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
267 error_report_err(err);
271 printf("exports available: %d\n", rc);
272 for (i = 0; i < rc; i++) {
273 printf(" export: '%s'\n", list[i].name);
274 if (list[i].description && *list[i].description) {
275 printf(" description: %s\n", list[i].description);
277 if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
278 printf(" size: %" PRIu64 "\n", list[i].size);
279 printf(" flags: 0x%x (", list[i].flags);
280 if (list[i].flags & NBD_FLAG_READ_ONLY) {
283 if (list[i].flags & NBD_FLAG_SEND_FLUSH) {
286 if (list[i].flags & NBD_FLAG_SEND_FUA) {
289 if (list[i].flags & NBD_FLAG_ROTATIONAL) {
290 printf(" rotational");
292 if (list[i].flags & NBD_FLAG_SEND_TRIM) {
295 if (list[i].flags & NBD_FLAG_SEND_WRITE_ZEROES) {
298 if (list[i].flags & NBD_FLAG_SEND_DF) {
301 if (list[i].flags & NBD_FLAG_CAN_MULTI_CONN) {
304 if (list[i].flags & NBD_FLAG_SEND_RESIZE) {
307 if (list[i].flags & NBD_FLAG_SEND_CACHE) {
312 if (list[i].min_block) {
313 printf(" min block: %u\n", list[i].min_block);
314 printf(" opt block: %u\n", list[i].opt_block);
315 printf(" max block: %u\n", list[i].max_block);
317 if (list[i].n_contexts) {
318 printf(" available meta contexts: %d\n", list[i].n_contexts);
319 for (j = 0; j < list[i].n_contexts; j++) {
320 printf(" %s\n", list[i].contexts[j]);
324 nbd_free_export_list(list, rc);
328 object_unref(OBJECT(sioc));
334 static void *show_parts(void *arg)
339 /* linux just needs an open() to trigger
340 * the partition table update
341 * but remember to load the module with max_part != 0 :
342 * modprobe nbd max_part=63
344 nbd = open(device, O_RDWR);
351 static void *nbd_client_thread(void *arg)
354 NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
355 QIOChannelSocket *sioc;
358 pthread_t show_parts_thread;
359 Error *local_error = NULL;
361 sioc = qio_channel_socket_new();
362 if (qio_channel_socket_connect_sync(sioc,
365 error_report_err(local_error);
369 ret = nbd_receive_negotiate(QIO_CHANNEL(sioc),
370 NULL, NULL, NULL, &info, &local_error);
373 error_report_err(local_error);
378 fd = open(device, O_RDWR);
380 /* Linux-only, we can use %m in printf. */
381 error_report("Failed to open %s: %m", device);
385 ret = nbd_init(fd, sioc, &info, &local_error);
387 error_report_err(local_error);
391 /* update partition table */
392 pthread_create(&show_parts_thread, NULL, show_parts, device);
395 fprintf(stderr, "NBD device %s is now connected to %s\n",
398 /* Close stderr so that the qemu-nbd process exits. */
399 dup2(STDOUT_FILENO, STDERR_FILENO);
402 ret = nbd_client(fd);
407 object_unref(OBJECT(sioc));
409 kill(getpid(), SIGTERM);
410 return (void *) EXIT_SUCCESS;
415 object_unref(OBJECT(sioc));
418 kill(getpid(), SIGTERM);
419 return (void *) EXIT_FAILURE;
421 #endif /* HAVE_NBD_DEVICE */
423 static int nbd_can_accept(void)
425 return state == RUNNING && nb_fds < shared;
428 static void nbd_export_closed(NBDExport *export)
430 assert(state == TERMINATING);
434 static void nbd_update_server_watch(void);
436 static void nbd_client_closed(NBDClient *client, bool negotiated)
439 if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
442 nbd_update_server_watch();
443 nbd_client_put(client);
446 static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
449 if (state >= TERMINATE) {
454 nbd_update_server_watch();
455 nbd_client_new(cioc, tlscreds, NULL, nbd_client_closed);
458 static void nbd_update_server_watch(void)
460 if (nbd_can_accept()) {
461 qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
463 qio_net_listener_set_client_func(server, NULL, NULL, NULL);
468 static SocketAddress *nbd_build_socket_address(const char *sockpath,
472 SocketAddress *saddr;
474 saddr = g_new0(SocketAddress, 1);
476 saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
477 saddr->u.q_unix.path = g_strdup(sockpath);
479 InetSocketAddress *inet;
480 saddr->type = SOCKET_ADDRESS_TYPE_INET;
481 inet = &saddr->u.inet;
482 inet->host = g_strdup(bindto);
484 inet->port = g_strdup(port);
486 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
494 static QemuOptsList file_opts = {
496 .implied_opt_name = "file",
497 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
499 /* no elements => accept any params */
500 { /* end of list */ }
504 static QemuOptsList qemu_object_opts = {
506 .implied_opt_name = "qom-type",
507 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
515 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
519 QCryptoTLSCreds *creds;
521 obj = object_resolve_path_component(
522 object_get_objects_root(), id);
524 error_setg(errp, "No TLS credentials with id '%s'",
528 creds = (QCryptoTLSCreds *)
529 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
531 error_setg(errp, "Object with id '%s' is not TLS credentials",
537 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
539 "Expecting TLS credentials with a client endpoint");
543 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
545 "Expecting TLS credentials with a server endpoint");
553 static void setup_address_and_port(const char **address, const char **port)
555 if (*address == NULL) {
556 *address = "0.0.0.0";
560 *port = stringify(NBD_DEFAULT_PORT);
565 * Check socket parameters compatibility when socket activation is used.
567 static const char *socket_activation_validate_opts(const char *device,
568 const char *sockpath,
573 if (device != NULL) {
574 return "NBD device can't be set when using socket activation";
577 if (sockpath != NULL) {
578 return "Unix socket can't be set when using socket activation";
581 if (address != NULL) {
582 return "The interface can't be set when using socket activation";
586 return "TCP port number can't be set when using socket activation";
590 return "List mode is incompatible with socket activation";
596 static void qemu_nbd_shutdown(void)
598 job_cancel_sync_all();
602 int main(int argc, char **argv)
605 BlockDriverState *bs;
606 uint64_t dev_offset = 0;
607 uint16_t nbdflags = 0;
608 bool disconnect = false;
609 const char *bindto = NULL;
610 const char *port = NULL;
611 char *sockpath = NULL;
614 QemuOpts *sn_opts = NULL;
615 const char *sn_id_or_name = NULL;
616 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:T:D:B:L";
617 struct option lopt[] = {
618 { "help", no_argument, NULL, 'h' },
619 { "version", no_argument, NULL, 'V' },
620 { "bind", required_argument, NULL, 'b' },
621 { "port", required_argument, NULL, 'p' },
622 { "socket", required_argument, NULL, 'k' },
623 { "offset", required_argument, NULL, 'o' },
624 { "read-only", no_argument, NULL, 'r' },
625 { "partition", required_argument, NULL, 'P' },
626 { "bitmap", required_argument, NULL, 'B' },
627 { "connect", required_argument, NULL, 'c' },
628 { "disconnect", no_argument, NULL, 'd' },
629 { "list", no_argument, NULL, 'L' },
630 { "snapshot", no_argument, NULL, 's' },
631 { "load-snapshot", required_argument, NULL, 'l' },
632 { "nocache", no_argument, NULL, 'n' },
633 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
634 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
635 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
636 { "detect-zeroes", required_argument, NULL,
637 QEMU_NBD_OPT_DETECT_ZEROES },
638 { "shared", required_argument, NULL, 'e' },
639 { "format", required_argument, NULL, 'f' },
640 { "persistent", no_argument, NULL, 't' },
641 { "verbose", no_argument, NULL, 'v' },
642 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
643 { "export-name", required_argument, NULL, 'x' },
644 { "description", required_argument, NULL, 'D' },
645 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
646 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
647 { "trace", required_argument, NULL, 'T' },
648 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
653 int flags = BDRV_O_RDWR;
656 bool seen_cache = false;
657 bool seen_discard = false;
658 bool seen_aio = false;
659 pthread_t client_thread;
660 const char *fmt = NULL;
661 Error *local_err = NULL;
662 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
663 QDict *options = NULL;
664 const char *export_name = NULL; /* defaults to "" later for server mode */
665 const char *export_description = NULL;
666 const char *bitmap = NULL;
667 const char *tlscredsid = NULL;
668 bool imageOpts = false;
669 bool writethrough = true;
670 char *trace_file = NULL;
671 bool fork_process = false;
674 unsigned socket_activation;
676 /* The client thread uses SIGTERM to interrupt the server. A signal
677 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
679 struct sigaction sa_sigterm;
680 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
681 sa_sigterm.sa_handler = termsig_handler;
682 sigaction(SIGTERM, &sa_sigterm, NULL);
685 signal(SIGPIPE, SIG_IGN);
688 module_call_init(MODULE_INIT_TRACE);
689 error_set_progname(argv[0]);
690 qcrypto_init(&error_fatal);
692 module_call_init(MODULE_INIT_QOM);
693 qemu_add_opts(&qemu_object_opts);
694 qemu_add_opts(&qemu_trace_opts);
695 qemu_init_exec_dir(argv[0]);
697 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
700 flags |= BDRV_O_SNAPSHOT;
703 optarg = (char *) "none";
705 case QEMU_NBD_OPT_CACHE:
707 error_report("-n and --cache can only be specified once");
711 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
712 error_report("Invalid cache mode `%s'", optarg);
716 case QEMU_NBD_OPT_AIO:
718 error_report("--aio can only be specified once");
722 if (!strcmp(optarg, "native")) {
723 flags |= BDRV_O_NATIVE_AIO;
724 } else if (!strcmp(optarg, "threads")) {
725 /* this is the default */
727 error_report("invalid aio mode `%s'", optarg);
731 case QEMU_NBD_OPT_DISCARD:
733 error_report("--discard can only be specified once");
737 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
738 error_report("Invalid discard mode `%s'", optarg);
742 case QEMU_NBD_OPT_DETECT_ZEROES:
744 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
746 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
749 error_reportf_err(local_err,
750 "Failed to parse detect_zeroes mode: ");
753 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
754 !(flags & BDRV_O_UNMAP)) {
755 error_report("setting detect-zeroes to unmap is not allowed "
756 "without setting discard operation to unmap");
767 if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
768 error_report("Invalid offset '%s'", optarg);
773 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
774 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
777 error_report("Failed in parsing snapshot param `%s'",
782 sn_id_or_name = optarg;
786 nbdflags |= NBD_FLAG_READ_ONLY;
787 flags &= ~BDRV_O_RDWR;
790 warn_report("The '-P' option is deprecated; use --image-opts with "
791 "a raw device wrapper for subset exports instead");
792 if (qemu_strtoi(optarg, NULL, 0, &partition) < 0 ||
793 partition < 1 || partition > 8) {
794 error_report("Invalid partition '%s'", optarg);
803 if (sockpath[0] != '/') {
804 error_report("socket path must be absolute");
815 if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
817 error_report("Invalid shared device number '%s'", optarg);
828 export_name = optarg;
831 export_description = optarg;
845 error_report("Try `%s --help' for more information.", argv[0]);
847 case QEMU_NBD_OPT_OBJECT: {
849 opts = qemu_opts_parse_noisily(&qemu_object_opts,
855 case QEMU_NBD_OPT_TLSCREDS:
858 case QEMU_NBD_OPT_IMAGE_OPTS:
863 trace_file = trace_opt_parse(optarg);
865 case QEMU_NBD_OPT_FORK:
875 if (argc != optind) {
876 error_report("List mode is incompatible with a file name");
879 if (export_name || export_description || dev_offset || partition ||
880 device || disconnect || fmt || sn_id_or_name || bitmap ||
881 seen_aio || seen_discard || seen_cache) {
882 error_report("List mode is incompatible with per-device settings");
886 error_report("List mode is incompatible with forking");
889 } else if ((argc - optind) != 1) {
890 error_report("Invalid number of arguments");
891 error_printf("Try `%s --help' for more information.\n", argv[0]);
893 } else if (!export_name) {
897 qemu_opts_foreach(&qemu_object_opts,
898 user_creatable_add_opts_foreach,
901 if (!trace_init_backends()) {
904 trace_init_file(trace_file);
905 qemu_set_log(LOG_TRACE);
907 socket_activation = check_socket_activation();
908 if (socket_activation == 0) {
909 setup_address_and_port(&bindto, &port);
911 /* Using socket activation - check user didn't use -p etc. */
912 const char *err_msg = socket_activation_validate_opts(device, sockpath,
915 if (err_msg != NULL) {
916 error_report("%s", err_msg);
920 /* qemu-nbd can only listen on a single socket. */
921 if (socket_activation > 1) {
922 error_report("qemu-nbd does not support socket activation with %s > 1",
930 error_report("TLS is only supported with IPv4/IPv6");
934 error_report("TLS is not supported with a host device");
937 tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
939 error_report("Failed to get TLS creds %s",
940 error_get_pretty(local_err));
946 saddr = nbd_build_socket_address(sockpath, bindto, port);
947 return qemu_nbd_client_list(saddr, tlscreds, bindto);
951 if (disconnect || device) {
952 error_report("Kernel /dev/nbdN support not available");
955 #else /* HAVE_NBD_DEVICE */
957 int nbdfd = open(argv[optind], O_RDWR);
959 error_report("Cannot open %s: %s", argv[optind],
963 nbd_disconnect(nbdfd);
967 printf("%s disconnected\n", argv[optind]);
973 if ((device && !verbose) || fork_process) {
978 if (qemu_pipe(stderr_fd) < 0) {
979 error_report("Error setting up communication pipe: %s",
984 /* Now daemonize, but keep a communication channel open to
985 * print errors and exit with the proper status code.
989 error_report("Failed to fork: %s", strerror(errno));
991 } else if (pid == 0) {
993 ret = qemu_daemon(1, 0);
995 /* Temporarily redirect stderr to the parent's pipe... */
996 old_stderr = dup(STDERR_FILENO);
997 dup2(stderr_fd[1], STDERR_FILENO);
999 error_report("Failed to daemonize: %s", strerror(errno));
1003 /* ... close the descriptor we inherited and go on. */
1004 close(stderr_fd[1]);
1006 bool errors = false;
1009 /* In the parent. Print error messages from the child until
1010 * it closes the pipe.
1012 close(stderr_fd[1]);
1013 buf = g_malloc(1024);
1014 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
1016 ret = qemu_write_full(STDERR_FILENO, buf, ret);
1022 error_report("Cannot read from daemon: %s",
1027 /* Usually the daemon should not print any message.
1028 * Exit with zero status in that case.
1034 if (device != NULL && sockpath == NULL) {
1035 sockpath = g_malloc(128);
1036 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
1039 server = qio_net_listener_new();
1040 if (socket_activation == 0) {
1041 saddr = nbd_build_socket_address(sockpath, bindto, port);
1042 if (qio_net_listener_open_sync(server, saddr, &local_err) < 0) {
1043 object_unref(OBJECT(server));
1044 error_report_err(local_err);
1049 /* See comment in check_socket_activation above. */
1050 for (i = 0; i < socket_activation; i++) {
1051 QIOChannelSocket *sioc;
1052 sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
1055 object_unref(OBJECT(server));
1056 error_report("Failed to use socket activation: %s",
1057 error_get_pretty(local_err));
1060 qio_net_listener_add(server, sioc);
1061 object_unref(OBJECT(sioc));
1065 if (qemu_init_main_loop(&local_err)) {
1066 error_report_err(local_err);
1070 atexit(qemu_nbd_shutdown);
1072 srcpath = argv[optind];
1076 error_report("--image-opts and -f are mutually exclusive");
1079 opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
1081 qemu_opts_reset(&file_opts);
1084 options = qemu_opts_to_qdict(opts, NULL);
1085 qemu_opts_reset(&file_opts);
1086 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
1089 options = qdict_new();
1090 qdict_put_str(options, "driver", fmt);
1092 blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
1096 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1102 blk_set_enable_write_cache(blk, !writethrough);
1105 ret = bdrv_snapshot_load_tmp(bs,
1106 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1107 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1109 } else if (sn_id_or_name) {
1110 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1114 error_reportf_err(local_err, "Failed to load snapshot: ");
1118 bs->detect_zeroes = detect_zeroes;
1119 fd_size = blk_getlength(blk);
1121 error_report("Failed to determine the image length: %s",
1122 strerror(-fd_size));
1126 if (dev_offset >= fd_size) {
1127 error_report("Offset (%" PRIu64 ") has to be smaller than the image "
1128 "size (%" PRId64 ")", dev_offset, fd_size);
1131 fd_size -= dev_offset;
1137 error_report("Cannot request partition and offset together");
1140 ret = find_partition(blk, partition, &dev_offset, &limit);
1142 error_report("Could not find partition %d: %s", partition,
1147 * MBR partition limits are (32-bit << 9); this assert lets
1148 * the compiler know that we can't overflow 64 bits.
1150 assert(dev_offset + limit >= dev_offset);
1151 if (dev_offset + limit > fd_size) {
1152 error_report("Discovered partition %d at offset %" PRIu64
1153 " size %" PRIu64 ", but size exceeds file length %"
1154 PRId64, partition, dev_offset, limit, fd_size);
1160 export = nbd_export_new(bs, dev_offset, fd_size, export_name,
1161 export_description, bitmap, nbdflags,
1162 nbd_export_closed, writethrough, NULL,
1169 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
1171 error_report("Failed to create client thread: %s", strerror(ret));
1176 /* Shut up GCC warnings. */
1177 memset(&client_thread, 0, sizeof(client_thread));
1180 nbd_update_server_watch();
1182 /* now when the initialization is (almost) complete, chdir("/")
1183 * to free any busy filesystems */
1184 if (chdir("/") < 0) {
1185 error_report("Could not chdir to root directory: %s",
1191 dup2(old_stderr, STDERR_FILENO);
1197 main_loop_wait(false);
1198 if (state == TERMINATE) {
1199 state = TERMINATING;
1200 nbd_export_close(export);
1201 nbd_export_put(export);
1204 } while (state != TERMINATED);
1211 qemu_opts_del(sn_opts);
1215 pthread_join(client_thread, &ret);