qemu/qemu-nbd.c
<<
>>
Prefs
   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_SELINUX
  51#include <selinux/selinux.h>
  52#endif
  53
  54#ifdef __linux__
  55#define HAVE_NBD_DEVICE 1
  56#else
  57#define HAVE_NBD_DEVICE 0
  58#endif
  59
  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
  73
  74#define MBR_SIZE 512
  75
  76static int verbose;
  77static char *srcpath;
  78static SocketAddress *saddr;
  79static int persistent = 0;
  80static enum { RUNNING, TERMINATE, TERMINATED } state;
  81static int shared = 1;
  82static int nb_fds;
  83static QIONetListener *server;
  84static QCryptoTLSCreds *tlscreds;
  85static const char *tlsauthz;
  86
  87static void usage(const char *name)
  88{
  89    (printf) (
  90"Usage: %s [OPTIONS] FILE\n"
  91"  or:  %s -L [OPTIONS]\n"
  92"QEMU Disk Network Block Device Utility\n"
  93"\n"
  94"  -h, --help                display this help and exit\n"
  95"  -V, --version             output version information and exit\n"
  96"\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"
 107"\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"
 112"\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"
 119"                            authorization\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"
 127#endif
 128#if HAVE_NBD_DEVICE
 129"\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"
 133#endif
 134"\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"
 145"                            '[ID_OR_NAME]'\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"
 154"\n"
 155QEMU_HELP_BOTTOM "\n"
 156    , name, name, NBD_DEFAULT_PORT, "DEVICE");
 157}
 158
 159static void version(const char *name)
 160{
 161    printf(
 162"%s " QEMU_FULL_VERSION "\n"
 163"Written by Anthony Liguori.\n"
 164"\n"
 165QEMU_COPYRIGHT "\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"
 168    , name);
 169}
 170
 171#ifdef CONFIG_POSIX
 172/*
 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.
 175 */
 176void qemu_system_killed(int signum, pid_t pid)
 177{
 178    qatomic_cmpxchg(&state, RUNNING, TERMINATE);
 179    qemu_notify_event();
 180}
 181#endif /* CONFIG_POSIX */
 182
 183static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
 184                                const char *hostname)
 185{
 186    int ret = EXIT_FAILURE;
 187    int rc;
 188    Error *err = NULL;
 189    QIOChannelSocket *sioc;
 190    NBDExportInfo *list;
 191    int i, j;
 192
 193    sioc = qio_channel_socket_new();
 194    if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
 195        error_report_err(err);
 196        goto out;
 197    }
 198    rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
 199                                 &err);
 200    if (rc < 0) {
 201        if (err) {
 202            error_report_err(err);
 203        }
 204        goto out;
 205    }
 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);
 211        }
 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",
 225            };
 226
 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]);
 232                }
 233            }
 234            printf(" )\n");
 235        }
 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);
 240        }
 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]);
 245            }
 246        }
 247    }
 248    nbd_free_export_list(list, rc);
 249
 250    ret = EXIT_SUCCESS;
 251 out:
 252    object_unref(OBJECT(sioc));
 253    return ret;
 254}
 255
 256
 257#if HAVE_NBD_DEVICE
 258static void *show_parts(void *arg)
 259{
 260    char *device = arg;
 261    int nbd;
 262
 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
 267     */
 268    nbd = open(device, O_RDWR);
 269    if (nbd >= 0) {
 270        close(nbd);
 271    }
 272    return NULL;
 273}
 274
 275struct NbdClientOpts {
 276    char *device;
 277    bool fork_process;
 278};
 279
 280static void *nbd_client_thread(void *arg)
 281{
 282    struct NbdClientOpts *opts = arg;
 283    NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
 284    QIOChannelSocket *sioc;
 285    int fd = -1;
 286    int ret = EXIT_FAILURE;
 287    pthread_t show_parts_thread;
 288    Error *local_error = NULL;
 289
 290    sioc = qio_channel_socket_new();
 291    if (qio_channel_socket_connect_sync(sioc,
 292                                        saddr,
 293                                        &local_error) < 0) {
 294        error_report_err(local_error);
 295        goto out;
 296    }
 297
 298    if (nbd_receive_negotiate(NULL, QIO_CHANNEL(sioc),
 299                              NULL, NULL, NULL, &info, &local_error) < 0) {
 300        if (local_error) {
 301            error_report_err(local_error);
 302        }
 303        goto out;
 304    }
 305
 306    fd = open(opts->device, O_RDWR);
 307    if (fd < 0) {
 308        /* Linux-only, we can use %m in printf.  */
 309        error_report("Failed to open %s: %m", opts->device);
 310        goto out;
 311    }
 312
 313    if (nbd_init(fd, sioc, &info, &local_error) < 0) {
 314        error_report_err(local_error);
 315        goto out;
 316    }
 317
 318    /* update partition table */
 319    pthread_create(&show_parts_thread, NULL, show_parts, opts->device);
 320
 321    if (verbose && !opts->fork_process) {
 322        fprintf(stderr, "NBD device %s is now connected to %s\n",
 323                opts->device, srcpath);
 324    } else {
 325        /* Close stderr so that the qemu-nbd process exits.  */
 326        dup2(STDOUT_FILENO, STDERR_FILENO);
 327    }
 328
 329    if (nbd_client(fd) < 0) {
 330        goto out;
 331    }
 332
 333    ret = EXIT_SUCCESS;
 334
 335 out:
 336    if (fd >= 0) {
 337        close(fd);
 338    }
 339    object_unref(OBJECT(sioc));
 340    g_free(info.name);
 341    kill(getpid(), SIGTERM);
 342    return (void *) (intptr_t) ret;
 343}
 344#endif /* HAVE_NBD_DEVICE */
 345
 346static int nbd_can_accept(void)
 347{
 348    return state == RUNNING && (shared == 0 || nb_fds < shared);
 349}
 350
 351static void nbd_update_server_watch(void);
 352
 353static void nbd_client_closed(NBDClient *client, bool negotiated)
 354{
 355    nb_fds--;
 356    if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
 357        state = TERMINATE;
 358    }
 359    nbd_update_server_watch();
 360    nbd_client_put(client);
 361}
 362
 363static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
 364                       gpointer opaque)
 365{
 366    if (state >= TERMINATE) {
 367        return;
 368    }
 369
 370    nb_fds++;
 371    nbd_update_server_watch();
 372    nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
 373}
 374
 375static void nbd_update_server_watch(void)
 376{
 377    if (nbd_can_accept()) {
 378        qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
 379    } else {
 380        qio_net_listener_set_client_func(server, NULL, NULL, NULL);
 381    }
 382}
 383
 384
 385static SocketAddress *nbd_build_socket_address(const char *sockpath,
 386                                               const char *bindto,
 387                                               const char *port)
 388{
 389    SocketAddress *saddr;
 390
 391    saddr = g_new0(SocketAddress, 1);
 392    if (sockpath) {
 393        saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
 394        saddr->u.q_unix.path = g_strdup(sockpath);
 395    } else {
 396        InetSocketAddress *inet;
 397        saddr->type = SOCKET_ADDRESS_TYPE_INET;
 398        inet = &saddr->u.inet;
 399        inet->host = g_strdup(bindto);
 400        if (port) {
 401            inet->port = g_strdup(port);
 402        } else  {
 403            inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
 404        }
 405    }
 406
 407    return saddr;
 408}
 409
 410
 411static QemuOptsList file_opts = {
 412    .name = "file",
 413    .implied_opt_name = "file",
 414    .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
 415    .desc = {
 416        /* no elements => accept any params */
 417        { /* end of list */ }
 418    },
 419};
 420
 421static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
 422                                          Error **errp)
 423{
 424    Object *obj;
 425    QCryptoTLSCreds *creds;
 426
 427    obj = object_resolve_path_component(
 428        object_get_objects_root(), id);
 429    if (!obj) {
 430        error_setg(errp, "No TLS credentials with id '%s'",
 431                   id);
 432        return NULL;
 433    }
 434    creds = (QCryptoTLSCreds *)
 435        object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
 436    if (!creds) {
 437        error_setg(errp, "Object with id '%s' is not TLS credentials",
 438                   id);
 439        return NULL;
 440    }
 441
 442    if (!qcrypto_tls_creds_check_endpoint(creds,
 443                                          list
 444                                          ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
 445                                          : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
 446                                          errp)) {
 447        return NULL;
 448    }
 449    object_ref(obj);
 450    return creds;
 451}
 452
 453static void setup_address_and_port(const char **address, const char **port)
 454{
 455    if (*address == NULL) {
 456        *address = "0.0.0.0";
 457    }
 458
 459    if (*port == NULL) {
 460        *port = stringify(NBD_DEFAULT_PORT);
 461    }
 462}
 463
 464/*
 465 * Check socket parameters compatibility when socket activation is used.
 466 */
 467static const char *socket_activation_validate_opts(const char *device,
 468                                                   const char *sockpath,
 469                                                   const char *address,
 470                                                   const char *port,
 471                                                   const char *selinux,
 472                                                   bool list)
 473{
 474    if (device != NULL) {
 475        return "NBD device can't be set when using socket activation";
 476    }
 477
 478    if (sockpath != NULL) {
 479        return "Unix socket can't be set when using socket activation";
 480    }
 481
 482    if (address != NULL) {
 483        return "The interface can't be set when using socket activation";
 484    }
 485
 486    if (port != NULL) {
 487        return "TCP port number can't be set when using socket activation";
 488    }
 489
 490    if (selinux != NULL) {
 491        return "SELinux label can't be set when using socket activation";
 492    }
 493
 494    if (list) {
 495        return "List mode is incompatible with socket activation";
 496    }
 497
 498    return NULL;
 499}
 500
 501static void qemu_nbd_shutdown(void)
 502{
 503    job_cancel_sync_all();
 504    blk_exp_close_all();
 505    bdrv_close_all();
 506}
 507
 508int main(int argc, char **argv)
 509{
 510    BlockBackend *blk;
 511    BlockDriverState *bs;
 512    uint64_t dev_offset = 0;
 513    bool readonly = false;
 514    bool disconnect = false;
 515    const char *bindto = NULL;
 516    const char *port = NULL;
 517    char *sockpath = NULL;
 518    char *device = NULL;
 519    QemuOpts *sn_opts = NULL;
 520    const char *sn_id_or_name = NULL;
 521    const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
 522    struct option lopt[] = {
 523        { "help", no_argument, NULL, 'h' },
 524        { "version", no_argument, NULL, 'V' },
 525        { "bind", required_argument, NULL, 'b' },
 526        { "port", required_argument, NULL, 'p' },
 527        { "socket", required_argument, NULL, 'k' },
 528        { "offset", required_argument, NULL, 'o' },
 529        { "read-only", no_argument, NULL, 'r' },
 530        { "allocation-depth", no_argument, NULL, 'A' },
 531        { "bitmap", required_argument, NULL, 'B' },
 532        { "connect", required_argument, NULL, 'c' },
 533        { "disconnect", no_argument, NULL, 'd' },
 534        { "list", no_argument, NULL, 'L' },
 535        { "snapshot", no_argument, NULL, 's' },
 536        { "load-snapshot", required_argument, NULL, 'l' },
 537        { "nocache", no_argument, NULL, 'n' },
 538        { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
 539        { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
 540        { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
 541        { "detect-zeroes", required_argument, NULL,
 542          QEMU_NBD_OPT_DETECT_ZEROES },
 543        { "shared", required_argument, NULL, 'e' },
 544        { "format", required_argument, NULL, 'f' },
 545        { "persistent", no_argument, NULL, 't' },
 546        { "verbose", no_argument, NULL, 'v' },
 547        { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
 548        { "export-name", required_argument, NULL, 'x' },
 549        { "description", required_argument, NULL, 'D' },
 550        { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
 551        { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
 552        { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
 553        { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
 554        { "trace", required_argument, NULL, 'T' },
 555        { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
 556        { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
 557        { "selinux-label", required_argument, NULL,
 558          QEMU_NBD_OPT_SELINUX_LABEL },
 559        { NULL, 0, NULL, 0 }
 560    };
 561    int ch;
 562    int opt_ind = 0;
 563    int flags = BDRV_O_RDWR;
 564    int ret = 0;
 565    bool seen_cache = false;
 566    bool seen_discard = false;
 567    bool seen_aio = false;
 568    pthread_t client_thread;
 569    const char *fmt = NULL;
 570    Error *local_err = NULL;
 571    BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
 572    QDict *options = NULL;
 573    const char *export_name = NULL; /* defaults to "" later for server mode */
 574    const char *export_description = NULL;
 575    BlockDirtyBitmapOrStrList *bitmaps = NULL;
 576    bool alloc_depth = false;
 577    const char *tlscredsid = NULL;
 578    const char *tlshostname = NULL;
 579    bool imageOpts = false;
 580    bool writethrough = false; /* Client will flush as needed. */
 581    bool fork_process = false;
 582    bool list = false;
 583    unsigned socket_activation;
 584    const char *pid_file_name = NULL;
 585    const char *selinux_label = NULL;
 586    BlockExportOptions *export_opts;
 587#if HAVE_NBD_DEVICE
 588    struct NbdClientOpts opts;
 589#endif
 590
 591#ifdef CONFIG_POSIX
 592    os_setup_early_signal_handling();
 593    os_setup_signal_handling();
 594#endif
 595
 596    socket_init();
 597    error_init(argv[0]);
 598    module_call_init(MODULE_INIT_TRACE);
 599    qcrypto_init(&error_fatal);
 600
 601    module_call_init(MODULE_INIT_QOM);
 602    qemu_add_opts(&qemu_trace_opts);
 603    qemu_init_exec_dir(argv[0]);
 604
 605    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
 606        switch (ch) {
 607        case 's':
 608            flags |= BDRV_O_SNAPSHOT;
 609            break;
 610        case 'n':
 611            optarg = (char *) "none";
 612            /* fallthrough */
 613        case QEMU_NBD_OPT_CACHE:
 614            if (seen_cache) {
 615                error_report("-n and --cache can only be specified once");
 616                exit(EXIT_FAILURE);
 617            }
 618            seen_cache = true;
 619            if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
 620                error_report("Invalid cache mode `%s'", optarg);
 621                exit(EXIT_FAILURE);
 622            }
 623            break;
 624        case QEMU_NBD_OPT_AIO:
 625            if (seen_aio) {
 626                error_report("--aio can only be specified once");
 627                exit(EXIT_FAILURE);
 628            }
 629            seen_aio = true;
 630            if (bdrv_parse_aio(optarg, &flags) < 0) {
 631                error_report("Invalid aio mode '%s'", optarg);
 632                exit(EXIT_FAILURE);
 633            }
 634            break;
 635        case QEMU_NBD_OPT_DISCARD:
 636            if (seen_discard) {
 637                error_report("--discard can only be specified once");
 638                exit(EXIT_FAILURE);
 639            }
 640            seen_discard = true;
 641            if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
 642                error_report("Invalid discard mode `%s'", optarg);
 643                exit(EXIT_FAILURE);
 644            }
 645            break;
 646        case QEMU_NBD_OPT_DETECT_ZEROES:
 647            detect_zeroes =
 648                qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
 649                                optarg,
 650                                BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
 651                                &local_err);
 652            if (local_err) {
 653                error_reportf_err(local_err,
 654                                  "Failed to parse detect_zeroes mode: ");
 655                exit(EXIT_FAILURE);
 656            }
 657            if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
 658                !(flags & BDRV_O_UNMAP)) {
 659                error_report("setting detect-zeroes to unmap is not allowed "
 660                             "without setting discard operation to unmap");
 661                exit(EXIT_FAILURE);
 662            }
 663            break;
 664        case 'b':
 665            bindto = optarg;
 666            break;
 667        case 'p':
 668            port = optarg;
 669            break;
 670        case 'o':
 671            if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
 672                error_report("Invalid offset '%s'", optarg);
 673                exit(EXIT_FAILURE);
 674            }
 675            break;
 676        case 'l':
 677            if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
 678                sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
 679                                                  optarg, false);
 680                if (!sn_opts) {
 681                    error_report("Failed in parsing snapshot param `%s'",
 682                                 optarg);
 683                    exit(EXIT_FAILURE);
 684                }
 685            } else {
 686                sn_id_or_name = optarg;
 687            }
 688            /* fall through */
 689        case 'r':
 690            readonly = true;
 691            flags &= ~BDRV_O_RDWR;
 692            break;
 693        case 'A':
 694            alloc_depth = true;
 695            break;
 696        case 'B':
 697            {
 698                BlockDirtyBitmapOrStr *el = g_new(BlockDirtyBitmapOrStr, 1);
 699                *el = (BlockDirtyBitmapOrStr) {
 700                    .type = QTYPE_QSTRING,
 701                    .u.local = g_strdup(optarg),
 702                };
 703                QAPI_LIST_PREPEND(bitmaps, el);
 704            }
 705            break;
 706        case 'k':
 707            sockpath = optarg;
 708            if (sockpath[0] != '/') {
 709                error_report("socket path must be absolute");
 710                exit(EXIT_FAILURE);
 711            }
 712            break;
 713        case 'd':
 714            disconnect = true;
 715            break;
 716        case 'c':
 717            device = optarg;
 718            break;
 719        case 'e':
 720            if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
 721                shared < 0) {
 722                error_report("Invalid shared device number '%s'", optarg);
 723                exit(EXIT_FAILURE);
 724            }
 725            break;
 726        case 'f':
 727            fmt = optarg;
 728            break;
 729        case 't':
 730            persistent = 1;
 731            break;
 732        case 'x':
 733            export_name = optarg;
 734            if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
 735                error_report("export name '%s' too long", export_name);
 736                exit(EXIT_FAILURE);
 737            }
 738            break;
 739        case 'D':
 740            export_description = optarg;
 741            if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
 742                error_report("export description '%s' too long",
 743                             export_description);
 744                exit(EXIT_FAILURE);
 745            }
 746            break;
 747        case 'v':
 748            verbose = 1;
 749            break;
 750        case 'V':
 751            version(argv[0]);
 752            exit(0);
 753            break;
 754        case 'h':
 755            usage(argv[0]);
 756            exit(0);
 757            break;
 758        case '?':
 759            error_report("Try `%s --help' for more information.", argv[0]);
 760            exit(EXIT_FAILURE);
 761        case QEMU_NBD_OPT_OBJECT:
 762            user_creatable_process_cmdline(optarg);
 763            break;
 764        case QEMU_NBD_OPT_TLSCREDS:
 765            tlscredsid = optarg;
 766            break;
 767        case QEMU_NBD_OPT_TLSHOSTNAME:
 768            tlshostname = optarg;
 769            break;
 770        case QEMU_NBD_OPT_IMAGE_OPTS:
 771            imageOpts = true;
 772            break;
 773        case 'T':
 774            trace_opt_parse(optarg);
 775            break;
 776        case QEMU_NBD_OPT_TLSAUTHZ:
 777            tlsauthz = optarg;
 778            break;
 779        case QEMU_NBD_OPT_FORK:
 780            fork_process = true;
 781            break;
 782        case 'L':
 783            list = true;
 784            break;
 785        case QEMU_NBD_OPT_PID_FILE:
 786            pid_file_name = optarg;
 787            break;
 788        case QEMU_NBD_OPT_SELINUX_LABEL:
 789            selinux_label = optarg;
 790            break;
 791        }
 792    }
 793
 794    if (list) {
 795        if (argc != optind) {
 796            error_report("List mode is incompatible with a file name");
 797            exit(EXIT_FAILURE);
 798        }
 799        if (export_name || export_description || dev_offset ||
 800            device || disconnect || fmt || sn_id_or_name || bitmaps ||
 801            alloc_depth || seen_aio || seen_discard || seen_cache) {
 802            error_report("List mode is incompatible with per-device settings");
 803            exit(EXIT_FAILURE);
 804        }
 805        if (fork_process) {
 806            error_report("List mode is incompatible with forking");
 807            exit(EXIT_FAILURE);
 808        }
 809    } else if ((argc - optind) != 1) {
 810        error_report("Invalid number of arguments");
 811        error_printf("Try `%s --help' for more information.\n", argv[0]);
 812        exit(EXIT_FAILURE);
 813    } else if (!export_name) {
 814        export_name = "";
 815    }
 816
 817    if (!trace_init_backends()) {
 818        exit(1);
 819    }
 820    trace_init_file();
 821    qemu_set_log(LOG_TRACE, &error_fatal);
 822
 823    socket_activation = check_socket_activation();
 824    if (socket_activation == 0) {
 825        if (!sockpath) {
 826            setup_address_and_port(&bindto, &port);
 827        }
 828    } else {
 829        /* Using socket activation - check user didn't use -p etc. */
 830        const char *err_msg = socket_activation_validate_opts(device, sockpath,
 831                                                              bindto, port,
 832                                                              selinux_label,
 833                                                              list);
 834        if (err_msg != NULL) {
 835            error_report("%s", err_msg);
 836            exit(EXIT_FAILURE);
 837        }
 838
 839        /* qemu-nbd can only listen on a single socket.  */
 840        if (socket_activation > 1) {
 841            error_report("qemu-nbd does not support socket activation with %s > 1",
 842                         "LISTEN_FDS");
 843            exit(EXIT_FAILURE);
 844        }
 845    }
 846
 847    if (tlscredsid) {
 848        if (device) {
 849            error_report("TLS is not supported with a host device");
 850            exit(EXIT_FAILURE);
 851        }
 852        if (tlsauthz && list) {
 853            error_report("TLS authorization is incompatible with export list");
 854            exit(EXIT_FAILURE);
 855        }
 856        if (tlshostname && !list) {
 857            error_report("TLS hostname is only supported with export list");
 858            exit(EXIT_FAILURE);
 859        }
 860        tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
 861        if (local_err) {
 862            error_reportf_err(local_err, "Failed to get TLS creds: ");
 863            exit(EXIT_FAILURE);
 864        }
 865    } else {
 866        if (tlsauthz) {
 867            error_report("--tls-authz is not permitted without --tls-creds");
 868            exit(EXIT_FAILURE);
 869        }
 870        if (tlshostname) {
 871            error_report("--tls-hostname is not permitted without --tls-creds");
 872            exit(EXIT_FAILURE);
 873        }
 874    }
 875
 876    if (selinux_label) {
 877#ifdef CONFIG_SELINUX
 878        if (sockpath == NULL && device == NULL) {
 879            error_report("--selinux-label is not permitted without --socket");
 880            exit(EXIT_FAILURE);
 881        }
 882#else
 883        error_report("SELinux support not enabled in this binary");
 884        exit(EXIT_FAILURE);
 885#endif
 886    }
 887
 888    if (list) {
 889        saddr = nbd_build_socket_address(sockpath, bindto, port);
 890        return qemu_nbd_client_list(saddr, tlscreds,
 891                                    tlshostname ? tlshostname : bindto);
 892    }
 893
 894#if !HAVE_NBD_DEVICE
 895    if (disconnect || device) {
 896        error_report("Kernel /dev/nbdN support not available");
 897        exit(EXIT_FAILURE);
 898    }
 899#else /* HAVE_NBD_DEVICE */
 900    if (disconnect) {
 901        int nbdfd = open(argv[optind], O_RDWR);
 902        if (nbdfd < 0) {
 903            error_report("Cannot open %s: %s", argv[optind],
 904                         strerror(errno));
 905            exit(EXIT_FAILURE);
 906        }
 907        nbd_disconnect(nbdfd);
 908
 909        close(nbdfd);
 910
 911        printf("%s disconnected\n", argv[optind]);
 912
 913        return 0;
 914    }
 915#endif
 916
 917    if ((device && !verbose) || fork_process) {
 918#ifndef WIN32
 919        g_autoptr(GError) err = NULL;
 920        int stderr_fd[2];
 921        pid_t pid;
 922        int ret;
 923
 924        if (!g_unix_open_pipe(stderr_fd, FD_CLOEXEC, &err)) {
 925            error_report("Error setting up communication pipe: %s",
 926                         err->message);
 927            exit(EXIT_FAILURE);
 928        }
 929
 930        /* Now daemonize, but keep a communication channel open to
 931         * print errors and exit with the proper status code.
 932         */
 933        pid = fork();
 934        if (pid < 0) {
 935            error_report("Failed to fork: %s", strerror(errno));
 936            exit(EXIT_FAILURE);
 937        } else if (pid == 0) {
 938            close(stderr_fd[0]);
 939
 940            ret = qemu_daemon(1, 0);
 941
 942            /* Temporarily redirect stderr to the parent's pipe...  */
 943            dup2(stderr_fd[1], STDERR_FILENO);
 944            if (ret < 0) {
 945                error_report("Failed to daemonize: %s", strerror(errno));
 946                exit(EXIT_FAILURE);
 947            }
 948
 949            /* ... close the descriptor we inherited and go on.  */
 950            close(stderr_fd[1]);
 951        } else {
 952            bool errors = false;
 953            char *buf;
 954
 955            /* In the parent.  Print error messages from the child until
 956             * it closes the pipe.
 957             */
 958            close(stderr_fd[1]);
 959            buf = g_malloc(1024);
 960            while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
 961                errors = true;
 962                ret = qemu_write_full(STDERR_FILENO, buf, ret);
 963                if (ret < 0) {
 964                    exit(EXIT_FAILURE);
 965                }
 966            }
 967            if (ret < 0) {
 968                error_report("Cannot read from daemon: %s",
 969                             strerror(errno));
 970                exit(EXIT_FAILURE);
 971            }
 972
 973            /* Usually the daemon should not print any message.
 974             * Exit with zero status in that case.
 975             */
 976            exit(errors);
 977        }
 978#else /* WIN32 */
 979        error_report("Unable to fork into background on Windows hosts");
 980        exit(EXIT_FAILURE);
 981#endif /* WIN32 */
 982    }
 983
 984    if (device != NULL && sockpath == NULL) {
 985        sockpath = g_malloc(128);
 986        snprintf(sockpath, 128, SOCKET_PATH, basename(device));
 987    }
 988
 989    server = qio_net_listener_new();
 990    if (socket_activation == 0) {
 991        int backlog;
 992
 993        if (persistent || shared == 0) {
 994            backlog = SOMAXCONN;
 995        } else {
 996            backlog = MIN(shared, SOMAXCONN);
 997        }
 998#ifdef CONFIG_SELINUX
 999        if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
1000            error_report("Cannot set SELinux socket create context to %s: %s",
1001                         selinux_label, strerror(errno));
1002            exit(EXIT_FAILURE);
1003        }
1004#endif
1005        saddr = nbd_build_socket_address(sockpath, bindto, port);
1006        if (qio_net_listener_open_sync(server, saddr, backlog,
1007                                       &local_err) < 0) {
1008            object_unref(OBJECT(server));
1009            error_report_err(local_err);
1010            exit(EXIT_FAILURE);
1011        }
1012#ifdef CONFIG_SELINUX
1013        if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
1014            error_report("Cannot clear SELinux socket create context: %s",
1015                         strerror(errno));
1016            exit(EXIT_FAILURE);
1017        }
1018#endif
1019    } else {
1020        size_t i;
1021        /* See comment in check_socket_activation above. */
1022        for (i = 0; i < socket_activation; i++) {
1023            QIOChannelSocket *sioc;
1024            sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
1025                                             &local_err);
1026            if (sioc == NULL) {
1027                object_unref(OBJECT(server));
1028                error_reportf_err(local_err,
1029                                  "Failed to use socket activation: ");
1030                exit(EXIT_FAILURE);
1031            }
1032            qio_net_listener_add(server, sioc);
1033            object_unref(OBJECT(sioc));
1034        }
1035    }
1036
1037    qemu_init_main_loop(&error_fatal);
1038    bdrv_init();
1039    atexit(qemu_nbd_shutdown);
1040
1041    srcpath = argv[optind];
1042    if (imageOpts) {
1043        QemuOpts *opts;
1044        if (fmt) {
1045            error_report("--image-opts and -f are mutually exclusive");
1046            exit(EXIT_FAILURE);
1047        }
1048        opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
1049        if (!opts) {
1050            qemu_opts_reset(&file_opts);
1051            exit(EXIT_FAILURE);
1052        }
1053        options = qemu_opts_to_qdict(opts, NULL);
1054        qemu_opts_reset(&file_opts);
1055        blk = blk_new_open(NULL, NULL, options, flags, &local_err);
1056    } else {
1057        if (fmt) {
1058            options = qdict_new();
1059            qdict_put_str(options, "driver", fmt);
1060        }
1061        blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
1062    }
1063
1064    if (!blk) {
1065        error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1066                          argv[optind]);
1067        exit(EXIT_FAILURE);
1068    }
1069    bs = blk_bs(blk);
1070
1071    if (dev_offset) {
1072        QDict *raw_opts = qdict_new();
1073        qdict_put_str(raw_opts, "driver", "raw");
1074        qdict_put_str(raw_opts, "file", bs->node_name);
1075        qdict_put_int(raw_opts, "offset", dev_offset);
1076        bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
1077        blk_remove_bs(blk);
1078        blk_insert_bs(blk, bs, &error_fatal);
1079        bdrv_unref(bs);
1080    }
1081
1082    blk_set_enable_write_cache(blk, !writethrough);
1083
1084    if (sn_opts) {
1085        ret = bdrv_snapshot_load_tmp(bs,
1086                                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1087                                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1088                                     &local_err);
1089    } else if (sn_id_or_name) {
1090        ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1091                                                   &local_err);
1092    }
1093    if (ret < 0) {
1094        error_reportf_err(local_err, "Failed to load snapshot: ");
1095        exit(EXIT_FAILURE);
1096    }
1097
1098    bs->detect_zeroes = detect_zeroes;
1099
1100    nbd_server_is_qemu_nbd(shared);
1101
1102    export_opts = g_new(BlockExportOptions, 1);
1103    *export_opts = (BlockExportOptions) {
1104        .type               = BLOCK_EXPORT_TYPE_NBD,
1105        .id                 = g_strdup("qemu-nbd-export"),
1106        .node_name          = g_strdup(bdrv_get_node_name(bs)),
1107        .has_writethrough   = true,
1108        .writethrough       = writethrough,
1109        .has_writable       = true,
1110        .writable           = !readonly,
1111        .u.nbd = {
1112            .has_name             = true,
1113            .name                 = g_strdup(export_name),
1114            .has_description      = !!export_description,
1115            .description          = g_strdup(export_description),
1116            .has_bitmaps          = !!bitmaps,
1117            .bitmaps              = bitmaps,
1118            .has_allocation_depth = alloc_depth,
1119            .allocation_depth     = alloc_depth,
1120        },
1121    };
1122    blk_exp_add(export_opts, &error_fatal);
1123    qapi_free_BlockExportOptions(export_opts);
1124
1125    if (device) {
1126#if HAVE_NBD_DEVICE
1127        int ret;
1128        opts = (struct NbdClientOpts) {
1129            .device = device,
1130            .fork_process = fork_process,
1131        };
1132
1133        ret = pthread_create(&client_thread, NULL, nbd_client_thread, &opts);
1134        if (ret != 0) {
1135            error_report("Failed to create client thread: %s", strerror(ret));
1136            exit(EXIT_FAILURE);
1137        }
1138#endif
1139    } else {
1140        /* Shut up GCC warnings.  */
1141        memset(&client_thread, 0, sizeof(client_thread));
1142    }
1143
1144    nbd_update_server_watch();
1145
1146    if (pid_file_name) {
1147        qemu_write_pidfile(pid_file_name, &error_fatal);
1148    }
1149
1150    /* now when the initialization is (almost) complete, chdir("/")
1151     * to free any busy filesystems */
1152    if (chdir("/") < 0) {
1153        error_report("Could not chdir to root directory: %s",
1154                     strerror(errno));
1155        exit(EXIT_FAILURE);
1156    }
1157
1158    if (fork_process) {
1159        dup2(STDOUT_FILENO, STDERR_FILENO);
1160    }
1161
1162    state = RUNNING;
1163    do {
1164        main_loop_wait(false);
1165        if (state == TERMINATE) {
1166            blk_exp_close_all();
1167            state = TERMINATED;
1168        }
1169    } while (state != TERMINATED);
1170
1171    blk_unref(blk);
1172    if (sockpath) {
1173        unlink(sockpath);
1174    }
1175
1176    qemu_opts_del(sn_opts);
1177
1178    if (device) {
1179        void *ret;
1180        pthread_join(client_thread, &ret);
1181        exit(ret != NULL);
1182    } else {
1183        exit(EXIT_SUCCESS);
1184    }
1185}
1186