Merge "[Title]strikethrough when version is mismatched and add socket option SO_REUSE...
[sdk/emulator/qemu.git] / nbd.c
1 /*
2  *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
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
21 #include <errno.h>
22 #include <string.h>
23 #ifndef _WIN32
24 #include <sys/ioctl.h>
25 #endif
26 #if defined(__sun__) || defined(__HAIKU__)
27 #include <sys/ioccom.h>
28 #endif
29 #include <ctype.h>
30 #include <inttypes.h>
31
32 #include "qemu_socket.h"
33
34 //#define DEBUG_NBD
35
36 #ifdef DEBUG_NBD
37 #define TRACE(msg, ...) do { \
38     LOG(msg, ## __VA_ARGS__); \
39 } while(0)
40 #else
41 #define TRACE(msg, ...) \
42     do { } while (0)
43 #endif
44
45 #define LOG(msg, ...) do { \
46     fprintf(stderr, "%s:%s():L%d: " msg "\n", \
47             __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
48 } while(0)
49
50 /* This is all part of the "official" NBD API */
51
52 #define NBD_REPLY_SIZE          (4 + 4 + 8)
53 #define NBD_REQUEST_MAGIC       0x25609513
54 #define NBD_REPLY_MAGIC         0x67446698
55
56 #define NBD_SET_SOCK            _IO(0xab, 0)
57 #define NBD_SET_BLKSIZE         _IO(0xab, 1)
58 #define NBD_SET_SIZE            _IO(0xab, 2)
59 #define NBD_DO_IT               _IO(0xab, 3)
60 #define NBD_CLEAR_SOCK          _IO(0xab, 4)
61 #define NBD_CLEAR_QUE           _IO(0xab, 5)
62 #define NBD_PRINT_DEBUG         _IO(0xab, 6)
63 #define NBD_SET_SIZE_BLOCKS     _IO(0xab, 7)
64 #define NBD_DISCONNECT          _IO(0xab, 8)
65
66 #define NBD_OPT_EXPORT_NAME     (1 << 0)
67
68 /* That's all folks */
69
70 #define read_sync(fd, buffer, size) nbd_wr_sync(fd, buffer, size, true)
71 #define write_sync(fd, buffer, size) nbd_wr_sync(fd, buffer, size, false)
72
73 size_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)
74 {
75     size_t offset = 0;
76
77     while (offset < size) {
78         ssize_t len;
79
80         if (do_read) {
81             len = recv(fd, buffer + offset, size - offset, 0);
82         } else {
83             len = send(fd, buffer + offset, size - offset, 0);
84         }
85
86         if (len == -1)
87             errno = socket_error();
88
89         /* recoverable error */
90         if (len == -1 && (errno == EAGAIN || errno == EINTR)) {
91             continue;
92         }
93
94         /* eof */
95         if (len == 0) {
96             break;
97         }
98
99         /* unrecoverable error */
100         if (len == -1) {
101             return 0;
102         }
103
104         offset += len;
105     }
106
107     return offset;
108 }
109
110 int tcp_socket_outgoing(const char *address, uint16_t port)
111 {
112     int s;
113         int i = 1;
114     struct in_addr in;
115     struct sockaddr_in addr;
116
117     s = socket(PF_INET, SOCK_STREAM, 0);
118     if (s == -1) {
119         return -1;
120     }
121         
122         if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&i, sizeof(int)) == -1) {
123                 goto error;
124         }
125
126     if (inet_aton(address, &in) == 0) {
127         struct hostent *ent;
128
129         ent = gethostbyname(address);
130         if (ent == NULL) {
131             goto error;
132         }
133
134         memcpy(&in, ent->h_addr, sizeof(in));
135     }
136
137     addr.sin_family = AF_INET;
138     addr.sin_port = htons(port);
139     memcpy(&addr.sin_addr.s_addr, &in, sizeof(in));
140
141     if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
142         goto error;
143     }
144
145     return s;
146 error:
147     closesocket(s);
148     return -1;
149 }
150
151 int tcp_socket_incoming(const char *address, uint16_t port)
152 {
153     int s;
154     struct in_addr in;
155     struct sockaddr_in addr;
156     int opt;
157
158     s = socket(PF_INET, SOCK_STREAM, 0);
159     if (s == -1) {
160         return -1;
161     }
162
163     if (inet_aton(address, &in) == 0) {
164         struct hostent *ent;
165
166         ent = gethostbyname(address);
167         if (ent == NULL) {
168             goto error;
169         }
170
171         memcpy(&in, ent->h_addr, sizeof(in));
172     }
173
174     addr.sin_family = AF_INET;
175     addr.sin_port = htons(port);
176     memcpy(&addr.sin_addr.s_addr, &in, sizeof(in));
177
178     opt = 1;
179     if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
180                    (const void *) &opt, sizeof(opt)) == -1) {
181         goto error;
182     }
183
184     if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
185         goto error;
186     }
187
188     if (listen(s, 128) == -1) {
189         goto error;
190     }
191
192     return s;
193 error:
194     closesocket(s);
195     return -1;
196 }
197
198 #ifndef _WIN32
199 int unix_socket_incoming(const char *path)
200 {
201     int s;
202     struct sockaddr_un addr;
203
204     s = socket(PF_UNIX, SOCK_STREAM, 0);
205     if (s == -1) {
206         return -1;
207     }
208
209     memset(&addr, 0, sizeof(addr));
210     addr.sun_family = AF_UNIX;
211     pstrcpy(addr.sun_path, sizeof(addr.sun_path), path);
212
213     if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
214         goto error;
215     }
216
217     if (listen(s, 128) == -1) {
218         goto error;
219     }
220
221     return s;
222 error:
223     closesocket(s);
224     return -1;
225 }
226
227 int unix_socket_outgoing(const char *path)
228 {
229     int s;
230     struct sockaddr_un addr;
231
232     s = socket(PF_UNIX, SOCK_STREAM, 0);
233     if (s == -1) {
234         return -1;
235     }
236
237     memset(&addr, 0, sizeof(addr));
238     addr.sun_family = AF_UNIX;
239     pstrcpy(addr.sun_path, sizeof(addr.sun_path), path);
240
241     if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
242         goto error;
243     }
244
245     return s;
246 error:
247     closesocket(s);
248     return -1;
249 }
250 #else
251 int unix_socket_incoming(const char *path)
252 {
253     errno = ENOTSUP;
254     return -1;
255 }
256
257 int unix_socket_outgoing(const char *path)
258 {
259     errno = ENOTSUP;
260     return -1;
261 }
262 #endif
263
264
265 /* Basic flow
266
267    Server         Client
268
269    Negotiate
270                   Request
271    Response
272                   Request
273    Response
274                   ...
275    ...
276                   Request (type == 2)
277 */
278
279 int nbd_negotiate(int csock, off_t size)
280 {
281         char buf[8 + 8 + 8 + 128];
282
283         /* Negotiate
284            [ 0 ..   7]   passwd   ("NBDMAGIC")
285            [ 8 ..  15]   magic    (0x00420281861253)
286            [16 ..  23]   size
287            [24 .. 151]   reserved (0)
288          */
289
290         TRACE("Beginning negotiation.");
291         memcpy(buf, "NBDMAGIC", 8);
292         cpu_to_be64w((uint64_t*)(buf + 8), 0x00420281861253LL);
293         cpu_to_be64w((uint64_t*)(buf + 16), size);
294         memset(buf + 24, 0, 128);
295
296         if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
297                 LOG("write failed");
298                 errno = EINVAL;
299                 return -1;
300         }
301
302         TRACE("Negotation succeeded.");
303
304         return 0;
305 }
306
307 int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,
308                           off_t *size, size_t *blocksize)
309 {
310         char buf[256];
311         uint64_t magic, s;
312         uint16_t tmp;
313
314         TRACE("Receiving negotation.");
315
316         if (read_sync(csock, buf, 8) != 8) {
317                 LOG("read failed");
318                 errno = EINVAL;
319                 return -1;
320         }
321
322         buf[8] = '\0';
323         if (strlen(buf) == 0) {
324                 LOG("server connection closed");
325                 errno = EINVAL;
326                 return -1;
327         }
328
329         TRACE("Magic is %c%c%c%c%c%c%c%c",
330               qemu_isprint(buf[0]) ? buf[0] : '.',
331               qemu_isprint(buf[1]) ? buf[1] : '.',
332               qemu_isprint(buf[2]) ? buf[2] : '.',
333               qemu_isprint(buf[3]) ? buf[3] : '.',
334               qemu_isprint(buf[4]) ? buf[4] : '.',
335               qemu_isprint(buf[5]) ? buf[5] : '.',
336               qemu_isprint(buf[6]) ? buf[6] : '.',
337               qemu_isprint(buf[7]) ? buf[7] : '.');
338
339         if (memcmp(buf, "NBDMAGIC", 8) != 0) {
340                 LOG("Invalid magic received");
341                 errno = EINVAL;
342                 return -1;
343         }
344
345         if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
346                 LOG("read failed");
347                 errno = EINVAL;
348                 return -1;
349         }
350         magic = be64_to_cpu(magic);
351         TRACE("Magic is 0x%" PRIx64, magic);
352
353         if (name) {
354                 uint32_t reserved = 0;
355                 uint32_t opt;
356                 uint32_t namesize;
357
358                 TRACE("Checking magic (opts_magic)");
359                 if (magic != 0x49484156454F5054LL) {
360                         LOG("Bad magic received");
361                         errno = EINVAL;
362                         return -1;
363                 }
364                 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
365                         LOG("flags read failed");
366                         errno = EINVAL;
367                         return -1;
368                 }
369                 *flags = be16_to_cpu(tmp) << 16;
370                 /* reserved for future use */
371                 if (write_sync(csock, &reserved, sizeof(reserved)) !=
372                     sizeof(reserved)) {
373                         LOG("write failed (reserved)");
374                         errno = EINVAL;
375                         return -1;
376                 }
377                 /* write the export name */
378                 magic = cpu_to_be64(magic);
379                 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
380                         LOG("write failed (magic)");
381                         errno = EINVAL;
382                         return -1;
383                 }
384                 opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);
385                 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
386                         LOG("write failed (opt)");
387                         errno = EINVAL;
388                         return -1;
389                 }
390                 namesize = cpu_to_be32(strlen(name));
391                 if (write_sync(csock, &namesize, sizeof(namesize)) !=
392                     sizeof(namesize)) {
393                         LOG("write failed (namesize)");
394                         errno = EINVAL;
395                         return -1;
396                 }
397                 if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {
398                         LOG("write failed (name)");
399                         errno = EINVAL;
400                         return -1;
401                 }
402         } else {
403                 TRACE("Checking magic (cli_magic)");
404
405                 if (magic != 0x00420281861253LL) {
406                         LOG("Bad magic received");
407                         errno = EINVAL;
408                         return -1;
409                 }
410         }
411
412         if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {
413                 LOG("read failed");
414                 errno = EINVAL;
415                 return -1;
416         }
417         *size = be64_to_cpu(s);
418         *blocksize = 1024;
419         TRACE("Size is %" PRIu64, *size);
420
421         if (!name) {
422                 if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {
423                         LOG("read failed (flags)");
424                         errno = EINVAL;
425                         return -1;
426                 }
427                 *flags = be32_to_cpup(flags);
428         } else {
429                 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
430                         LOG("read failed (tmp)");
431                         errno = EINVAL;
432                         return -1;
433                 }
434                 *flags |= be32_to_cpu(tmp);
435         }
436         if (read_sync(csock, &buf, 124) != 124) {
437                 LOG("read failed (buf)");
438                 errno = EINVAL;
439                 return -1;
440         }
441         return 0;
442 }
443
444 #ifndef _WIN32
445 int nbd_init(int fd, int csock, off_t size, size_t blocksize)
446 {
447         TRACE("Setting block size to %lu", (unsigned long)blocksize);
448
449         if (ioctl(fd, NBD_SET_BLKSIZE, blocksize) == -1) {
450                 int serrno = errno;
451                 LOG("Failed setting NBD block size");
452                 errno = serrno;
453                 return -1;
454         }
455
456         TRACE("Setting size to %zd block(s)", (size_t)(size / blocksize));
457
458         if (ioctl(fd, NBD_SET_SIZE_BLOCKS, size / blocksize) == -1) {
459                 int serrno = errno;
460                 LOG("Failed setting size (in blocks)");
461                 errno = serrno;
462                 return -1;
463         }
464
465         TRACE("Clearing NBD socket");
466
467         if (ioctl(fd, NBD_CLEAR_SOCK) == -1) {
468                 int serrno = errno;
469                 LOG("Failed clearing NBD socket");
470                 errno = serrno;
471                 return -1;
472         }
473
474         TRACE("Setting NBD socket");
475
476         if (ioctl(fd, NBD_SET_SOCK, csock) == -1) {
477                 int serrno = errno;
478                 LOG("Failed to set NBD socket");
479                 errno = serrno;
480                 return -1;
481         }
482
483         TRACE("Negotiation ended");
484
485         return 0;
486 }
487
488 int nbd_disconnect(int fd)
489 {
490         ioctl(fd, NBD_CLEAR_QUE);
491         ioctl(fd, NBD_DISCONNECT);
492         ioctl(fd, NBD_CLEAR_SOCK);
493         return 0;
494 }
495
496 int nbd_client(int fd)
497 {
498         int ret;
499         int serrno;
500
501         TRACE("Doing NBD loop");
502
503         ret = ioctl(fd, NBD_DO_IT);
504         serrno = errno;
505
506         TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
507
508         TRACE("Clearing NBD queue");
509         ioctl(fd, NBD_CLEAR_QUE);
510
511         TRACE("Clearing NBD socket");
512         ioctl(fd, NBD_CLEAR_SOCK);
513
514         errno = serrno;
515         return ret;
516 }
517 #else
518 int nbd_init(int fd, int csock, off_t size, size_t blocksize)
519 {
520     errno = ENOTSUP;
521     return -1;
522 }
523
524 int nbd_disconnect(int fd)
525 {
526     errno = ENOTSUP;
527     return -1;
528 }
529
530 int nbd_client(int fd)
531 {
532     errno = ENOTSUP;
533     return -1;
534 }
535 #endif
536
537 int nbd_send_request(int csock, struct nbd_request *request)
538 {
539         uint8_t buf[4 + 4 + 8 + 8 + 4];
540
541         cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);
542         cpu_to_be32w((uint32_t*)(buf + 4), request->type);
543         cpu_to_be64w((uint64_t*)(buf + 8), request->handle);
544         cpu_to_be64w((uint64_t*)(buf + 16), request->from);
545         cpu_to_be32w((uint32_t*)(buf + 24), request->len);
546
547         TRACE("Sending request to client");
548
549         if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
550                 LOG("writing to socket failed");
551                 errno = EINVAL;
552                 return -1;
553         }
554         return 0;
555 }
556
557
558 static int nbd_receive_request(int csock, struct nbd_request *request)
559 {
560         uint8_t buf[4 + 4 + 8 + 8 + 4];
561         uint32_t magic;
562
563         if (read_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
564                 LOG("read failed");
565                 errno = EINVAL;
566                 return -1;
567         }
568
569         /* Request
570            [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)
571            [ 4 ..  7]   type    (0 == READ, 1 == WRITE)
572            [ 8 .. 15]   handle
573            [16 .. 23]   from
574            [24 .. 27]   len
575          */
576
577         magic = be32_to_cpup((uint32_t*)buf);
578         request->type  = be32_to_cpup((uint32_t*)(buf + 4));
579         request->handle = be64_to_cpup((uint64_t*)(buf + 8));
580         request->from  = be64_to_cpup((uint64_t*)(buf + 16));
581         request->len   = be32_to_cpup((uint32_t*)(buf + 24));
582
583         TRACE("Got request: "
584               "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
585               magic, request->type, request->from, request->len);
586
587         if (magic != NBD_REQUEST_MAGIC) {
588                 LOG("invalid magic (got 0x%x)", magic);
589                 errno = EINVAL;
590                 return -1;
591         }
592         return 0;
593 }
594
595 int nbd_receive_reply(int csock, struct nbd_reply *reply)
596 {
597         uint8_t buf[NBD_REPLY_SIZE];
598         uint32_t magic;
599
600         memset(buf, 0xAA, sizeof(buf));
601
602         if (read_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
603                 LOG("read failed");
604                 errno = EINVAL;
605                 return -1;
606         }
607
608         /* Reply
609            [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
610            [ 4 ..  7]    error   (0 == no error)
611            [ 7 .. 15]    handle
612          */
613
614         magic = be32_to_cpup((uint32_t*)buf);
615         reply->error  = be32_to_cpup((uint32_t*)(buf + 4));
616         reply->handle = be64_to_cpup((uint64_t*)(buf + 8));
617
618         TRACE("Got reply: "
619               "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",
620               magic, reply->error, reply->handle);
621
622         if (magic != NBD_REPLY_MAGIC) {
623                 LOG("invalid magic (got 0x%x)", magic);
624                 errno = EINVAL;
625                 return -1;
626         }
627         return 0;
628 }
629
630 static int nbd_send_reply(int csock, struct nbd_reply *reply)
631 {
632         uint8_t buf[4 + 4 + 8];
633
634         /* Reply
635            [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
636            [ 4 ..  7]    error   (0 == no error)
637            [ 7 .. 15]    handle
638          */
639         cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
640         cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
641         cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
642
643         TRACE("Sending response to client");
644
645         if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
646                 LOG("writing to socket failed");
647                 errno = EINVAL;
648                 return -1;
649         }
650         return 0;
651 }
652
653 int nbd_trip(BlockDriverState *bs, int csock, off_t size, uint64_t dev_offset,
654              off_t *offset, bool readonly, uint8_t *data, int data_size)
655 {
656         struct nbd_request request;
657         struct nbd_reply reply;
658
659         TRACE("Reading request.");
660
661         if (nbd_receive_request(csock, &request) == -1)
662                 return -1;
663
664         if (request.len + NBD_REPLY_SIZE > data_size) {
665                 LOG("len (%u) is larger than max len (%u)",
666                     request.len + NBD_REPLY_SIZE, data_size);
667                 errno = EINVAL;
668                 return -1;
669         }
670
671         if ((request.from + request.len) < request.from) {
672                 LOG("integer overflow detected! "
673                     "you're probably being attacked");
674                 errno = EINVAL;
675                 return -1;
676         }
677
678         if ((request.from + request.len) > size) {
679                 LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
680                     ", Offset: %" PRIu64 "\n",
681                     request.from, request.len, (uint64_t)size, dev_offset);
682                 LOG("requested operation past EOF--bad client?");
683                 errno = EINVAL;
684                 return -1;
685         }
686
687         TRACE("Decoding type");
688
689         reply.handle = request.handle;
690         reply.error = 0;
691
692         switch (request.type) {
693         case NBD_CMD_READ:
694                 TRACE("Request type is READ");
695
696                 if (bdrv_read(bs, (request.from + dev_offset) / 512,
697                               data + NBD_REPLY_SIZE,
698                               request.len / 512) == -1) {
699                         LOG("reading from file failed");
700                         errno = EINVAL;
701                         return -1;
702                 }
703                 *offset += request.len;
704
705                 TRACE("Read %u byte(s)", request.len);
706
707                 /* Reply
708                    [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
709                    [ 4 ..  7]    error   (0 == no error)
710                    [ 7 .. 15]    handle
711                  */
712
713                 cpu_to_be32w((uint32_t*)data, NBD_REPLY_MAGIC);
714                 cpu_to_be32w((uint32_t*)(data + 4), reply.error);
715                 cpu_to_be64w((uint64_t*)(data + 8), reply.handle);
716
717                 TRACE("Sending data to client");
718
719                 if (write_sync(csock, data,
720                                request.len + NBD_REPLY_SIZE) !=
721                                request.len + NBD_REPLY_SIZE) {
722                         LOG("writing to socket failed");
723                         errno = EINVAL;
724                         return -1;
725                 }
726                 break;
727         case NBD_CMD_WRITE:
728                 TRACE("Request type is WRITE");
729
730                 TRACE("Reading %u byte(s)", request.len);
731
732                 if (read_sync(csock, data, request.len) != request.len) {
733                         LOG("reading from socket failed");
734                         errno = EINVAL;
735                         return -1;
736                 }
737
738                 if (readonly) {
739                         TRACE("Server is read-only, return error");
740                         reply.error = 1;
741                 } else {
742                         TRACE("Writing to device");
743
744                         if (bdrv_write(bs, (request.from + dev_offset) / 512,
745                                        data, request.len / 512) == -1) {
746                                 LOG("writing to file failed");
747                                 errno = EINVAL;
748                                 return -1;
749                         }
750
751                         *offset += request.len;
752                 }
753
754                 if (nbd_send_reply(csock, &reply) == -1)
755                         return -1;
756                 break;
757         case NBD_CMD_DISC:
758                 TRACE("Request type is DISCONNECT");
759                 errno = 0;
760                 return 1;
761         default:
762                 LOG("invalid request type (%u) received", request.type);
763                 errno = EINVAL;
764                 return -1;
765         }
766
767         TRACE("Request/Reply complete");
768
769         return 0;
770 }