]> Git Repo - qemu.git/blob - block/nbd.c
block/nbd: Default port in nbd_refresh_filename()
[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 <[email protected]>
6  *
7  * Some parts:
8  *    Copyright (C) 2007 Anthony Liguori <[email protected]>
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/qmp/qdict.h"
36 #include "qapi/qmp/qjson.h"
37 #include "qapi/qmp/qint.h"
38 #include "qapi/qmp/qstring.h"
39 #include "qemu/cutils.h"
40
41 #define EN_OPTSTR ":exportname="
42
43 typedef struct BDRVNBDState {
44     NbdClientSession client;
45
46     /* For nbd_refresh_filename() */
47     char *path, *host, *port, *export, *tlscredsid;
48 } BDRVNBDState;
49
50 static int nbd_parse_uri(const char *filename, QDict *options)
51 {
52     URI *uri;
53     const char *p;
54     QueryParams *qp = NULL;
55     int ret = 0;
56     bool is_unix;
57
58     uri = uri_parse(filename);
59     if (!uri) {
60         return -EINVAL;
61     }
62
63     /* transport */
64     if (!strcmp(uri->scheme, "nbd")) {
65         is_unix = false;
66     } else if (!strcmp(uri->scheme, "nbd+tcp")) {
67         is_unix = false;
68     } else if (!strcmp(uri->scheme, "nbd+unix")) {
69         is_unix = true;
70     } else {
71         ret = -EINVAL;
72         goto out;
73     }
74
75     p = uri->path ? uri->path : "/";
76     p += strspn(p, "/");
77     if (p[0]) {
78         qdict_put(options, "export", qstring_from_str(p));
79     }
80
81     qp = query_params_parse(uri->query);
82     if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
83         ret = -EINVAL;
84         goto out;
85     }
86
87     if (is_unix) {
88         /* nbd+unix:///export?socket=path */
89         if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
90             ret = -EINVAL;
91             goto out;
92         }
93         qdict_put(options, "path", qstring_from_str(qp->p[0].value));
94     } else {
95         QString *host;
96         /* nbd[+tcp]://host[:port]/export */
97         if (!uri->server) {
98             ret = -EINVAL;
99             goto out;
100         }
101
102         /* strip braces from literal IPv6 address */
103         if (uri->server[0] == '[') {
104             host = qstring_from_substr(uri->server, 1,
105                                        strlen(uri->server) - 2);
106         } else {
107             host = qstring_from_str(uri->server);
108         }
109
110         qdict_put(options, "host", host);
111         if (uri->port) {
112             char* port_str = g_strdup_printf("%d", uri->port);
113             qdict_put(options, "port", qstring_from_str(port_str));
114             g_free(port_str);
115         }
116     }
117
118 out:
119     if (qp) {
120         query_params_free(qp);
121     }
122     uri_free(uri);
123     return ret;
124 }
125
126 static void nbd_parse_filename(const char *filename, QDict *options,
127                                Error **errp)
128 {
129     char *file;
130     char *export_name;
131     const char *host_spec;
132     const char *unixpath;
133
134     if (qdict_haskey(options, "host")
135         || qdict_haskey(options, "port")
136         || qdict_haskey(options, "path"))
137     {
138         error_setg(errp, "host/port/path and a file name may not be specified "
139                          "at the same time");
140         return;
141     }
142
143     if (strstr(filename, "://")) {
144         int ret = nbd_parse_uri(filename, options);
145         if (ret < 0) {
146             error_setg(errp, "No valid URL specified");
147         }
148         return;
149     }
150
151     file = g_strdup(filename);
152
153     export_name = strstr(file, EN_OPTSTR);
154     if (export_name) {
155         if (export_name[strlen(EN_OPTSTR)] == 0) {
156             goto out;
157         }
158         export_name[0] = 0; /* truncate 'file' */
159         export_name += strlen(EN_OPTSTR);
160
161         qdict_put(options, "export", qstring_from_str(export_name));
162     }
163
164     /* extract the host_spec - fail if it's not nbd:... */
165     if (!strstart(file, "nbd:", &host_spec)) {
166         error_setg(errp, "File name string for NBD must start with 'nbd:'");
167         goto out;
168     }
169
170     if (!*host_spec) {
171         goto out;
172     }
173
174     /* are we a UNIX or TCP socket? */
175     if (strstart(host_spec, "unix:", &unixpath)) {
176         qdict_put(options, "path", qstring_from_str(unixpath));
177     } else {
178         InetSocketAddress *addr = NULL;
179
180         addr = inet_parse(host_spec, errp);
181         if (!addr) {
182             goto out;
183         }
184
185         qdict_put(options, "host", qstring_from_str(addr->host));
186         qdict_put(options, "port", qstring_from_str(addr->port));
187         qapi_free_InetSocketAddress(addr);
188     }
189
190 out:
191     g_free(file);
192 }
193
194 static SocketAddress *nbd_config(BDRVNBDState *s, QemuOpts *opts, Error **errp)
195 {
196     SocketAddress *saddr;
197
198     s->path = g_strdup(qemu_opt_get(opts, "path"));
199     s->host = g_strdup(qemu_opt_get(opts, "host"));
200     s->port = g_strdup(qemu_opt_get(opts, "port"));
201
202     if (!s->path == !s->host) {
203         if (s->path) {
204             error_setg(errp, "path and host may not be used at the same time");
205         } else {
206             error_setg(errp, "one of path and host must be specified");
207         }
208         return NULL;
209     }
210     if (s->port && !s->host) {
211         error_setg(errp, "port may not be used without host");
212         return NULL;
213     }
214
215     saddr = g_new0(SocketAddress, 1);
216
217     if (s->path) {
218         UnixSocketAddress *q_unix;
219         saddr->type = SOCKET_ADDRESS_KIND_UNIX;
220         q_unix = saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
221         q_unix->path = g_strdup(s->path);
222     } else {
223         InetSocketAddress *inet;
224
225         saddr->type = SOCKET_ADDRESS_KIND_INET;
226         inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
227         inet->host = g_strdup(s->host);
228         inet->port = g_strdup(s->port);
229         if (!inet->port) {
230             inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
231         }
232     }
233
234     s->client.is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
235
236     s->export = g_strdup(qemu_opt_get(opts, "export"));
237
238     return saddr;
239 }
240
241 NbdClientSession *nbd_get_client_session(BlockDriverState *bs)
242 {
243     BDRVNBDState *s = bs->opaque;
244     return &s->client;
245 }
246
247 static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
248                                                   Error **errp)
249 {
250     QIOChannelSocket *sioc;
251     Error *local_err = NULL;
252
253     sioc = qio_channel_socket_new();
254
255     qio_channel_socket_connect_sync(sioc,
256                                     saddr,
257                                     &local_err);
258     if (local_err) {
259         error_propagate(errp, local_err);
260         return NULL;
261     }
262
263     qio_channel_set_delay(QIO_CHANNEL(sioc), false);
264
265     return sioc;
266 }
267
268
269 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
270 {
271     Object *obj;
272     QCryptoTLSCreds *creds;
273
274     obj = object_resolve_path_component(
275         object_get_objects_root(), id);
276     if (!obj) {
277         error_setg(errp, "No TLS credentials with id '%s'",
278                    id);
279         return NULL;
280     }
281     creds = (QCryptoTLSCreds *)
282         object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
283     if (!creds) {
284         error_setg(errp, "Object with id '%s' is not TLS credentials",
285                    id);
286         return NULL;
287     }
288
289     if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
290         error_setg(errp,
291                    "Expecting TLS credentials with a client endpoint");
292         return NULL;
293     }
294     object_ref(obj);
295     return creds;
296 }
297
298
299 static QemuOptsList nbd_runtime_opts = {
300     .name = "nbd",
301     .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
302     .desc = {
303         {
304             .name = "host",
305             .type = QEMU_OPT_STRING,
306             .help = "TCP host to connect to",
307         },
308         {
309             .name = "port",
310             .type = QEMU_OPT_STRING,
311             .help = "TCP port to connect to",
312         },
313         {
314             .name = "path",
315             .type = QEMU_OPT_STRING,
316             .help = "Unix socket path to connect to",
317         },
318         {
319             .name = "export",
320             .type = QEMU_OPT_STRING,
321             .help = "Name of the NBD export to open",
322         },
323         {
324             .name = "tls-creds",
325             .type = QEMU_OPT_STRING,
326             .help = "ID of the TLS credentials to use",
327         },
328     },
329 };
330
331 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
332                     Error **errp)
333 {
334     BDRVNBDState *s = bs->opaque;
335     QemuOpts *opts = NULL;
336     Error *local_err = NULL;
337     QIOChannelSocket *sioc = NULL;
338     SocketAddress *saddr = NULL;
339     QCryptoTLSCreds *tlscreds = NULL;
340     const char *hostname = NULL;
341     int ret = -EINVAL;
342
343     opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
344     qemu_opts_absorb_qdict(opts, options, &local_err);
345     if (local_err) {
346         error_propagate(errp, local_err);
347         goto error;
348     }
349
350     /* Pop the config into our state object. Exit if invalid. */
351     saddr = nbd_config(s, opts, errp);
352     if (!saddr) {
353         goto error;
354     }
355
356     s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
357     if (s->tlscredsid) {
358         tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
359         if (!tlscreds) {
360             goto error;
361         }
362
363         if (saddr->type != SOCKET_ADDRESS_KIND_INET) {
364             error_setg(errp, "TLS only supported over IP sockets");
365             goto error;
366         }
367         hostname = saddr->u.inet.data->host;
368     }
369
370     /* establish TCP connection, return error if it fails
371      * TODO: Configurable retry-until-timeout behaviour.
372      */
373     sioc = nbd_establish_connection(saddr, errp);
374     if (!sioc) {
375         ret = -ECONNREFUSED;
376         goto error;
377     }
378
379     /* NBD handshake */
380     ret = nbd_client_init(bs, sioc, s->export,
381                           tlscreds, hostname, errp);
382  error:
383     if (sioc) {
384         object_unref(OBJECT(sioc));
385     }
386     if (tlscreds) {
387         object_unref(OBJECT(tlscreds));
388     }
389     if (ret < 0) {
390         g_free(s->path);
391         g_free(s->host);
392         g_free(s->port);
393         g_free(s->export);
394         g_free(s->tlscredsid);
395     }
396     qapi_free_SocketAddress(saddr);
397     qemu_opts_del(opts);
398     return ret;
399 }
400
401 static int nbd_co_flush(BlockDriverState *bs)
402 {
403     return nbd_client_co_flush(bs);
404 }
405
406 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
407 {
408     bs->bl.max_pdiscard = NBD_MAX_BUFFER_SIZE;
409     bs->bl.max_transfer = NBD_MAX_BUFFER_SIZE;
410 }
411
412 static void nbd_close(BlockDriverState *bs)
413 {
414     BDRVNBDState *s = bs->opaque;
415
416     nbd_client_close(bs);
417
418     g_free(s->path);
419     g_free(s->host);
420     g_free(s->port);
421     g_free(s->export);
422     g_free(s->tlscredsid);
423 }
424
425 static int64_t nbd_getlength(BlockDriverState *bs)
426 {
427     BDRVNBDState *s = bs->opaque;
428
429     return s->client.size;
430 }
431
432 static void nbd_detach_aio_context(BlockDriverState *bs)
433 {
434     nbd_client_detach_aio_context(bs);
435 }
436
437 static void nbd_attach_aio_context(BlockDriverState *bs,
438                                    AioContext *new_context)
439 {
440     nbd_client_attach_aio_context(bs, new_context);
441 }
442
443 static void nbd_refresh_filename(BlockDriverState *bs, QDict *options)
444 {
445     BDRVNBDState *s = bs->opaque;
446     QDict *opts = qdict_new();
447     const char *port = s->port ?: stringify(NBD_DEFAULT_PORT);
448
449     qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("nbd")));
450
451     if (s->path && s->export) {
452         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
453                  "nbd+unix:///%s?socket=%s", s->export, s->path);
454     } else if (s->path && !s->export) {
455         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
456                  "nbd+unix://?socket=%s", s->path);
457     } else if (!s->path && s->export) {
458         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
459                  "nbd://%s:%s/%s", s->host, port, s->export);
460     } else if (!s->path && !s->export) {
461         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
462                  "nbd://%s:%s", s->host, port);
463     }
464
465     if (s->path) {
466         qdict_put_obj(opts, "path", QOBJECT(qstring_from_str(s->path)));
467     } else {
468         qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(s->host)));
469         qdict_put_obj(opts, "port", QOBJECT(qstring_from_str(port)));
470     }
471     if (s->export) {
472         qdict_put_obj(opts, "export", QOBJECT(qstring_from_str(s->export)));
473     }
474     if (s->tlscredsid) {
475         qdict_put_obj(opts, "tls-creds",
476                       QOBJECT(qstring_from_str(s->tlscredsid)));
477     }
478
479     bs->full_open_options = opts;
480 }
481
482 static BlockDriver bdrv_nbd = {
483     .format_name                = "nbd",
484     .protocol_name              = "nbd",
485     .instance_size              = sizeof(BDRVNBDState),
486     .bdrv_parse_filename        = nbd_parse_filename,
487     .bdrv_file_open             = nbd_open,
488     .bdrv_co_preadv             = nbd_client_co_preadv,
489     .bdrv_co_pwritev            = nbd_client_co_pwritev,
490     .bdrv_close                 = nbd_close,
491     .bdrv_co_flush_to_os        = nbd_co_flush,
492     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
493     .bdrv_refresh_limits        = nbd_refresh_limits,
494     .bdrv_getlength             = nbd_getlength,
495     .bdrv_detach_aio_context    = nbd_detach_aio_context,
496     .bdrv_attach_aio_context    = nbd_attach_aio_context,
497     .bdrv_refresh_filename      = nbd_refresh_filename,
498 };
499
500 static BlockDriver bdrv_nbd_tcp = {
501     .format_name                = "nbd",
502     .protocol_name              = "nbd+tcp",
503     .instance_size              = sizeof(BDRVNBDState),
504     .bdrv_parse_filename        = nbd_parse_filename,
505     .bdrv_file_open             = nbd_open,
506     .bdrv_co_preadv             = nbd_client_co_preadv,
507     .bdrv_co_pwritev            = nbd_client_co_pwritev,
508     .bdrv_close                 = nbd_close,
509     .bdrv_co_flush_to_os        = nbd_co_flush,
510     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
511     .bdrv_refresh_limits        = nbd_refresh_limits,
512     .bdrv_getlength             = nbd_getlength,
513     .bdrv_detach_aio_context    = nbd_detach_aio_context,
514     .bdrv_attach_aio_context    = nbd_attach_aio_context,
515     .bdrv_refresh_filename      = nbd_refresh_filename,
516 };
517
518 static BlockDriver bdrv_nbd_unix = {
519     .format_name                = "nbd",
520     .protocol_name              = "nbd+unix",
521     .instance_size              = sizeof(BDRVNBDState),
522     .bdrv_parse_filename        = nbd_parse_filename,
523     .bdrv_file_open             = nbd_open,
524     .bdrv_co_preadv             = nbd_client_co_preadv,
525     .bdrv_co_pwritev            = nbd_client_co_pwritev,
526     .bdrv_close                 = nbd_close,
527     .bdrv_co_flush_to_os        = nbd_co_flush,
528     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
529     .bdrv_refresh_limits        = nbd_refresh_limits,
530     .bdrv_getlength             = nbd_getlength,
531     .bdrv_detach_aio_context    = nbd_detach_aio_context,
532     .bdrv_attach_aio_context    = nbd_attach_aio_context,
533     .bdrv_refresh_filename      = nbd_refresh_filename,
534 };
535
536 static void bdrv_nbd_init(void)
537 {
538     bdrv_register(&bdrv_nbd);
539     bdrv_register(&bdrv_nbd_tcp);
540     bdrv_register(&bdrv_nbd_unix);
541 }
542
543 block_init(bdrv_nbd_init);
This page took 0.052553 seconds and 4 git commands to generate.