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