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