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