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