nbd.c 15.7 KB
Newer Older
1 2 3 4
/*
 * QEMU Block driver for  NBD
 *
 * Copyright (C) 2008 Bull S.A.S.
M
malc 已提交
5
 *     Author: Laurent Vivier <Laurent.Vivier@bull.net>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *
 * Some parts:
 *    Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

P
Peter Maydell 已提交
29
#include "qemu/osdep.h"
M
Marc-André Lureau 已提交
30
#include "block/nbd-client.h"
31
#include "qapi/error.h"
32
#include "qemu/uri.h"
33
#include "block/block_int.h"
34
#include "qemu/module.h"
35
#include "qapi/qmp/qdict.h"
36 37
#include "qapi/qmp/qjson.h"
#include "qapi/qmp/qint.h"
38
#include "qapi/qmp/qstring.h"
39
#include "qemu/cutils.h"
40

41 42
#define EN_OPTSTR ":exportname="

43
typedef struct BDRVNBDState {
M
Marc-André Lureau 已提交
44
    NbdClientSession client;
45 46
} BDRVNBDState;

47
static int nbd_parse_uri(const char *filename, QDict *options)
P
Paolo Bonzini 已提交
48 49 50 51 52
{
    URI *uri;
    const char *p;
    QueryParams *qp = NULL;
    int ret = 0;
53
    bool is_unix;
P
Paolo Bonzini 已提交
54 55 56 57 58 59 60 61

    uri = uri_parse(filename);
    if (!uri) {
        return -EINVAL;
    }

    /* transport */
    if (!strcmp(uri->scheme, "nbd")) {
62
        is_unix = false;
P
Paolo Bonzini 已提交
63
    } else if (!strcmp(uri->scheme, "nbd+tcp")) {
64
        is_unix = false;
P
Paolo Bonzini 已提交
65
    } else if (!strcmp(uri->scheme, "nbd+unix")) {
66
        is_unix = true;
P
Paolo Bonzini 已提交
67 68 69 70 71 72 73 74
    } else {
        ret = -EINVAL;
        goto out;
    }

    p = uri->path ? uri->path : "/";
    p += strspn(p, "/");
    if (p[0]) {
75
        qdict_put(options, "export", qstring_from_str(p));
P
Paolo Bonzini 已提交
76 77 78
    }

    qp = query_params_parse(uri->query);
79
    if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
P
Paolo Bonzini 已提交
80 81 82 83
        ret = -EINVAL;
        goto out;
    }

84
    if (is_unix) {
P
Paolo Bonzini 已提交
85 86 87 88 89
        /* nbd+unix:///export?socket=path */
        if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
            ret = -EINVAL;
            goto out;
        }
90
        qdict_put(options, "path", qstring_from_str(qp->p[0].value));
P
Paolo Bonzini 已提交
91
    } else {
92
        QString *host;
93
        /* nbd[+tcp]://host[:port]/export */
P
Paolo Bonzini 已提交
94 95 96 97
        if (!uri->server) {
            ret = -EINVAL;
            goto out;
        }
98

99 100 101 102 103 104 105 106 107
        /* strip braces from literal IPv6 address */
        if (uri->server[0] == '[') {
            host = qstring_from_substr(uri->server, 1,
                                       strlen(uri->server) - 2);
        } else {
            host = qstring_from_str(uri->server);
        }

        qdict_put(options, "host", host);
108 109 110 111 112
        if (uri->port) {
            char* port_str = g_strdup_printf("%d", uri->port);
            qdict_put(options, "port", qstring_from_str(port_str));
            g_free(port_str);
        }
P
Paolo Bonzini 已提交
113 114 115 116 117 118 119 120 121 122
    }

out:
    if (qp) {
        query_params_free(qp);
    }
    uri_free(uri);
    return ret;
}

123 124
static void nbd_parse_filename(const char *filename, QDict *options,
                               Error **errp)
125
{
126
    char *file;
127 128
    char *export_name;
    const char *host_spec;
129 130
    const char *unixpath;

131 132 133 134 135 136 137 138 139
    if (qdict_haskey(options, "host")
        || qdict_haskey(options, "port")
        || qdict_haskey(options, "path"))
    {
        error_setg(errp, "host/port/path and a file name may not be specified "
                         "at the same time");
        return;
    }

P
Paolo Bonzini 已提交
140
    if (strstr(filename, "://")) {
141 142 143 144 145
        int ret = nbd_parse_uri(filename, options);
        if (ret < 0) {
            error_setg(errp, "No valid URL specified");
        }
        return;
P
Paolo Bonzini 已提交
146 147
    }

148
    file = g_strdup(filename);
149

150 151 152
    export_name = strstr(file, EN_OPTSTR);
    if (export_name) {
        if (export_name[strlen(EN_OPTSTR)] == 0) {
153 154
            goto out;
        }
155 156
        export_name[0] = 0; /* truncate 'file' */
        export_name += strlen(EN_OPTSTR);
157 158

        qdict_put(options, "export", qstring_from_str(export_name));
159 160
    }

161 162
    /* extract the host_spec - fail if it's not nbd:... */
    if (!strstart(file, "nbd:", &host_spec)) {
163
        error_setg(errp, "File name string for NBD must start with 'nbd:'");
164 165
        goto out;
    }
166

167 168 169 170
    if (!*host_spec) {
        goto out;
    }

171 172
    /* are we a UNIX or TCP socket? */
    if (strstart(host_spec, "unix:", &unixpath)) {
173
        qdict_put(options, "path", qstring_from_str(unixpath));
174
    } else {
175 176
        InetSocketAddress *addr = NULL;

177
        addr = inet_parse(host_spec, errp);
178
        if (!addr) {
179 180
            goto out;
        }
181

182 183 184 185
        qdict_put(options, "host", qstring_from_str(addr->host));
        qdict_put(options, "port", qstring_from_str(addr->port));
        qapi_free_InetSocketAddress(addr);
    }
186

187
out:
188
    g_free(file);
189 190
}

191
static SocketAddress *nbd_config(BDRVNBDState *s, QemuOpts *opts, char **export,
192
                                 Error **errp)
193
{
194
    SocketAddress *saddr;
195

196 197
    if (!qemu_opt_get(opts, "path") == !qemu_opt_get(opts, "host")) {
        if (qemu_opt_get(opts, "path")) {
P
Paolo Bonzini 已提交
198
            error_setg(errp, "path and host may not be used at the same time.");
199
        } else {
P
Paolo Bonzini 已提交
200
            error_setg(errp, "one of path and host must be specified.");
201
        }
202
        return NULL;
203
    }
204

205
    saddr = g_new0(SocketAddress, 1);
206

207
    if (qemu_opt_get(opts, "path")) {
208
        UnixSocketAddress *q_unix;
209
        saddr->type = SOCKET_ADDRESS_KIND_UNIX;
210
        q_unix = saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
211
        q_unix->path = g_strdup(qemu_opt_get(opts, "path"));
212
    } else {
213
        InetSocketAddress *inet;
214
        saddr->type = SOCKET_ADDRESS_KIND_INET;
215
        inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
216 217 218
        inet->host = g_strdup(qemu_opt_get(opts, "host"));
        inet->port = g_strdup(qemu_opt_get(opts, "port"));
        if (!inet->port) {
219
            inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
220
        }
221 222
    }

223
    s->client.is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
224

225
    *export = g_strdup(qemu_opt_get(opts, "export"));
226 227

    return saddr;
228
}
229

M
Max Reitz 已提交
230 231 232 233 234 235
NbdClientSession *nbd_get_client_session(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;
    return &s->client;
}

236 237
static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
                                                  Error **errp)
238
{
239 240
    QIOChannelSocket *sioc;
    Error *local_err = NULL;
241

242
    sioc = qio_channel_socket_new();
243

244 245 246 247 248 249
    qio_channel_socket_connect_sync(sioc,
                                    saddr,
                                    &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return NULL;
250
    }
251

252
    qio_channel_set_delay(QIO_CHANNEL(sioc), false);
253

254
    return sioc;
255 256
}

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
{
    Object *obj;
    QCryptoTLSCreds *creds;

    obj = object_resolve_path_component(
        object_get_objects_root(), id);
    if (!obj) {
        error_setg(errp, "No TLS credentials with id '%s'",
                   id);
        return NULL;
    }
    creds = (QCryptoTLSCreds *)
        object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
    if (!creds) {
        error_setg(errp, "Object with id '%s' is not TLS credentials",
                   id);
        return NULL;
    }

    if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
        error_setg(errp,
                   "Expecting TLS credentials with a client endpoint");
        return NULL;
    }
    object_ref(obj);
    return creds;
}


288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
static QemuOptsList nbd_runtime_opts = {
    .name = "nbd",
    .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
    .desc = {
        {
            .name = "host",
            .type = QEMU_OPT_STRING,
            .help = "TCP host to connect to",
        },
        {
            .name = "port",
            .type = QEMU_OPT_STRING,
            .help = "TCP port to connect to",
        },
        {
            .name = "path",
            .type = QEMU_OPT_STRING,
            .help = "Unix socket path to connect to",
        },
        {
            .name = "export",
            .type = QEMU_OPT_STRING,
            .help = "Name of the NBD export to open",
        },
        {
            .name = "tls-creds",
            .type = QEMU_OPT_STRING,
            .help = "ID of the TLS credentials to use",
        },
    },
};

M
Max Reitz 已提交
320 321
static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
                    Error **errp)
322 323
{
    BDRVNBDState *s = bs->opaque;
324 325
    QemuOpts *opts = NULL;
    Error *local_err = NULL;
326
    char *export = NULL;
327
    QIOChannelSocket *sioc = NULL;
328
    SocketAddress *saddr = NULL;
329 330 331 332
    const char *tlscredsid;
    QCryptoTLSCreds *tlscreds = NULL;
    const char *hostname = NULL;
    int ret = -EINVAL;
333

334 335 336 337 338 339 340
    opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        goto error;
    }

341
    /* Pop the config into our state object. Exit if invalid. */
342
    saddr = nbd_config(s, opts, &export, errp);
343
    if (!saddr) {
344 345 346
        goto error;
    }

347
    tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
348 349 350 351 352 353 354 355 356 357
    if (tlscredsid) {
        tlscreds = nbd_get_tls_creds(tlscredsid, errp);
        if (!tlscreds) {
            goto error;
        }

        if (saddr->type != SOCKET_ADDRESS_KIND_INET) {
            error_setg(errp, "TLS only supported over IP sockets");
            goto error;
        }
358
        hostname = saddr->u.inet.data->host;
359 360 361 362 363
    }

    /* establish TCP connection, return error if it fails
     * TODO: Configurable retry-until-timeout behaviour.
     */
364 365
    sioc = nbd_establish_connection(saddr, errp);
    if (!sioc) {
366 367
        ret = -ECONNREFUSED;
        goto error;
368 369
    }

M
Marc-André Lureau 已提交
370
    /* NBD handshake */
371 372 373 374 375 376 377 378 379 380
    ret = nbd_client_init(bs, sioc, export,
                          tlscreds, hostname, errp);
 error:
    if (sioc) {
        object_unref(OBJECT(sioc));
    }
    if (tlscreds) {
        object_unref(OBJECT(tlscreds));
    }
    qapi_free_SocketAddress(saddr);
381
    g_free(export);
382
    qemu_opts_del(opts);
383
    return ret;
384 385
}

P
Paolo Bonzini 已提交
386 387
static int nbd_co_flush(BlockDriverState *bs)
{
M
Max Reitz 已提交
388
    return nbd_client_co_flush(bs);
P
Paolo Bonzini 已提交
389 390
}

391 392
static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
{
393
    bs->bl.max_pdiscard = NBD_MAX_BUFFER_SIZE;
394
    bs->bl.max_transfer = NBD_MAX_BUFFER_SIZE;
395 396
}

397 398
static void nbd_close(BlockDriverState *bs)
{
M
Max Reitz 已提交
399
    nbd_client_close(bs);
400 401 402 403 404 405
}

static int64_t nbd_getlength(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;

M
Marc-André Lureau 已提交
406
    return s->client.size;
407 408
}

409 410
static void nbd_detach_aio_context(BlockDriverState *bs)
{
M
Max Reitz 已提交
411
    nbd_client_detach_aio_context(bs);
412 413 414 415 416
}

static void nbd_attach_aio_context(BlockDriverState *bs,
                                   AioContext *new_context)
{
M
Max Reitz 已提交
417
    nbd_client_attach_aio_context(bs, new_context);
418 419
}

420
static void nbd_refresh_filename(BlockDriverState *bs, QDict *options)
421 422
{
    QDict *opts = qdict_new();
423 424 425 426
    const char *path   = qdict_get_try_str(options, "path");
    const char *host   = qdict_get_try_str(options, "host");
    const char *port   = qdict_get_try_str(options, "port");
    const char *export = qdict_get_try_str(options, "export");
427
    const char *tlscreds = qdict_get_try_str(options, "tls-creds");
428 429 430

    qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("nbd")));

M
Max Reitz 已提交
431
    if (path && export) {
432
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
433 434
                 "nbd+unix:///%s?socket=%s", export, path);
    } else if (path && !export) {
435
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
436 437 438 439 440 441 442 443 444 445 446
                 "nbd+unix://?socket=%s", path);
    } else if (!path && export && port) {
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                 "nbd://%s:%s/%s", host, port, export);
    } else if (!path && export && !port) {
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                 "nbd://%s/%s", host, export);
    } else if (!path && !export && port) {
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                 "nbd://%s:%s", host, port);
    } else if (!path && !export && !port) {
447
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
448 449 450 451 452 453
                 "nbd://%s", host);
    }

    if (path) {
        qdict_put_obj(opts, "path", QOBJECT(qstring_from_str(path)));
    } else if (port) {
454 455
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
        qdict_put_obj(opts, "port", QOBJECT(qstring_from_str(port)));
M
Max Reitz 已提交
456 457 458 459 460
    } else {
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
    }
    if (export) {
        qdict_put_obj(opts, "export", QOBJECT(qstring_from_str(export)));
461
    }
462 463 464
    if (tlscreds) {
        qdict_put_obj(opts, "tls-creds", QOBJECT(qstring_from_str(tlscreds)));
    }
465 466 467 468

    bs->full_open_options = opts;
}

469
static BlockDriver bdrv_nbd = {
470 471 472 473 474
    .format_name                = "nbd",
    .protocol_name              = "nbd",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
475 476
    .bdrv_co_preadv             = nbd_client_co_preadv,
    .bdrv_co_pwritev            = nbd_client_co_pwritev,
477 478
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
479
    .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
480
    .bdrv_refresh_limits        = nbd_refresh_limits,
481 482 483
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
484
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
485 486 487
};

static BlockDriver bdrv_nbd_tcp = {
488 489 490 491 492
    .format_name                = "nbd",
    .protocol_name              = "nbd+tcp",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
493 494
    .bdrv_co_preadv             = nbd_client_co_preadv,
    .bdrv_co_pwritev            = nbd_client_co_pwritev,
495 496
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
497
    .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
498
    .bdrv_refresh_limits        = nbd_refresh_limits,
499 500 501
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
502
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
503 504 505
};

static BlockDriver bdrv_nbd_unix = {
506 507 508 509 510
    .format_name                = "nbd",
    .protocol_name              = "nbd+unix",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
511 512
    .bdrv_co_preadv             = nbd_client_co_preadv,
    .bdrv_co_pwritev            = nbd_client_co_pwritev,
513 514
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
515
    .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
516
    .bdrv_refresh_limits        = nbd_refresh_limits,
517 518 519
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
520
    .bdrv_refresh_filename      = nbd_refresh_filename,
521
};
522 523 524 525

static void bdrv_nbd_init(void)
{
    bdrv_register(&bdrv_nbd);
P
Paolo Bonzini 已提交
526 527
    bdrv_register(&bdrv_nbd_tcp);
    bdrv_register(&bdrv_nbd_unix);
528 529 530
}

block_init(bdrv_nbd_init);