nbd.c 15.4 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 "qemu/uri.h"
32
#include "block/block_int.h"
33
#include "qemu/module.h"
34
#include "qapi/qmp/qdict.h"
35 36
#include "qapi/qmp/qjson.h"
#include "qapi/qmp/qint.h"
37
#include "qapi/qmp/qstring.h"
38 39


40 41
#define EN_OPTSTR ":exportname="

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

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

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

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

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

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

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

98 99 100 101 102 103 104 105 106
        /* 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);
107 108 109 110 111
        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 已提交
112 113 114 115 116 117 118 119 120 121
    }

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

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

130 131 132 133 134 135 136 137 138
    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 已提交
139
    if (strstr(filename, "://")) {
140 141 142 143 144
        int ret = nbd_parse_uri(filename, options);
        if (ret < 0) {
            error_setg(errp, "No valid URL specified");
        }
        return;
P
Paolo Bonzini 已提交
145 146
    }

147
    file = g_strdup(filename);
148

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

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

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

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

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

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

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

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

190 191
static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options, char **export,
                                 Error **errp)
192
{
193
    SocketAddress *saddr;
194

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

204
    saddr = g_new0(SocketAddress, 1);
205

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

226
    s->client.is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
227

228 229
    *export = g_strdup(qdict_get_try_str(options, "export"));
    if (*export) {
230 231
        qdict_del(options, "export");
    }
232 233

    return saddr;
234
}
235

M
Max Reitz 已提交
236 237 238 239 240 241
NbdClientSession *nbd_get_client_session(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;
    return &s->client;
}

242 243
static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
                                                  Error **errp)
244
{
245 246
    QIOChannelSocket *sioc;
    Error *local_err = NULL;
247

248
    sioc = qio_channel_socket_new();
249

250 251 252 253 254 255
    qio_channel_socket_connect_sync(sioc,
                                    saddr,
                                    &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return NULL;
256
    }
257

258
    qio_channel_set_delay(QIO_CHANNEL(sioc), false);
259

260
    return sioc;
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 288 289 290 291 292 293

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;
}


M
Max Reitz 已提交
294 295
static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
                    Error **errp)
296 297
{
    BDRVNBDState *s = bs->opaque;
298
    char *export = NULL;
299
    QIOChannelSocket *sioc = NULL;
300
    SocketAddress *saddr;
301 302 303 304
    const char *tlscredsid;
    QCryptoTLSCreds *tlscreds = NULL;
    const char *hostname = NULL;
    int ret = -EINVAL;
305

306
    /* Pop the config into our state object. Exit if invalid. */
307 308
    saddr = nbd_config(s, options, &export, errp);
    if (!saddr) {
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        goto error;
    }

    tlscredsid = g_strdup(qdict_get_try_str(options, "tls-creds"));
    if (tlscredsid) {
        qdict_del(options, "tls-creds");
        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;
        }
324
        hostname = saddr->u.inet.data->host;
325 326 327 328 329
    }

    /* establish TCP connection, return error if it fails
     * TODO: Configurable retry-until-timeout behaviour.
     */
330 331
    sioc = nbd_establish_connection(saddr, errp);
    if (!sioc) {
332 333
        ret = -ECONNREFUSED;
        goto error;
334 335
    }

M
Marc-André Lureau 已提交
336
    /* NBD handshake */
337 338 339 340 341 342 343 344 345 346
    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);
347
    g_free(export);
348
    return ret;
349 350
}

P
Paolo Bonzini 已提交
351 352 353
static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
                        int nb_sectors, QEMUIOVector *qiov)
{
M
Max Reitz 已提交
354
    return nbd_client_co_readv(bs, sector_num, nb_sectors, qiov);
P
Paolo Bonzini 已提交
355 356 357 358 359
}

static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
                         int nb_sectors, QEMUIOVector *qiov)
{
M
Max Reitz 已提交
360
    return nbd_client_co_writev(bs, sector_num, nb_sectors, qiov);
P
Paolo Bonzini 已提交
361 362
}

P
Paolo Bonzini 已提交
363 364
static int nbd_co_flush(BlockDriverState *bs)
{
M
Max Reitz 已提交
365
    return nbd_client_co_flush(bs);
P
Paolo Bonzini 已提交
366 367
}

368 369 370 371 372 373
static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
{
    bs->bl.max_discard = UINT32_MAX >> BDRV_SECTOR_BITS;
    bs->bl.max_transfer_length = UINT32_MAX >> BDRV_SECTOR_BITS;
}

P
Paolo Bonzini 已提交
374 375 376
static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
                          int nb_sectors)
{
M
Max Reitz 已提交
377
    return nbd_client_co_discard(bs, sector_num, nb_sectors);
P
Paolo Bonzini 已提交
378 379
}

380 381
static void nbd_close(BlockDriverState *bs)
{
M
Max Reitz 已提交
382
    nbd_client_close(bs);
383 384 385 386 387 388
}

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

M
Marc-André Lureau 已提交
389
    return s->client.size;
390 391
}

392 393
static void nbd_detach_aio_context(BlockDriverState *bs)
{
M
Max Reitz 已提交
394
    nbd_client_detach_aio_context(bs);
395 396 397 398 399
}

static void nbd_attach_aio_context(BlockDriverState *bs,
                                   AioContext *new_context)
{
M
Max Reitz 已提交
400
    nbd_client_attach_aio_context(bs, new_context);
401 402
}

403
static void nbd_refresh_filename(BlockDriverState *bs, QDict *options)
404 405
{
    QDict *opts = qdict_new();
406 407 408 409
    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");
410
    const char *tlscreds = qdict_get_try_str(options, "tls-creds");
411 412 413

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

M
Max Reitz 已提交
414
    if (path && export) {
415
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
416 417
                 "nbd+unix:///%s?socket=%s", export, path);
    } else if (path && !export) {
418
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
419 420 421 422 423 424 425 426 427 428 429
                 "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) {
430
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
431 432 433 434 435 436
                 "nbd://%s", host);
    }

    if (path) {
        qdict_put_obj(opts, "path", QOBJECT(qstring_from_str(path)));
    } else if (port) {
437 438
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
        qdict_put_obj(opts, "port", QOBJECT(qstring_from_str(port)));
M
Max Reitz 已提交
439 440 441 442 443
    } else {
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
    }
    if (export) {
        qdict_put_obj(opts, "export", QOBJECT(qstring_from_str(export)));
444
    }
445 446 447
    if (tlscreds) {
        qdict_put_obj(opts, "tls-creds", QOBJECT(qstring_from_str(tlscreds)));
    }
448 449 450 451

    bs->full_open_options = opts;
}

452
static BlockDriver bdrv_nbd = {
453 454 455 456 457 458 459 460 461 462
    .format_name                = "nbd",
    .protocol_name              = "nbd",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
    .bdrv_co_readv              = nbd_co_readv,
    .bdrv_co_writev             = nbd_co_writev,
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
    .bdrv_co_discard            = nbd_co_discard,
463
    .bdrv_refresh_limits        = nbd_refresh_limits,
464 465 466
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
467
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
468 469 470
};

static BlockDriver bdrv_nbd_tcp = {
471 472 473 474 475 476 477 478 479 480
    .format_name                = "nbd",
    .protocol_name              = "nbd+tcp",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
    .bdrv_co_readv              = nbd_co_readv,
    .bdrv_co_writev             = nbd_co_writev,
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
    .bdrv_co_discard            = nbd_co_discard,
481
    .bdrv_refresh_limits        = nbd_refresh_limits,
482 483 484
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
485
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
486 487 488
};

static BlockDriver bdrv_nbd_unix = {
489 490 491 492 493 494 495 496 497 498
    .format_name                = "nbd",
    .protocol_name              = "nbd+unix",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
    .bdrv_co_readv              = nbd_co_readv,
    .bdrv_co_writev             = nbd_co_writev,
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
    .bdrv_co_discard            = nbd_co_discard,
499
    .bdrv_refresh_limits        = nbd_refresh_limits,
500 501 502
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
503
    .bdrv_refresh_filename      = nbd_refresh_filename,
504
};
505 506 507 508

static void bdrv_nbd_init(void)
{
    bdrv_register(&bdrv_nbd);
P
Paolo Bonzini 已提交
509 510
    bdrv_register(&bdrv_nbd_tcp);
    bdrv_register(&bdrv_nbd_unix);
511 512 513
}

block_init(bdrv_nbd_init);