]> Git Repo - qemu.git/blob - nbd.c
Merge remote-tracking branch 'kiszka/queues/slirp' into staging
[qemu.git] / nbd.c
1 /*
2  *  Copyright (C) 2005  Anthony Liguori <[email protected]>
3  *
4  *  Network Block Device
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; under version 2 of the License.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "nbd.h"
20 #include "block.h"
21
22 #include <errno.h>
23 #include <string.h>
24 #ifndef _WIN32
25 #include <sys/ioctl.h>
26 #endif
27 #if defined(__sun__) || defined(__HAIKU__)
28 #include <sys/ioccom.h>
29 #endif
30 #include <ctype.h>
31 #include <inttypes.h>
32
33 #include "qemu_socket.h"
34
35 //#define DEBUG_NBD
36
37 #ifdef DEBUG_NBD
38 #define TRACE(msg, ...) do { \
39     LOG(msg, ## __VA_ARGS__); \
40 } while(0)
41 #else
42 #define TRACE(msg, ...) \
43     do { } while (0)
44 #endif
45
46 #define LOG(msg, ...) do { \
47     fprintf(stderr, "%s:%s():L%d: " msg "\n", \
48             __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
49 } while(0)
50
51 /* This is all part of the "official" NBD API */
52
53 #define NBD_REPLY_SIZE          (4 + 4 + 8)
54 #define NBD_REQUEST_MAGIC       0x25609513
55 #define NBD_REPLY_MAGIC         0x67446698
56
57 #define NBD_SET_SOCK            _IO(0xab, 0)
58 #define NBD_SET_BLKSIZE         _IO(0xab, 1)
59 #define NBD_SET_SIZE            _IO(0xab, 2)
60 #define NBD_DO_IT               _IO(0xab, 3)
61 #define NBD_CLEAR_SOCK          _IO(0xab, 4)
62 #define NBD_CLEAR_QUE           _IO(0xab, 5)
63 #define NBD_PRINT_DEBUG         _IO(0xab, 6)
64 #define NBD_SET_SIZE_BLOCKS     _IO(0xab, 7)
65 #define NBD_DISCONNECT          _IO(0xab, 8)
66
67 #define NBD_OPT_EXPORT_NAME     (1 << 0)
68
69 /* That's all folks */
70
71 #define read_sync(fd, buffer, size) nbd_wr_sync(fd, buffer, size, true)
72 #define write_sync(fd, buffer, size) nbd_wr_sync(fd, buffer, size, false)
73
74 size_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)
75 {
76     size_t offset = 0;
77
78     while (offset < size) {
79         ssize_t len;
80
81         if (do_read) {
82             len = qemu_recv(fd, buffer + offset, size - offset, 0);
83         } else {
84             len = send(fd, buffer + offset, size - offset, 0);
85         }
86
87         if (len == -1)
88             errno = socket_error();
89
90         /* recoverable error */
91         if (len == -1 && (errno == EAGAIN || errno == EINTR)) {
92             continue;
93         }
94
95         /* eof */
96         if (len == 0) {
97             break;
98         }
99
100         /* unrecoverable error */
101         if (len == -1) {
102             return 0;
103         }
104
105         offset += len;
106     }
107
108     return offset;
109 }
110
111 static void combine_addr(char *buf, size_t len, const char* address,
112                          uint16_t port)
113 {
114     /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
115     if (strstr(address, ":")) {
116         snprintf(buf, len, "[%s]:%u", address, port);
117     } else {
118         snprintf(buf, len, "%s:%u", address, port);
119     }
120 }
121
122 int tcp_socket_outgoing(const char *address, uint16_t port)
123 {
124     char address_and_port[128];
125     combine_addr(address_and_port, 128, address, port);
126     return tcp_socket_outgoing_spec(address_and_port);
127 }
128
129 int tcp_socket_outgoing_spec(const char *address_and_port)
130 {
131     return inet_connect(address_and_port, SOCK_STREAM);
132 }
133
134 int tcp_socket_incoming(const char *address, uint16_t port)
135 {
136     char address_and_port[128];
137     combine_addr(address_and_port, 128, address, port);
138     return tcp_socket_incoming_spec(address_and_port);
139 }
140
141 int tcp_socket_incoming_spec(const char *address_and_port)
142 {
143     char *ostr  = NULL;
144     int olen = 0;
145     return inet_listen(address_and_port, ostr, olen, SOCK_STREAM, 0);
146 }
147
148 int unix_socket_incoming(const char *path)
149 {
150     char *ostr = NULL;
151     int olen = 0;
152
153     return unix_listen(path, ostr, olen);
154 }
155
156 int unix_socket_outgoing(const char *path)
157 {
158     return unix_connect(path);
159 }
160
161 /* Basic flow
162
163    Server         Client
164
165    Negotiate
166                   Request
167    Response
168                   Request
169    Response
170                   ...
171    ...
172                   Request (type == 2)
173 */
174
175 int nbd_negotiate(int csock, off_t size)
176 {
177     char buf[8 + 8 + 8 + 128];
178
179     /* Negotiate
180         [ 0 ..   7]   passwd   ("NBDMAGIC")
181         [ 8 ..  15]   magic    (0x00420281861253)
182         [16 ..  23]   size
183         [24 .. 151]   reserved (0)
184      */
185
186     TRACE("Beginning negotiation.");
187     memcpy(buf, "NBDMAGIC", 8);
188     cpu_to_be64w((uint64_t*)(buf + 8), 0x00420281861253LL);
189     cpu_to_be64w((uint64_t*)(buf + 16), size);
190     memset(buf + 24, 0, 128);
191
192     if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
193         LOG("write failed");
194         errno = EINVAL;
195         return -1;
196     }
197
198     TRACE("Negotation succeeded.");
199
200     return 0;
201 }
202
203 int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,
204                           off_t *size, size_t *blocksize)
205 {
206     char buf[256];
207     uint64_t magic, s;
208     uint16_t tmp;
209
210     TRACE("Receiving negotation.");
211
212     if (read_sync(csock, buf, 8) != 8) {
213         LOG("read failed");
214         errno = EINVAL;
215         return -1;
216     }
217
218     buf[8] = '\0';
219     if (strlen(buf) == 0) {
220         LOG("server connection closed");
221         errno = EINVAL;
222         return -1;
223     }
224
225     TRACE("Magic is %c%c%c%c%c%c%c%c",
226           qemu_isprint(buf[0]) ? buf[0] : '.',
227           qemu_isprint(buf[1]) ? buf[1] : '.',
228           qemu_isprint(buf[2]) ? buf[2] : '.',
229           qemu_isprint(buf[3]) ? buf[3] : '.',
230           qemu_isprint(buf[4]) ? buf[4] : '.',
231           qemu_isprint(buf[5]) ? buf[5] : '.',
232           qemu_isprint(buf[6]) ? buf[6] : '.',
233           qemu_isprint(buf[7]) ? buf[7] : '.');
234
235     if (memcmp(buf, "NBDMAGIC", 8) != 0) {
236         LOG("Invalid magic received");
237         errno = EINVAL;
238         return -1;
239     }
240
241     if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
242         LOG("read failed");
243         errno = EINVAL;
244         return -1;
245     }
246     magic = be64_to_cpu(magic);
247     TRACE("Magic is 0x%" PRIx64, magic);
248
249     if (name) {
250         uint32_t reserved = 0;
251         uint32_t opt;
252         uint32_t namesize;
253
254         TRACE("Checking magic (opts_magic)");
255         if (magic != 0x49484156454F5054LL) {
256             LOG("Bad magic received");
257             errno = EINVAL;
258             return -1;
259         }
260         if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
261             LOG("flags read failed");
262             errno = EINVAL;
263             return -1;
264         }
265         *flags = be16_to_cpu(tmp) << 16;
266         /* reserved for future use */
267         if (write_sync(csock, &reserved, sizeof(reserved)) !=
268             sizeof(reserved)) {
269             LOG("write failed (reserved)");
270             errno = EINVAL;
271             return -1;
272         }
273         /* write the export name */
274         magic = cpu_to_be64(magic);
275         if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
276             LOG("write failed (magic)");
277             errno = EINVAL;
278             return -1;
279         }
280         opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);
281         if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
282             LOG("write failed (opt)");
283             errno = EINVAL;
284             return -1;
285         }
286         namesize = cpu_to_be32(strlen(name));
287         if (write_sync(csock, &namesize, sizeof(namesize)) !=
288             sizeof(namesize)) {
289             LOG("write failed (namesize)");
290             errno = EINVAL;
291             return -1;
292         }
293         if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {
294             LOG("write failed (name)");
295             errno = EINVAL;
296             return -1;
297         }
298     } else {
299         TRACE("Checking magic (cli_magic)");
300
301         if (magic != 0x00420281861253LL) {
302             LOG("Bad magic received");
303             errno = EINVAL;
304             return -1;
305         }
306     }
307
308     if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {
309         LOG("read failed");
310         errno = EINVAL;
311         return -1;
312     }
313     *size = be64_to_cpu(s);
314     *blocksize = 1024;
315     TRACE("Size is %" PRIu64, *size);
316
317     if (!name) {
318         if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {
319             LOG("read failed (flags)");
320             errno = EINVAL;
321             return -1;
322         }
323         *flags = be32_to_cpup(flags);
324     } else {
325         if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
326             LOG("read failed (tmp)");
327             errno = EINVAL;
328             return -1;
329         }
330         *flags |= be32_to_cpu(tmp);
331     }
332     if (read_sync(csock, &buf, 124) != 124) {
333         LOG("read failed (buf)");
334         errno = EINVAL;
335         return -1;
336     }
337         return 0;
338 }
339
340 #ifndef _WIN32
341 int nbd_init(int fd, int csock, off_t size, size_t blocksize)
342 {
343     TRACE("Setting block size to %lu", (unsigned long)blocksize);
344
345     if (ioctl(fd, NBD_SET_BLKSIZE, blocksize) == -1) {
346         int serrno = errno;
347         LOG("Failed setting NBD block size");
348         errno = serrno;
349         return -1;
350     }
351
352         TRACE("Setting size to %zd block(s)", (size_t)(size / blocksize));
353
354     if (ioctl(fd, NBD_SET_SIZE_BLOCKS, size / blocksize) == -1) {
355         int serrno = errno;
356         LOG("Failed setting size (in blocks)");
357         errno = serrno;
358         return -1;
359     }
360
361     TRACE("Clearing NBD socket");
362
363     if (ioctl(fd, NBD_CLEAR_SOCK) == -1) {
364         int serrno = errno;
365         LOG("Failed clearing NBD socket");
366         errno = serrno;
367         return -1;
368     }
369
370     TRACE("Setting NBD socket");
371
372     if (ioctl(fd, NBD_SET_SOCK, csock) == -1) {
373         int serrno = errno;
374         LOG("Failed to set NBD socket");
375         errno = serrno;
376         return -1;
377     }
378
379     TRACE("Negotiation ended");
380
381     return 0;
382 }
383
384 int nbd_disconnect(int fd)
385 {
386     ioctl(fd, NBD_CLEAR_QUE);
387     ioctl(fd, NBD_DISCONNECT);
388     ioctl(fd, NBD_CLEAR_SOCK);
389     return 0;
390 }
391
392 int nbd_client(int fd)
393 {
394     int ret;
395     int serrno;
396
397     TRACE("Doing NBD loop");
398
399     ret = ioctl(fd, NBD_DO_IT);
400     serrno = errno;
401
402     TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
403
404     TRACE("Clearing NBD queue");
405     ioctl(fd, NBD_CLEAR_QUE);
406
407     TRACE("Clearing NBD socket");
408     ioctl(fd, NBD_CLEAR_SOCK);
409
410     errno = serrno;
411     return ret;
412 }
413 #else
414 int nbd_init(int fd, int csock, off_t size, size_t blocksize)
415 {
416     errno = ENOTSUP;
417     return -1;
418 }
419
420 int nbd_disconnect(int fd)
421 {
422     errno = ENOTSUP;
423     return -1;
424 }
425
426 int nbd_client(int fd)
427 {
428     errno = ENOTSUP;
429     return -1;
430 }
431 #endif
432
433 int nbd_send_request(int csock, struct nbd_request *request)
434 {
435     uint8_t buf[4 + 4 + 8 + 8 + 4];
436
437     cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);
438     cpu_to_be32w((uint32_t*)(buf + 4), request->type);
439     cpu_to_be64w((uint64_t*)(buf + 8), request->handle);
440     cpu_to_be64w((uint64_t*)(buf + 16), request->from);
441     cpu_to_be32w((uint32_t*)(buf + 24), request->len);
442
443     TRACE("Sending request to client: "
444           "{ .from = %" PRIu64", .len = %u, .handle = %" PRIu64", .type=%i}",
445           request->from, request->len, request->handle, request->type);
446
447     if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
448         LOG("writing to socket failed");
449         errno = EINVAL;
450         return -1;
451     }
452     return 0;
453 }
454
455 static int nbd_receive_request(int csock, struct nbd_request *request)
456 {
457     uint8_t buf[4 + 4 + 8 + 8 + 4];
458     uint32_t magic;
459
460     if (read_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
461         LOG("read failed");
462         errno = EINVAL;
463         return -1;
464     }
465
466     /* Request
467        [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)
468        [ 4 ..  7]   type    (0 == READ, 1 == WRITE)
469        [ 8 .. 15]   handle
470        [16 .. 23]   from
471        [24 .. 27]   len
472      */
473
474     magic = be32_to_cpup((uint32_t*)buf);
475     request->type  = be32_to_cpup((uint32_t*)(buf + 4));
476     request->handle = be64_to_cpup((uint64_t*)(buf + 8));
477     request->from  = be64_to_cpup((uint64_t*)(buf + 16));
478     request->len   = be32_to_cpup((uint32_t*)(buf + 24));
479
480     TRACE("Got request: "
481           "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
482           magic, request->type, request->from, request->len);
483
484     if (magic != NBD_REQUEST_MAGIC) {
485         LOG("invalid magic (got 0x%x)", magic);
486         errno = EINVAL;
487         return -1;
488     }
489     return 0;
490 }
491
492 int nbd_receive_reply(int csock, struct nbd_reply *reply)
493 {
494     uint8_t buf[NBD_REPLY_SIZE];
495     uint32_t magic;
496
497     memset(buf, 0xAA, sizeof(buf));
498
499     if (read_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
500         LOG("read failed");
501         errno = EINVAL;
502         return -1;
503     }
504
505     /* Reply
506        [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
507        [ 4 ..  7]    error   (0 == no error)
508        [ 7 .. 15]    handle
509      */
510
511     magic = be32_to_cpup((uint32_t*)buf);
512     reply->error  = be32_to_cpup((uint32_t*)(buf + 4));
513     reply->handle = be64_to_cpup((uint64_t*)(buf + 8));
514
515     TRACE("Got reply: "
516           "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",
517           magic, reply->error, reply->handle);
518
519     if (magic != NBD_REPLY_MAGIC) {
520         LOG("invalid magic (got 0x%x)", magic);
521         errno = EINVAL;
522         return -1;
523     }
524     return 0;
525 }
526
527 static int nbd_send_reply(int csock, struct nbd_reply *reply)
528 {
529     uint8_t buf[4 + 4 + 8];
530
531     /* Reply
532        [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
533        [ 4 ..  7]    error   (0 == no error)
534        [ 7 .. 15]    handle
535      */
536     cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
537     cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
538     cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
539
540     TRACE("Sending response to client");
541
542     if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
543         LOG("writing to socket failed");
544         errno = EINVAL;
545         return -1;
546     }
547     return 0;
548 }
549
550 int nbd_trip(BlockDriverState *bs, int csock, off_t size, uint64_t dev_offset,
551              off_t *offset, bool readonly, uint8_t *data, int data_size)
552 {
553     struct nbd_request request;
554     struct nbd_reply reply;
555
556     TRACE("Reading request.");
557
558     if (nbd_receive_request(csock, &request) == -1)
559         return -1;
560
561     if (request.len + NBD_REPLY_SIZE > data_size) {
562         LOG("len (%u) is larger than max len (%u)",
563             request.len + NBD_REPLY_SIZE, data_size);
564         errno = EINVAL;
565         return -1;
566     }
567
568     if ((request.from + request.len) < request.from) {
569         LOG("integer overflow detected! "
570             "you're probably being attacked");
571         errno = EINVAL;
572         return -1;
573     }
574
575     if ((request.from + request.len) > size) {
576             LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
577             ", Offset: %" PRIu64 "\n",
578                     request.from, request.len, (uint64_t)size, dev_offset);
579         LOG("requested operation past EOF--bad client?");
580         errno = EINVAL;
581         return -1;
582     }
583
584     TRACE("Decoding type");
585
586     reply.handle = request.handle;
587     reply.error = 0;
588
589     switch (request.type) {
590     case NBD_CMD_READ:
591         TRACE("Request type is READ");
592
593         if (bdrv_read(bs, (request.from + dev_offset) / 512,
594                   data + NBD_REPLY_SIZE,
595                   request.len / 512) == -1) {
596             LOG("reading from file failed");
597             errno = EINVAL;
598             return -1;
599         }
600         *offset += request.len;
601
602         TRACE("Read %u byte(s)", request.len);
603
604         /* Reply
605            [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
606            [ 4 ..  7]    error   (0 == no error)
607            [ 7 .. 15]    handle
608          */
609
610         cpu_to_be32w((uint32_t*)data, NBD_REPLY_MAGIC);
611         cpu_to_be32w((uint32_t*)(data + 4), reply.error);
612         cpu_to_be64w((uint64_t*)(data + 8), reply.handle);
613
614         TRACE("Sending data to client");
615
616         if (write_sync(csock, data,
617                    request.len + NBD_REPLY_SIZE) !=
618                    request.len + NBD_REPLY_SIZE) {
619             LOG("writing to socket failed");
620             errno = EINVAL;
621             return -1;
622         }
623         break;
624     case NBD_CMD_WRITE:
625         TRACE("Request type is WRITE");
626
627         TRACE("Reading %u byte(s)", request.len);
628
629         if (read_sync(csock, data, request.len) != request.len) {
630             LOG("reading from socket failed");
631             errno = EINVAL;
632             return -1;
633         }
634
635         if (readonly) {
636             TRACE("Server is read-only, return error");
637             reply.error = 1;
638         } else {
639             TRACE("Writing to device");
640
641             if (bdrv_write(bs, (request.from + dev_offset) / 512,
642                        data, request.len / 512) == -1) {
643                 LOG("writing to file failed");
644                 errno = EINVAL;
645                 return -1;
646             }
647
648             *offset += request.len;
649         }
650
651         if (nbd_send_reply(csock, &reply) == -1)
652             return -1;
653         break;
654     case NBD_CMD_DISC:
655         TRACE("Request type is DISCONNECT");
656         errno = 0;
657         return 1;
658     default:
659         LOG("invalid request type (%u) received", request.type);
660         errno = EINVAL;
661         return -1;
662     }
663
664     TRACE("Request/Reply complete");
665
666     return 0;
667 }
This page took 0.061793 seconds and 4 git commands to generate.