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
78 static SocketAddress
*saddr
;
79 static int persistent
= 0;
80 static enum { RUNNING
, TERMINATE
, TERMINATED
} state
;
81 static int shared
= 1;
83 static QIONetListener
*server
;
84 static QCryptoTLSCreds
*tlscreds
;
85 static const char *tlsauthz
;
87 static void usage(const char *name
)
90 "Usage: %s [OPTIONS] FILE\n"
91 " or: %s -L [OPTIONS]\n"
92 "QEMU Disk Network Block Device Utility\n"
94 " -h, --help display this help and exit\n"
95 " -V, --version output version information and exit\n"
97 "Connection properties:\n"
98 " -p, --port=PORT port to listen on (default `%d')\n"
99 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
100 " -k, --socket=PATH path to the unix socket\n"
101 " (default '"SOCKET_PATH
"')\n"
102 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
103 " -t, --persistent don't exit on the last connection\n"
104 " -v, --verbose display extra debugging information\n"
105 " -x, --export-name=NAME expose export by name (default is empty string)\n"
106 " -D, --description=TEXT export a human-readable description\n"
108 "Exposing part of the image:\n"
109 " -o, --offset=OFFSET offset into the image\n"
110 " -A, --allocation-depth expose the allocation depth\n"
111 " -B, --bitmap=NAME expose a persistent dirty bitmap\n"
113 "General purpose options:\n"
114 " -L, --list list exports available from another NBD server\n"
115 " --object type,id=ID,... define an object such as 'secret' for providing\n"
116 " passwords and/or encryption keys\n"
117 " --tls-creds=ID use id of an earlier --object to provide TLS\n"
118 " --tls-authz=ID use id of an earlier --object to provide\n"
120 " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
121 " specify tracing options\n"
122 " --fork fork off the server process and exit the parent\n"
123 " once the server is running\n"
124 " --pid-file=PATH store the server's process ID in the given file\n"
125 #ifdef CONFIG_SELINUX
126 " --selinux-label=LABEL set SELinux process label on listening socket\n"
130 "Kernel NBD client support:\n"
131 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
132 " -d, --disconnect disconnect the specified device\n"
135 "Block device options:\n"
136 " -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
137 " -r, --read-only export read-only\n"
138 " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
139 " file with backing_file=FILE, redirect the write to\n"
140 " the temporary one\n"
141 " -l, --load-snapshot=SNAPSHOT_PARAM\n"
142 " load an internal snapshot inside FILE and export it\n"
143 " as an read-only device, SNAPSHOT_PARAM format is\n"
144 " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
146 " -n, --nocache disable host cache\n"
147 " --cache=MODE set cache mode used to access the disk image, the\n"
148 " valid options are: 'none', 'writeback' (default),\n"
149 " 'writethrough', 'directsync' and 'unsafe'\n"
150 " --aio=MODE set AIO mode (native, io_uring or threads)\n"
151 " --discard=MODE set discard mode (ignore, unmap)\n"
152 " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
153 " --image-opts treat FILE as a full set of image options\n"
155 QEMU_HELP_BOTTOM
"\n"
156 , name
, name
, NBD_DEFAULT_PORT
, "DEVICE");
159 static void version(const char *name
)
162 "%s " QEMU_FULL_VERSION
"\n"
163 "Written by Anthony Liguori.\n"
166 "This is free software; see the source for copying conditions. There is NO\n"
167 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
173 * The client thread uses SIGTERM to interrupt the server. A signal
174 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
176 void qemu_system_killed(int signum
, pid_t pid
)
178 qatomic_cmpxchg(&state
, RUNNING
, TERMINATE
);
181 #endif /* CONFIG_POSIX */
183 static int qemu_nbd_client_list(SocketAddress
*saddr
, QCryptoTLSCreds
*tls
,
184 const char *hostname
)
186 int ret
= EXIT_FAILURE
;
189 QIOChannelSocket
*sioc
;
193 sioc
= qio_channel_socket_new();
194 if (qio_channel_socket_connect_sync(sioc
, saddr
, &err
) < 0) {
195 error_report_err(err
);
198 rc
= nbd_receive_export_list(QIO_CHANNEL(sioc
), tls
, hostname
, &list
,
202 error_report_err(err
);
206 printf("exports available: %d\n", rc
);
207 for (i
= 0; i
< rc
; i
++) {
208 printf(" export: '%s'\n", list
[i
].name
);
209 if (list
[i
].description
&& *list
[i
].description
) {
210 printf(" description: %s\n", list
[i
].description
);
212 if (list
[i
].flags
& NBD_FLAG_HAS_FLAGS
) {
213 static const char *const flag_names
[] = {
214 [NBD_FLAG_READ_ONLY_BIT
] = "readonly",
215 [NBD_FLAG_SEND_FLUSH_BIT
] = "flush",
216 [NBD_FLAG_SEND_FUA_BIT
] = "fua",
217 [NBD_FLAG_ROTATIONAL_BIT
] = "rotational",
218 [NBD_FLAG_SEND_TRIM_BIT
] = "trim",
219 [NBD_FLAG_SEND_WRITE_ZEROES_BIT
] = "zeroes",
220 [NBD_FLAG_SEND_DF_BIT
] = "df",
221 [NBD_FLAG_CAN_MULTI_CONN_BIT
] = "multi",
222 [NBD_FLAG_SEND_RESIZE_BIT
] = "resize",
223 [NBD_FLAG_SEND_CACHE_BIT
] = "cache",
224 [NBD_FLAG_SEND_FAST_ZERO_BIT
] = "fast-zero",
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 if (list
[i
].n_contexts
) {
242 printf(" available meta contexts: %d\n", list
[i
].n_contexts
);
243 for (j
= 0; j
< list
[i
].n_contexts
; j
++) {
244 printf(" %s\n", list
[i
].contexts
[j
]);
248 nbd_free_export_list(list
, rc
);
252 object_unref(OBJECT(sioc
));
258 static void *show_parts(void *arg
)
263 /* linux just needs an open() to trigger
264 * the partition table update
265 * but remember to load the module with max_part != 0 :
266 * modprobe nbd max_part=63
268 nbd
= open(device
, O_RDWR
);
275 static void *nbd_client_thread(void *arg
)
278 NBDExportInfo info
= { .request_sizes
= false, .name
= g_strdup("") };
279 QIOChannelSocket
*sioc
;
281 int ret
= EXIT_FAILURE
;
282 pthread_t show_parts_thread
;
283 Error
*local_error
= NULL
;
285 sioc
= qio_channel_socket_new();
286 if (qio_channel_socket_connect_sync(sioc
,
289 error_report_err(local_error
);
293 if (nbd_receive_negotiate(NULL
, QIO_CHANNEL(sioc
),
294 NULL
, NULL
, NULL
, &info
, &local_error
) < 0) {
296 error_report_err(local_error
);
301 fd
= open(device
, O_RDWR
);
303 /* Linux-only, we can use %m in printf. */
304 error_report("Failed to open %s: %m", device
);
308 if (nbd_init(fd
, sioc
, &info
, &local_error
) < 0) {
309 error_report_err(local_error
);
313 /* update partition table */
314 pthread_create(&show_parts_thread
, NULL
, show_parts
, device
);
317 fprintf(stderr
, "NBD device %s is now connected to %s\n",
320 /* Close stderr so that the qemu-nbd process exits. */
321 dup2(STDOUT_FILENO
, STDERR_FILENO
);
324 if (nbd_client(fd
) < 0) {
334 object_unref(OBJECT(sioc
));
336 kill(getpid(), SIGTERM
);
337 return (void *) (intptr_t) ret
;
339 #endif /* HAVE_NBD_DEVICE */
341 static int nbd_can_accept(void)
343 return state
== RUNNING
&& (shared
== 0 || nb_fds
< shared
);
346 static void nbd_update_server_watch(void);
348 static void nbd_client_closed(NBDClient
*client
, bool negotiated
)
351 if (negotiated
&& nb_fds
== 0 && !persistent
&& state
== RUNNING
) {
354 nbd_update_server_watch();
355 nbd_client_put(client
);
358 static void nbd_accept(QIONetListener
*listener
, QIOChannelSocket
*cioc
,
361 if (state
>= TERMINATE
) {
366 nbd_update_server_watch();
367 nbd_client_new(cioc
, tlscreds
, tlsauthz
, nbd_client_closed
);
370 static void nbd_update_server_watch(void)
372 if (nbd_can_accept()) {
373 qio_net_listener_set_client_func(server
, nbd_accept
, NULL
, NULL
);
375 qio_net_listener_set_client_func(server
, NULL
, NULL
, NULL
);
380 static SocketAddress
*nbd_build_socket_address(const char *sockpath
,
384 SocketAddress
*saddr
;
386 saddr
= g_new0(SocketAddress
, 1);
388 saddr
->type
= SOCKET_ADDRESS_TYPE_UNIX
;
389 saddr
->u
.q_unix
.path
= g_strdup(sockpath
);
391 InetSocketAddress
*inet
;
392 saddr
->type
= SOCKET_ADDRESS_TYPE_INET
;
393 inet
= &saddr
->u
.inet
;
394 inet
->host
= g_strdup(bindto
);
396 inet
->port
= g_strdup(port
);
398 inet
->port
= g_strdup_printf("%d", NBD_DEFAULT_PORT
);
406 static QemuOptsList file_opts
= {
408 .implied_opt_name
= "file",
409 .head
= QTAILQ_HEAD_INITIALIZER(file_opts
.head
),
411 /* no elements => accept any params */
412 { /* end of list */ }
416 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, bool list
,
420 QCryptoTLSCreds
*creds
;
422 obj
= object_resolve_path_component(
423 object_get_objects_root(), id
);
425 error_setg(errp
, "No TLS credentials with id '%s'",
429 creds
= (QCryptoTLSCreds
*)
430 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
432 error_setg(errp
, "Object with id '%s' is not TLS credentials",
437 if (!qcrypto_tls_creds_check_endpoint(creds
,
439 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
440 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER
,
448 static void setup_address_and_port(const char **address
, const char **port
)
450 if (*address
== NULL
) {
451 *address
= "0.0.0.0";
455 *port
= stringify(NBD_DEFAULT_PORT
);
460 * Check socket parameters compatibility when socket activation is used.
462 static const char *socket_activation_validate_opts(const char *device
,
463 const char *sockpath
,
469 if (device
!= NULL
) {
470 return "NBD device can't be set when using socket activation";
473 if (sockpath
!= NULL
) {
474 return "Unix socket can't be set when using socket activation";
477 if (address
!= NULL
) {
478 return "The interface can't be set when using socket activation";
482 return "TCP port number can't be set when using socket activation";
485 if (selinux
!= NULL
) {
486 return "SELinux label can't be set when using socket activation";
490 return "List mode is incompatible with socket activation";
496 static void qemu_nbd_shutdown(void)
498 job_cancel_sync_all();
503 int main(int argc
, char **argv
)
506 BlockDriverState
*bs
;
507 uint64_t dev_offset
= 0;
508 bool readonly
= false;
509 bool disconnect
= false;
510 const char *bindto
= NULL
;
511 const char *port
= NULL
;
512 char *sockpath
= NULL
;
514 QemuOpts
*sn_opts
= NULL
;
515 const char *sn_id_or_name
= NULL
;
516 const char *sopt
= "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
517 struct option lopt
[] = {
518 { "help", no_argument
, NULL
, 'h' },
519 { "version", no_argument
, NULL
, 'V' },
520 { "bind", required_argument
, NULL
, 'b' },
521 { "port", required_argument
, NULL
, 'p' },
522 { "socket", required_argument
, NULL
, 'k' },
523 { "offset", required_argument
, NULL
, 'o' },
524 { "read-only", no_argument
, NULL
, 'r' },
525 { "allocation-depth", no_argument
, NULL
, 'A' },
526 { "bitmap", required_argument
, NULL
, 'B' },
527 { "connect", required_argument
, NULL
, 'c' },
528 { "disconnect", no_argument
, NULL
, 'd' },
529 { "list", no_argument
, NULL
, 'L' },
530 { "snapshot", no_argument
, NULL
, 's' },
531 { "load-snapshot", required_argument
, NULL
, 'l' },
532 { "nocache", no_argument
, NULL
, 'n' },
533 { "cache", required_argument
, NULL
, QEMU_NBD_OPT_CACHE
},
534 { "aio", required_argument
, NULL
, QEMU_NBD_OPT_AIO
},
535 { "discard", required_argument
, NULL
, QEMU_NBD_OPT_DISCARD
},
536 { "detect-zeroes", required_argument
, NULL
,
537 QEMU_NBD_OPT_DETECT_ZEROES
},
538 { "shared", required_argument
, NULL
, 'e' },
539 { "format", required_argument
, NULL
, 'f' },
540 { "persistent", no_argument
, NULL
, 't' },
541 { "verbose", no_argument
, NULL
, 'v' },
542 { "object", required_argument
, NULL
, QEMU_NBD_OPT_OBJECT
},
543 { "export-name", required_argument
, NULL
, 'x' },
544 { "description", required_argument
, NULL
, 'D' },
545 { "tls-creds", required_argument
, NULL
, QEMU_NBD_OPT_TLSCREDS
},
546 { "tls-hostname", required_argument
, NULL
, QEMU_NBD_OPT_TLSHOSTNAME
},
547 { "tls-authz", required_argument
, NULL
, QEMU_NBD_OPT_TLSAUTHZ
},
548 { "image-opts", no_argument
, NULL
, QEMU_NBD_OPT_IMAGE_OPTS
},
549 { "trace", required_argument
, NULL
, 'T' },
550 { "fork", no_argument
, NULL
, QEMU_NBD_OPT_FORK
},
551 { "pid-file", required_argument
, NULL
, QEMU_NBD_OPT_PID_FILE
},
552 { "selinux-label", required_argument
, NULL
,
553 QEMU_NBD_OPT_SELINUX_LABEL
},
558 int flags
= BDRV_O_RDWR
;
560 bool seen_cache
= false;
561 bool seen_discard
= false;
562 bool seen_aio
= false;
563 pthread_t client_thread
;
564 const char *fmt
= NULL
;
565 Error
*local_err
= NULL
;
566 BlockdevDetectZeroesOptions detect_zeroes
= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
;
567 QDict
*options
= NULL
;
568 const char *export_name
= NULL
; /* defaults to "" later for server mode */
569 const char *export_description
= NULL
;
570 BlockDirtyBitmapOrStrList
*bitmaps
= NULL
;
571 bool alloc_depth
= false;
572 const char *tlscredsid
= NULL
;
573 const char *tlshostname
= NULL
;
574 bool imageOpts
= false;
575 bool writethrough
= false; /* Client will flush as needed. */
576 bool fork_process
= false;
579 unsigned socket_activation
;
580 const char *pid_file_name
= NULL
;
581 const char *selinux_label
= NULL
;
582 BlockExportOptions
*export_opts
;
585 os_setup_early_signal_handling();
586 os_setup_signal_handling();
591 module_call_init(MODULE_INIT_TRACE
);
592 qcrypto_init(&error_fatal
);
594 module_call_init(MODULE_INIT_QOM
);
595 qemu_add_opts(&qemu_trace_opts
);
596 qemu_init_exec_dir(argv
[0]);
598 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
601 flags
|= BDRV_O_SNAPSHOT
;
604 optarg
= (char *) "none";
606 case QEMU_NBD_OPT_CACHE
:
608 error_report("-n and --cache can only be specified once");
612 if (bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
) == -1) {
613 error_report("Invalid cache mode `%s'", optarg
);
617 case QEMU_NBD_OPT_AIO
:
619 error_report("--aio can only be specified once");
623 if (bdrv_parse_aio(optarg
, &flags
) < 0) {
624 error_report("Invalid aio mode '%s'", optarg
);
628 case QEMU_NBD_OPT_DISCARD
:
630 error_report("--discard can only be specified once");
634 if (bdrv_parse_discard_flags(optarg
, &flags
) == -1) {
635 error_report("Invalid discard mode `%s'", optarg
);
639 case QEMU_NBD_OPT_DETECT_ZEROES
:
641 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
,
643 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
,
646 error_reportf_err(local_err
,
647 "Failed to parse detect_zeroes mode: ");
650 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
651 !(flags
& BDRV_O_UNMAP
)) {
652 error_report("setting detect-zeroes to unmap is not allowed "
653 "without setting discard operation to unmap");
664 if (qemu_strtou64(optarg
, NULL
, 0, &dev_offset
) < 0) {
665 error_report("Invalid offset '%s'", optarg
);
670 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
671 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
674 error_report("Failed in parsing snapshot param `%s'",
679 sn_id_or_name
= optarg
;
684 flags
&= ~BDRV_O_RDWR
;
691 BlockDirtyBitmapOrStr
*el
= g_new(BlockDirtyBitmapOrStr
, 1);
692 *el
= (BlockDirtyBitmapOrStr
) {
693 .type
= QTYPE_QSTRING
,
694 .u
.local
= g_strdup(optarg
),
696 QAPI_LIST_PREPEND(bitmaps
, el
);
701 if (sockpath
[0] != '/') {
702 error_report("socket path must be absolute");
713 if (qemu_strtoi(optarg
, NULL
, 0, &shared
) < 0 ||
715 error_report("Invalid shared device number '%s'", optarg
);
726 export_name
= optarg
;
727 if (strlen(export_name
) > NBD_MAX_STRING_SIZE
) {
728 error_report("export name '%s' too long", export_name
);
733 export_description
= optarg
;
734 if (strlen(export_description
) > NBD_MAX_STRING_SIZE
) {
735 error_report("export description '%s' too long",
752 error_report("Try `%s --help' for more information.", argv
[0]);
754 case QEMU_NBD_OPT_OBJECT
:
755 user_creatable_process_cmdline(optarg
);
757 case QEMU_NBD_OPT_TLSCREDS
:
760 case QEMU_NBD_OPT_TLSHOSTNAME
:
761 tlshostname
= optarg
;
763 case QEMU_NBD_OPT_IMAGE_OPTS
:
767 trace_opt_parse(optarg
);
769 case QEMU_NBD_OPT_TLSAUTHZ
:
772 case QEMU_NBD_OPT_FORK
:
778 case QEMU_NBD_OPT_PID_FILE
:
779 pid_file_name
= optarg
;
781 case QEMU_NBD_OPT_SELINUX_LABEL
:
782 selinux_label
= optarg
;
788 if (argc
!= optind
) {
789 error_report("List mode is incompatible with a file name");
792 if (export_name
|| export_description
|| dev_offset
||
793 device
|| disconnect
|| fmt
|| sn_id_or_name
|| bitmaps
||
794 alloc_depth
|| seen_aio
|| seen_discard
|| seen_cache
) {
795 error_report("List mode is incompatible with per-device settings");
799 error_report("List mode is incompatible with forking");
802 } else if ((argc
- optind
) != 1) {
803 error_report("Invalid number of arguments");
804 error_printf("Try `%s --help' for more information.\n", argv
[0]);
806 } else if (!export_name
) {
810 if (!trace_init_backends()) {
814 qemu_set_log(LOG_TRACE
, &error_fatal
);
816 socket_activation
= check_socket_activation();
817 if (socket_activation
== 0) {
819 setup_address_and_port(&bindto
, &port
);
822 /* Using socket activation - check user didn't use -p etc. */
823 const char *err_msg
= socket_activation_validate_opts(device
, sockpath
,
827 if (err_msg
!= NULL
) {
828 error_report("%s", err_msg
);
832 /* qemu-nbd can only listen on a single socket. */
833 if (socket_activation
> 1) {
834 error_report("qemu-nbd does not support socket activation with %s > 1",
842 error_report("TLS is not supported with a host device");
845 if (tlsauthz
&& list
) {
846 error_report("TLS authorization is incompatible with export list");
849 if (tlshostname
&& !list
) {
850 error_report("TLS hostname is only supported with export list");
853 tlscreds
= nbd_get_tls_creds(tlscredsid
, list
, &local_err
);
855 error_reportf_err(local_err
, "Failed to get TLS creds: ");
860 error_report("--tls-authz is not permitted without --tls-creds");
864 error_report("--tls-hostname is not permitted without --tls-creds");
870 #ifdef CONFIG_SELINUX
871 if (sockpath
== NULL
&& device
== NULL
) {
872 error_report("--selinux-label is not permitted without --socket");
876 error_report("SELinux support not enabled in this binary");
882 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
883 return qemu_nbd_client_list(saddr
, tlscreds
,
884 tlshostname
? tlshostname
: bindto
);
888 if (disconnect
|| device
) {
889 error_report("Kernel /dev/nbdN support not available");
892 #else /* HAVE_NBD_DEVICE */
894 int nbdfd
= open(argv
[optind
], O_RDWR
);
896 error_report("Cannot open %s: %s", argv
[optind
],
900 nbd_disconnect(nbdfd
);
904 printf("%s disconnected\n", argv
[optind
]);
910 if ((device
&& !verbose
) || fork_process
) {
912 g_autoptr(GError
) err
= NULL
;
917 if (!g_unix_open_pipe(stderr_fd
, FD_CLOEXEC
, &err
)) {
918 error_report("Error setting up communication pipe: %s",
923 /* Now daemonize, but keep a communication channel open to
924 * print errors and exit with the proper status code.
928 error_report("Failed to fork: %s", strerror(errno
));
930 } else if (pid
== 0) {
933 /* Remember parent's stderr if we will be restoring it. */
935 old_stderr
= dup(STDERR_FILENO
);
938 ret
= qemu_daemon(1, 0);
940 /* Temporarily redirect stderr to the parent's pipe... */
941 dup2(stderr_fd
[1], STDERR_FILENO
);
943 error_report("Failed to daemonize: %s", strerror(errno
));
947 /* ... close the descriptor we inherited and go on. */
953 /* In the parent. Print error messages from the child until
954 * it closes the pipe.
957 buf
= g_malloc(1024);
958 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
960 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
966 error_report("Cannot read from daemon: %s",
971 /* Usually the daemon should not print any message.
972 * Exit with zero status in that case.
977 error_report("Unable to fork into background on Windows hosts");
982 if (device
!= NULL
&& sockpath
== NULL
) {
983 sockpath
= g_malloc(128);
984 snprintf(sockpath
, 128, SOCKET_PATH
, basename(device
));
987 server
= qio_net_listener_new();
988 if (socket_activation
== 0) {
991 if (persistent
|| shared
== 0) {
994 backlog
= MIN(shared
, SOMAXCONN
);
996 #ifdef CONFIG_SELINUX
997 if (selinux_label
&& setsockcreatecon_raw(selinux_label
) == -1) {
998 error_report("Cannot set SELinux socket create context to %s: %s",
999 selinux_label
, strerror(errno
));
1003 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
1004 if (qio_net_listener_open_sync(server
, saddr
, backlog
,
1006 object_unref(OBJECT(server
));
1007 error_report_err(local_err
);
1010 #ifdef CONFIG_SELINUX
1011 if (selinux_label
&& setsockcreatecon_raw(NULL
) == -1) {
1012 error_report("Cannot clear SELinux socket create context: %s",
1019 /* See comment in check_socket_activation above. */
1020 for (i
= 0; i
< socket_activation
; i
++) {
1021 QIOChannelSocket
*sioc
;
1022 sioc
= qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD
+ i
,
1025 object_unref(OBJECT(server
));
1026 error_reportf_err(local_err
,
1027 "Failed to use socket activation: ");
1030 qio_net_listener_add(server
, sioc
);
1031 object_unref(OBJECT(sioc
));
1035 qemu_init_main_loop(&error_fatal
);
1037 atexit(qemu_nbd_shutdown
);
1039 srcpath
= argv
[optind
];
1043 error_report("--image-opts and -f are mutually exclusive");
1046 opts
= qemu_opts_parse_noisily(&file_opts
, srcpath
, true);
1048 qemu_opts_reset(&file_opts
);
1051 options
= qemu_opts_to_qdict(opts
, NULL
);
1052 qemu_opts_reset(&file_opts
);
1053 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
1056 options
= qdict_new();
1057 qdict_put_str(options
, "driver", fmt
);
1059 blk
= blk_new_open(srcpath
, NULL
, options
, flags
, &local_err
);
1063 error_reportf_err(local_err
, "Failed to blk_new_open '%s': ",
1070 QDict
*raw_opts
= qdict_new();
1071 qdict_put_str(raw_opts
, "driver", "raw");
1072 qdict_put_str(raw_opts
, "file", bs
->node_name
);
1073 qdict_put_int(raw_opts
, "offset", dev_offset
);
1074 bs
= bdrv_open(NULL
, NULL
, raw_opts
, flags
, &error_fatal
);
1076 blk_insert_bs(blk
, bs
, &error_fatal
);
1080 blk_set_enable_write_cache(blk
, !writethrough
);
1083 ret
= bdrv_snapshot_load_tmp(bs
,
1084 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1085 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1087 } else if (sn_id_or_name
) {
1088 ret
= bdrv_snapshot_load_tmp_by_id_or_name(bs
, sn_id_or_name
,
1092 error_reportf_err(local_err
, "Failed to load snapshot: ");
1096 bs
->detect_zeroes
= detect_zeroes
;
1098 nbd_server_is_qemu_nbd(shared
);
1100 export_opts
= g_new(BlockExportOptions
, 1);
1101 *export_opts
= (BlockExportOptions
) {
1102 .type
= BLOCK_EXPORT_TYPE_NBD
,
1103 .id
= g_strdup("qemu-nbd-export"),
1104 .node_name
= g_strdup(bdrv_get_node_name(bs
)),
1105 .has_writethrough
= true,
1106 .writethrough
= writethrough
,
1107 .has_writable
= true,
1108 .writable
= !readonly
,
1111 .name
= g_strdup(export_name
),
1112 .has_description
= !!export_description
,
1113 .description
= g_strdup(export_description
),
1114 .has_bitmaps
= !!bitmaps
,
1116 .has_allocation_depth
= alloc_depth
,
1117 .allocation_depth
= alloc_depth
,
1120 blk_exp_add(export_opts
, &error_fatal
);
1121 qapi_free_BlockExportOptions(export_opts
);
1127 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, device
);
1129 error_report("Failed to create client thread: %s", strerror(ret
));
1134 /* Shut up GCC warnings. */
1135 memset(&client_thread
, 0, sizeof(client_thread
));
1138 nbd_update_server_watch();
1140 if (pid_file_name
) {
1141 qemu_write_pidfile(pid_file_name
, &error_fatal
);
1144 /* now when the initialization is (almost) complete, chdir("/")
1145 * to free any busy filesystems */
1146 if (chdir("/") < 0) {
1147 error_report("Could not chdir to root directory: %s",
1153 dup2(old_stderr
, STDERR_FILENO
);
1159 main_loop_wait(false);
1160 if (state
== TERMINATE
) {
1161 blk_exp_close_all();
1164 } while (state
!= TERMINATED
);
1171 qemu_opts_del(sn_opts
);
1175 pthread_join(client_thread
, &ret
);