]> git.proxmox.com Git - mirror_qemu.git/blob - block/nbd.c
Merge remote-tracking branch 'remotes/vivier/tags/m68k-for-2.10-pull-request' into...
[mirror_qemu.git] / block / nbd.c
1 /*
2 * QEMU Block driver for NBD
3 *
4 * Copyright (C) 2008 Bull S.A.S.
5 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
6 *
7 * Some parts:
8 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
9 *
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
27 */
28
29 #include "qemu/osdep.h"
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-visit.h"
36 #include "qapi/qobject-input-visitor.h"
37 #include "qapi/qobject-output-visitor.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qstring.h"
41 #include "qemu/cutils.h"
42
43 #define EN_OPTSTR ":exportname="
44
45 typedef struct BDRVNBDState {
46 NBDClientSession client;
47
48 /* For nbd_refresh_filename() */
49 SocketAddress *saddr;
50 char *export, *tlscredsid;
51 } BDRVNBDState;
52
53 static int nbd_parse_uri(const char *filename, QDict *options)
54 {
55 URI *uri;
56 const char *p;
57 QueryParams *qp = NULL;
58 int ret = 0;
59 bool is_unix;
60
61 uri = uri_parse(filename);
62 if (!uri) {
63 return -EINVAL;
64 }
65
66 /* transport */
67 if (!g_strcmp0(uri->scheme, "nbd")) {
68 is_unix = false;
69 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
70 is_unix = false;
71 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
72 is_unix = true;
73 } else {
74 ret = -EINVAL;
75 goto out;
76 }
77
78 p = uri->path ? uri->path : "/";
79 p += strspn(p, "/");
80 if (p[0]) {
81 qdict_put_str(options, "export", p);
82 }
83
84 qp = query_params_parse(uri->query);
85 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
86 ret = -EINVAL;
87 goto out;
88 }
89
90 if (is_unix) {
91 /* nbd+unix:///export?socket=path */
92 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
93 ret = -EINVAL;
94 goto out;
95 }
96 qdict_put_str(options, "server.type", "unix");
97 qdict_put_str(options, "server.path", qp->p[0].value);
98 } else {
99 QString *host;
100 char *port_str;
101
102 /* nbd[+tcp]://host[:port]/export */
103 if (!uri->server) {
104 ret = -EINVAL;
105 goto out;
106 }
107
108 /* strip braces from literal IPv6 address */
109 if (uri->server[0] == '[') {
110 host = qstring_from_substr(uri->server, 1,
111 strlen(uri->server) - 2);
112 } else {
113 host = qstring_from_str(uri->server);
114 }
115
116 qdict_put_str(options, "server.type", "inet");
117 qdict_put(options, "server.host", host);
118
119 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
120 qdict_put_str(options, "server.port", port_str);
121 g_free(port_str);
122 }
123
124 out:
125 if (qp) {
126 query_params_free(qp);
127 }
128 uri_free(uri);
129 return ret;
130 }
131
132 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
133 {
134 const QDictEntry *e;
135
136 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
137 if (!strcmp(e->key, "host") ||
138 !strcmp(e->key, "port") ||
139 !strcmp(e->key, "path") ||
140 !strcmp(e->key, "export") ||
141 strstart(e->key, "server.", NULL))
142 {
143 error_setg(errp, "Option '%s' cannot be used with a file name",
144 e->key);
145 return true;
146 }
147 }
148
149 return false;
150 }
151
152 static void nbd_parse_filename(const char *filename, QDict *options,
153 Error **errp)
154 {
155 char *file;
156 char *export_name;
157 const char *host_spec;
158 const char *unixpath;
159
160 if (nbd_has_filename_options_conflict(options, errp)) {
161 return;
162 }
163
164 if (strstr(filename, "://")) {
165 int ret = nbd_parse_uri(filename, options);
166 if (ret < 0) {
167 error_setg(errp, "No valid URL specified");
168 }
169 return;
170 }
171
172 file = g_strdup(filename);
173
174 export_name = strstr(file, EN_OPTSTR);
175 if (export_name) {
176 if (export_name[strlen(EN_OPTSTR)] == 0) {
177 goto out;
178 }
179 export_name[0] = 0; /* truncate 'file' */
180 export_name += strlen(EN_OPTSTR);
181
182 qdict_put_str(options, "export", export_name);
183 }
184
185 /* extract the host_spec - fail if it's not nbd:... */
186 if (!strstart(file, "nbd:", &host_spec)) {
187 error_setg(errp, "File name string for NBD must start with 'nbd:'");
188 goto out;
189 }
190
191 if (!*host_spec) {
192 goto out;
193 }
194
195 /* are we a UNIX or TCP socket? */
196 if (strstart(host_spec, "unix:", &unixpath)) {
197 qdict_put_str(options, "server.type", "unix");
198 qdict_put_str(options, "server.path", unixpath);
199 } else {
200 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
201
202 if (inet_parse(addr, host_spec, errp)) {
203 goto out_inet;
204 }
205
206 qdict_put_str(options, "server.type", "inet");
207 qdict_put_str(options, "server.host", addr->host);
208 qdict_put_str(options, "server.port", addr->port);
209 out_inet:
210 qapi_free_InetSocketAddress(addr);
211 }
212
213 out:
214 g_free(file);
215 }
216
217 static bool nbd_process_legacy_socket_options(QDict *output_options,
218 QemuOpts *legacy_opts,
219 Error **errp)
220 {
221 const char *path = qemu_opt_get(legacy_opts, "path");
222 const char *host = qemu_opt_get(legacy_opts, "host");
223 const char *port = qemu_opt_get(legacy_opts, "port");
224 const QDictEntry *e;
225
226 if (!path && !host && !port) {
227 return true;
228 }
229
230 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
231 {
232 if (strstart(e->key, "server.", NULL)) {
233 error_setg(errp, "Cannot use 'server' and path/host/port at the "
234 "same time");
235 return false;
236 }
237 }
238
239 if (path && host) {
240 error_setg(errp, "path and host may not be used at the same time");
241 return false;
242 } else if (path) {
243 if (port) {
244 error_setg(errp, "port may not be used without host");
245 return false;
246 }
247
248 qdict_put_str(output_options, "server.type", "unix");
249 qdict_put_str(output_options, "server.path", path);
250 } else if (host) {
251 qdict_put_str(output_options, "server.type", "inet");
252 qdict_put_str(output_options, "server.host", host);
253 qdict_put_str(output_options, "server.port",
254 port ?: stringify(NBD_DEFAULT_PORT));
255 }
256
257 return true;
258 }
259
260 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
261 Error **errp)
262 {
263 SocketAddress *saddr = NULL;
264 QDict *addr = NULL;
265 QObject *crumpled_addr = NULL;
266 Visitor *iv = NULL;
267 Error *local_err = NULL;
268
269 qdict_extract_subqdict(options, &addr, "server.");
270 if (!qdict_size(addr)) {
271 error_setg(errp, "NBD server address missing");
272 goto done;
273 }
274
275 crumpled_addr = qdict_crumple(addr, errp);
276 if (!crumpled_addr) {
277 goto done;
278 }
279
280 /*
281 * FIXME .numeric, .to, .ipv4 or .ipv6 don't work with -drive
282 * server.type=inet. .to doesn't matter, it's ignored anyway.
283 * That's because when @options come from -blockdev or
284 * blockdev_add, members are typed according to the QAPI schema,
285 * but when they come from -drive, they're all QString. The
286 * visitor expects the former.
287 */
288 iv = qobject_input_visitor_new(crumpled_addr);
289 visit_type_SocketAddress(iv, NULL, &saddr, &local_err);
290 if (local_err) {
291 error_propagate(errp, local_err);
292 goto done;
293 }
294
295 done:
296 QDECREF(addr);
297 qobject_decref(crumpled_addr);
298 visit_free(iv);
299 return saddr;
300 }
301
302 NBDClientSession *nbd_get_client_session(BlockDriverState *bs)
303 {
304 BDRVNBDState *s = bs->opaque;
305 return &s->client;
306 }
307
308 static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
309 Error **errp)
310 {
311 QIOChannelSocket *sioc;
312 Error *local_err = NULL;
313
314 sioc = qio_channel_socket_new();
315 qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");
316
317 qio_channel_socket_connect_sync(sioc,
318 saddr,
319 &local_err);
320 if (local_err) {
321 object_unref(OBJECT(sioc));
322 error_propagate(errp, local_err);
323 return NULL;
324 }
325
326 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
327
328 return sioc;
329 }
330
331
332 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
333 {
334 Object *obj;
335 QCryptoTLSCreds *creds;
336
337 obj = object_resolve_path_component(
338 object_get_objects_root(), id);
339 if (!obj) {
340 error_setg(errp, "No TLS credentials with id '%s'",
341 id);
342 return NULL;
343 }
344 creds = (QCryptoTLSCreds *)
345 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
346 if (!creds) {
347 error_setg(errp, "Object with id '%s' is not TLS credentials",
348 id);
349 return NULL;
350 }
351
352 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
353 error_setg(errp,
354 "Expecting TLS credentials with a client endpoint");
355 return NULL;
356 }
357 object_ref(obj);
358 return creds;
359 }
360
361
362 static QemuOptsList nbd_runtime_opts = {
363 .name = "nbd",
364 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
365 .desc = {
366 {
367 .name = "host",
368 .type = QEMU_OPT_STRING,
369 .help = "TCP host to connect to",
370 },
371 {
372 .name = "port",
373 .type = QEMU_OPT_STRING,
374 .help = "TCP port to connect to",
375 },
376 {
377 .name = "path",
378 .type = QEMU_OPT_STRING,
379 .help = "Unix socket path to connect to",
380 },
381 {
382 .name = "export",
383 .type = QEMU_OPT_STRING,
384 .help = "Name of the NBD export to open",
385 },
386 {
387 .name = "tls-creds",
388 .type = QEMU_OPT_STRING,
389 .help = "ID of the TLS credentials to use",
390 },
391 },
392 };
393
394 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
395 Error **errp)
396 {
397 BDRVNBDState *s = bs->opaque;
398 QemuOpts *opts = NULL;
399 Error *local_err = NULL;
400 QIOChannelSocket *sioc = NULL;
401 QCryptoTLSCreds *tlscreds = NULL;
402 const char *hostname = NULL;
403 int ret = -EINVAL;
404
405 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
406 qemu_opts_absorb_qdict(opts, options, &local_err);
407 if (local_err) {
408 error_propagate(errp, local_err);
409 goto error;
410 }
411
412 /* Translate @host, @port, and @path to a SocketAddress */
413 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
414 goto error;
415 }
416
417 /* Pop the config into our state object. Exit if invalid. */
418 s->saddr = nbd_config(s, options, errp);
419 if (!s->saddr) {
420 goto error;
421 }
422
423 s->export = g_strdup(qemu_opt_get(opts, "export"));
424
425 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
426 if (s->tlscredsid) {
427 tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
428 if (!tlscreds) {
429 goto error;
430 }
431
432 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
433 if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
434 error_setg(errp, "TLS only supported over IP sockets");
435 goto error;
436 }
437 hostname = s->saddr->u.inet.host;
438 }
439
440 /* establish TCP connection, return error if it fails
441 * TODO: Configurable retry-until-timeout behaviour.
442 */
443 sioc = nbd_establish_connection(s->saddr, errp);
444 if (!sioc) {
445 ret = -ECONNREFUSED;
446 goto error;
447 }
448
449 /* NBD handshake */
450 ret = nbd_client_init(bs, sioc, s->export,
451 tlscreds, hostname, errp);
452 error:
453 if (sioc) {
454 object_unref(OBJECT(sioc));
455 }
456 if (tlscreds) {
457 object_unref(OBJECT(tlscreds));
458 }
459 if (ret < 0) {
460 qapi_free_SocketAddress(s->saddr);
461 g_free(s->export);
462 g_free(s->tlscredsid);
463 }
464 qemu_opts_del(opts);
465 return ret;
466 }
467
468 static int nbd_co_flush(BlockDriverState *bs)
469 {
470 return nbd_client_co_flush(bs);
471 }
472
473 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
474 {
475 bs->bl.max_pdiscard = NBD_MAX_BUFFER_SIZE;
476 bs->bl.max_pwrite_zeroes = NBD_MAX_BUFFER_SIZE;
477 bs->bl.max_transfer = NBD_MAX_BUFFER_SIZE;
478 }
479
480 static void nbd_close(BlockDriverState *bs)
481 {
482 BDRVNBDState *s = bs->opaque;
483
484 nbd_client_close(bs);
485
486 qapi_free_SocketAddress(s->saddr);
487 g_free(s->export);
488 g_free(s->tlscredsid);
489 }
490
491 static int64_t nbd_getlength(BlockDriverState *bs)
492 {
493 BDRVNBDState *s = bs->opaque;
494
495 return s->client.size;
496 }
497
498 static void nbd_detach_aio_context(BlockDriverState *bs)
499 {
500 nbd_client_detach_aio_context(bs);
501 }
502
503 static void nbd_attach_aio_context(BlockDriverState *bs,
504 AioContext *new_context)
505 {
506 nbd_client_attach_aio_context(bs, new_context);
507 }
508
509 static void nbd_refresh_filename(BlockDriverState *bs, QDict *options)
510 {
511 BDRVNBDState *s = bs->opaque;
512 QDict *opts = qdict_new();
513 QObject *saddr_qdict;
514 Visitor *ov;
515 const char *host = NULL, *port = NULL, *path = NULL;
516
517 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
518 const InetSocketAddress *inet = &s->saddr->u.inet;
519 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
520 host = inet->host;
521 port = inet->port;
522 }
523 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
524 path = s->saddr->u.q_unix.path;
525 } /* else can't represent as pseudo-filename */
526
527 qdict_put_str(opts, "driver", "nbd");
528
529 if (path && s->export) {
530 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
531 "nbd+unix:///%s?socket=%s", s->export, path);
532 } else if (path && !s->export) {
533 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
534 "nbd+unix://?socket=%s", path);
535 } else if (host && s->export) {
536 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
537 "nbd://%s:%s/%s", host, port, s->export);
538 } else if (host && !s->export) {
539 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
540 "nbd://%s:%s", host, port);
541 }
542
543 ov = qobject_output_visitor_new(&saddr_qdict);
544 visit_type_SocketAddress(ov, NULL, &s->saddr, &error_abort);
545 visit_complete(ov, &saddr_qdict);
546 visit_free(ov);
547 qdict_put_obj(opts, "server", saddr_qdict);
548
549 if (s->export) {
550 qdict_put_str(opts, "export", s->export);
551 }
552 if (s->tlscredsid) {
553 qdict_put_str(opts, "tls-creds", s->tlscredsid);
554 }
555
556 qdict_flatten(opts);
557 bs->full_open_options = opts;
558 }
559
560 static BlockDriver bdrv_nbd = {
561 .format_name = "nbd",
562 .protocol_name = "nbd",
563 .instance_size = sizeof(BDRVNBDState),
564 .bdrv_parse_filename = nbd_parse_filename,
565 .bdrv_file_open = nbd_open,
566 .bdrv_co_preadv = nbd_client_co_preadv,
567 .bdrv_co_pwritev = nbd_client_co_pwritev,
568 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
569 .bdrv_close = nbd_close,
570 .bdrv_co_flush_to_os = nbd_co_flush,
571 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
572 .bdrv_refresh_limits = nbd_refresh_limits,
573 .bdrv_getlength = nbd_getlength,
574 .bdrv_detach_aio_context = nbd_detach_aio_context,
575 .bdrv_attach_aio_context = nbd_attach_aio_context,
576 .bdrv_refresh_filename = nbd_refresh_filename,
577 };
578
579 static BlockDriver bdrv_nbd_tcp = {
580 .format_name = "nbd",
581 .protocol_name = "nbd+tcp",
582 .instance_size = sizeof(BDRVNBDState),
583 .bdrv_parse_filename = nbd_parse_filename,
584 .bdrv_file_open = nbd_open,
585 .bdrv_co_preadv = nbd_client_co_preadv,
586 .bdrv_co_pwritev = nbd_client_co_pwritev,
587 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
588 .bdrv_close = nbd_close,
589 .bdrv_co_flush_to_os = nbd_co_flush,
590 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
591 .bdrv_refresh_limits = nbd_refresh_limits,
592 .bdrv_getlength = nbd_getlength,
593 .bdrv_detach_aio_context = nbd_detach_aio_context,
594 .bdrv_attach_aio_context = nbd_attach_aio_context,
595 .bdrv_refresh_filename = nbd_refresh_filename,
596 };
597
598 static BlockDriver bdrv_nbd_unix = {
599 .format_name = "nbd",
600 .protocol_name = "nbd+unix",
601 .instance_size = sizeof(BDRVNBDState),
602 .bdrv_parse_filename = nbd_parse_filename,
603 .bdrv_file_open = nbd_open,
604 .bdrv_co_preadv = nbd_client_co_preadv,
605 .bdrv_co_pwritev = nbd_client_co_pwritev,
606 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
607 .bdrv_close = nbd_close,
608 .bdrv_co_flush_to_os = nbd_co_flush,
609 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
610 .bdrv_refresh_limits = nbd_refresh_limits,
611 .bdrv_getlength = nbd_getlength,
612 .bdrv_detach_aio_context = nbd_detach_aio_context,
613 .bdrv_attach_aio_context = nbd_attach_aio_context,
614 .bdrv_refresh_filename = nbd_refresh_filename,
615 };
616
617 static void bdrv_nbd_init(void)
618 {
619 bdrv_register(&bdrv_nbd);
620 bdrv_register(&bdrv_nbd_tcp);
621 bdrv_register(&bdrv_nbd_unix);
622 }
623
624 block_init(bdrv_nbd_init);