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
77 static SocketAddress
*saddr
;
78 static int persistent
= 0;
79 static enum { RUNNING
, TERMINATE
, TERMINATED
} state
;
80 static int shared
= 1;
82 static QIONetListener
*server
;
83 static QCryptoTLSCreds
*tlscreds
;
84 static const char *tlsauthz
;
86 static void usage(const char *name
)
89 "Usage: %s [OPTIONS] FILE\n"
90 " or: %s -L [OPTIONS]\n"
91 "QEMU Disk Network Block Device Utility\n"
93 " -h, --help display this help and exit\n"
94 " -V, --version output version information and exit\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"
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"
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"
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"
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"
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"
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"
154 QEMU_HELP_BOTTOM
"\n"
155 , name
, name
, NBD_DEFAULT_PORT
, "DEVICE");
158 static void version(const char *name
)
161 "%s " QEMU_FULL_VERSION
"\n"
162 "Written by Anthony Liguori.\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"
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
);
180 #endif /* CONFIG_POSIX */
182 static int qemu_nbd_client_list(SocketAddress
*saddr
, QCryptoTLSCreds
*tls
,
183 const char *hostname
)
185 int ret
= EXIT_FAILURE
;
188 QIOChannelSocket
*sioc
;
192 sioc
= qio_channel_socket_new();
193 if (qio_channel_socket_connect_sync(sioc
, saddr
, &err
) < 0) {
194 error_report_err(err
);
197 rc
= nbd_receive_export_list(QIO_CHANNEL(sioc
), tls
, hostname
, &list
,
201 error_report_err(err
);
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
]);
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
);
255 object_unref(OBJECT(sioc
));
261 static void *show_parts(void *arg
)
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
);
278 struct NbdClientOpts
{
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
;
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
,
300 error_report_err(local_error
);
304 if (nbd_receive_negotiate(NULL
, QIO_CHANNEL(sioc
),
305 NULL
, NULL
, NULL
, &info
, &local_error
) < 0) {
307 error_report_err(local_error
);
312 fd
= open(opts
->device
, O_RDWR
);
314 /* Linux-only, we can use %m in printf. */
315 error_report("Failed to open %s: %m", opts
->device
);
319 if (nbd_init(fd
, sioc
, &info
, &local_error
) < 0) {
320 error_report_err(local_error
);
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
);
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",
339 if (nbd_client(fd
) < 0) {
349 object_unref(OBJECT(sioc
));
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
)
366 if (negotiated
&& nb_fds
== 0 && !persistent
&& state
== RUNNING
) {
369 nbd_update_server_watch();
370 nbd_client_put(client
);
373 static void nbd_accept(QIONetListener
*listener
, QIOChannelSocket
*cioc
,
376 if (state
>= TERMINATE
) {
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
);
390 qio_net_listener_set_client_func(server
, NULL
, NULL
, NULL
);
395 static SocketAddress
*nbd_build_socket_address(const char *sockpath
,
399 SocketAddress
*saddr
;
401 saddr
= g_new0(SocketAddress
, 1);
403 saddr
->type
= SOCKET_ADDRESS_TYPE_UNIX
;
404 saddr
->u
.q_unix
.path
= g_strdup(sockpath
);
406 InetSocketAddress
*inet
;
407 saddr
->type
= SOCKET_ADDRESS_TYPE_INET
;
408 inet
= &saddr
->u
.inet
;
409 inet
->host
= g_strdup(bindto
);
411 inet
->port
= g_strdup(port
);
413 inet
->port
= g_strdup_printf("%d", NBD_DEFAULT_PORT
);
421 static QemuOptsList file_opts
= {
423 .implied_opt_name
= "file",
424 .head
= QTAILQ_HEAD_INITIALIZER(file_opts
.head
),
426 /* no elements => accept any params */
427 { /* end of list */ }
431 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, bool list
,
435 QCryptoTLSCreds
*creds
;
437 obj
= object_resolve_path_component(
438 object_get_objects_root(), id
);
440 error_setg(errp
, "No TLS credentials with id '%s'",
444 creds
= (QCryptoTLSCreds
*)
445 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
447 error_setg(errp
, "Object with id '%s' is not TLS credentials",
452 if (!qcrypto_tls_creds_check_endpoint(creds
,
454 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
455 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER
,
463 static void setup_address_and_port(const char **address
, const char **port
)
465 if (*address
== NULL
) {
466 *address
= "0.0.0.0";
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
,
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";
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";
505 return "List mode is incompatible with socket activation";
511 static void qemu_nbd_shutdown(void)
513 job_cancel_sync_all();
518 int main(int argc
, char **argv
)
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
;
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
},
573 int flags
= BDRV_O_RDWR
;
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;
594 unsigned socket_activation
;
595 const char *pid_file_name
= NULL
;
596 const char *selinux_label
= NULL
;
597 BlockExportOptions
*export_opts
;
599 struct NbdClientOpts opts
;
603 os_setup_early_signal_handling();
604 os_setup_signal_handling();
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) {
619 flags
|= BDRV_O_SNAPSHOT
;
622 optarg
= (char *) "none";
624 case QEMU_NBD_OPT_CACHE
:
626 error_report("-n and --cache can only be specified once");
630 if (bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
) == -1) {
631 error_report("Invalid cache mode `%s'", optarg
);
635 case QEMU_NBD_OPT_AIO
:
637 error_report("--aio can only be specified once");
641 if (bdrv_parse_aio(optarg
, &flags
) < 0) {
642 error_report("Invalid aio mode '%s'", optarg
);
646 case QEMU_NBD_OPT_DISCARD
:
648 error_report("--discard can only be specified once");
652 if (bdrv_parse_discard_flags(optarg
, &flags
) == -1) {
653 error_report("Invalid discard mode `%s'", optarg
);
657 case QEMU_NBD_OPT_DETECT_ZEROES
:
659 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
,
661 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
,
664 error_reportf_err(local_err
,
665 "Failed to parse detect_zeroes mode: ");
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");
682 if (qemu_strtou64(optarg
, NULL
, 0, &dev_offset
) < 0) {
683 error_report("Invalid offset '%s'", optarg
);
688 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
689 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
692 error_report("Failed in parsing snapshot param `%s'",
697 sn_id_or_name
= optarg
;
702 flags
&= ~BDRV_O_RDWR
;
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
);
719 if (sockpath
[0] != '/') {
720 error_report("socket path must be absolute");
731 if (qemu_strtoi(optarg
, NULL
, 0, &shared
) < 0 ||
733 error_report("Invalid shared device number '%s'", optarg
);
744 export_name
= optarg
;
745 if (strlen(export_name
) > NBD_MAX_STRING_SIZE
) {
746 error_report("export name '%s' too long", export_name
);
751 export_description
= optarg
;
752 if (strlen(export_description
) > NBD_MAX_STRING_SIZE
) {
753 error_report("export description '%s' too long",
770 error_report("Try `%s --help' for more information.", argv
[0]);
772 case QEMU_NBD_OPT_OBJECT
:
773 user_creatable_process_cmdline(optarg
);
775 case QEMU_NBD_OPT_TLSCREDS
:
778 case QEMU_NBD_OPT_TLSHOSTNAME
:
779 tlshostname
= optarg
;
781 case QEMU_NBD_OPT_IMAGE_OPTS
:
785 trace_opt_parse(optarg
);
787 case QEMU_NBD_OPT_TLSAUTHZ
:
790 case QEMU_NBD_OPT_FORK
:
796 case QEMU_NBD_OPT_PID_FILE
:
797 pid_file_name
= optarg
;
799 case QEMU_NBD_OPT_SELINUX_LABEL
:
800 selinux_label
= optarg
;
806 if (argc
!= optind
) {
807 error_report("List mode is incompatible with a file name");
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");
817 error_report("List mode is incompatible with forking");
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]);
824 } else if (!export_name
) {
828 if (!trace_init_backends()) {
832 qemu_set_log(LOG_TRACE
, &error_fatal
);
834 socket_activation
= check_socket_activation();
835 if (socket_activation
== 0) {
837 setup_address_and_port(&bindto
, &port
);
840 /* Using socket activation - check user didn't use -p etc. */
841 const char *err_msg
= socket_activation_validate_opts(device
, sockpath
,
845 if (err_msg
!= NULL
) {
846 error_report("%s", err_msg
);
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",
860 error_report("TLS is not supported with a host device");
863 if (tlsauthz
&& list
) {
864 error_report("TLS authorization is incompatible with export list");
867 if (tlshostname
&& !list
) {
868 error_report("TLS hostname is only supported with export list");
871 tlscreds
= nbd_get_tls_creds(tlscredsid
, list
, &local_err
);
873 error_reportf_err(local_err
, "Failed to get TLS creds: ");
878 error_report("--tls-authz is not permitted without --tls-creds");
882 error_report("--tls-hostname is not permitted without --tls-creds");
888 #ifdef CONFIG_SELINUX
889 if (sockpath
== NULL
&& device
== NULL
) {
890 error_report("--selinux-label is not permitted without --socket");
894 error_report("SELinux support not enabled in this binary");
900 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
901 return qemu_nbd_client_list(saddr
, tlscreds
,
902 tlshostname
? tlshostname
: bindto
);
906 if (disconnect
|| device
) {
907 error_report("Kernel /dev/nbdN support not available");
910 #else /* HAVE_NBD_DEVICE */
912 int nbdfd
= open(argv
[optind
], O_RDWR
);
914 error_report("Cannot open %s: %s", argv
[optind
],
918 nbd_disconnect(nbdfd
);
922 printf("%s disconnected\n", argv
[optind
]);
928 if ((device
&& !verbose
) || fork_process
) {
930 g_autoptr(GError
) err
= NULL
;
935 if (!g_unix_open_pipe(stderr_fd
, FD_CLOEXEC
, &err
)) {
936 error_report("Error setting up communication pipe: %s",
941 /* Now daemonize, but keep a communication channel open to
942 * print errors and exit with the proper status code.
946 error_report("Failed to fork: %s", strerror(errno
));
948 } else if (pid
== 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) {
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
967 ret
= write(stderr_fd
[1], str
, strlen(str
));
972 error_report("Failed to daemonize: %s", strerror(saved_errno
));
976 /* ... close the descriptor we inherited and go on. */
982 /* In the parent. Print error messages from the child until
983 * it closes the pipe.
986 buf
= g_malloc(1024);
987 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
989 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
995 error_report("Cannot read from daemon: %s",
1000 /* Usually the daemon should not print any message.
1001 * Exit with zero status in that case.
1006 error_report("Unable to fork into background on Windows hosts");
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) {
1020 if (persistent
|| shared
== 0) {
1021 backlog
= SOMAXCONN
;
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
));
1032 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
1033 if (qio_net_listener_open_sync(server
, saddr
, backlog
,
1035 object_unref(OBJECT(server
));
1036 error_report_err(local_err
);
1039 #ifdef CONFIG_SELINUX
1040 if (selinux_label
&& setsockcreatecon_raw(NULL
) == -1) {
1041 error_report("Cannot clear SELinux socket create context: %s",
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
,
1054 object_unref(OBJECT(server
));
1055 error_reportf_err(local_err
,
1056 "Failed to use socket activation: ");
1059 qio_net_listener_add(server
, sioc
);
1060 object_unref(OBJECT(sioc
));
1064 qemu_init_main_loop(&error_fatal
);
1066 atexit(qemu_nbd_shutdown
);
1068 srcpath
= argv
[optind
];
1072 error_report("--image-opts and -f are mutually exclusive");
1075 opts
= qemu_opts_parse_noisily(&file_opts
, srcpath
, true);
1077 qemu_opts_reset(&file_opts
);
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
);
1085 options
= qdict_new();
1086 qdict_put_str(options
, "driver", fmt
);
1088 blk
= blk_new_open(srcpath
, NULL
, options
, flags
, &local_err
);
1092 error_reportf_err(local_err
, "Failed to blk_new_open '%s': ",
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());
1109 blk_insert_bs(blk
, bs
, &error_fatal
);
1113 blk_set_enable_write_cache(blk
, !writethrough
);
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
),
1120 } else if (sn_id_or_name
) {
1121 ret
= bdrv_snapshot_load_tmp_by_id_or_name(bs
, sn_id_or_name
,
1125 error_reportf_err(local_err
, "Failed to load snapshot: ");
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
,
1143 .name
= g_strdup(export_name
),
1144 .description
= g_strdup(export_description
),
1145 .has_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
);
1157 opts
= (struct NbdClientOpts
) {
1159 .fork_process
= fork_process
,
1163 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, &opts
);
1165 error_report("Failed to create client thread: %s", strerror(ret
));
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",
1189 if (dup2(STDOUT_FILENO
, STDERR_FILENO
) < 0) {
1190 error_report("Could not set stderr to /dev/null: %s",
1198 main_loop_wait(false);
1199 if (state
== TERMINATE
) {
1200 blk_exp_close_all();
1203 } while (state
!= TERMINATED
);
1210 qemu_opts_del(sn_opts
);
1214 pthread_join(client_thread
, &ret
);