Allow to share a disk image via nbd, by Laurent Vivier.
[qemu] / qemu-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, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #include <qemu-common.h>
21 #include "block_int.h"
22 #include "nbd.h"
23
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <getopt.h>
27 #include <err.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
32 #include <arpa/inet.h>
33 #include <signal.h>
34
35 #define SOCKET_PATH    "/var/lock/qemu-nbd-%s"
36
37 #define NBD_BUFFER_SIZE (1024*1024)
38
39 int verbose;
40
41 static void usage(const char *name)
42 {
43     printf(
44 "Usage: %s [OPTIONS] FILE\n"
45 "QEMU Disk Network Block Device Server\n"
46 "\n"
47 "  -p, --port=PORT      port to listen on (default `1024')\n"
48 "  -o, --offset=OFFSET  offset into the image\n"
49 "  -b, --bind=IFACE     interface to bind to (default `0.0.0.0')\n"
50 "  -k, --socket=PATH    path to the unix socket\n"
51 "                       (default '"SOCKET_PATH"')\n"
52 "  -r, --read-only      export read-only\n"
53 "  -P, --partition=NUM  only expose partition NUM\n"
54 "  -s, --snapshot       use snapshot file\n"
55 "  -n, --nocache        disable host cache\n"
56 "  -c, --connect=DEV    connect FILE to the local NBD device DEV\n"
57 "  -d, --disconnect     disconnect the specified device\n"
58 "  -e, --shared=NUM     device can be shared by NUM clients (default '1')\n"
59 "  -v, --verbose        display extra debugging information\n"
60 "  -h, --help           display this help and exit\n"
61 "  -V, --version        output version information and exit\n"
62 "\n"
63 "Report bugs to <anthony@codemonkey.ws>\n"
64     , name, "DEVICE");
65 }
66
67 static void version(const char *name)
68 {
69     printf(
70 "qemu-nbd version 0.0.1\n"
71 "Written by Anthony Liguori.\n"
72 "\n"
73 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
74 "This is free software; see the source for copying conditions.  There is NO\n"
75 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
76     );
77 }
78
79 struct partition_record
80 {
81     uint8_t bootable;
82     uint8_t start_head;
83     uint32_t start_cylinder;
84     uint8_t start_sector;
85     uint8_t system;
86     uint8_t end_head;
87     uint8_t end_cylinder;
88     uint8_t end_sector;
89     uint32_t start_sector_abs;
90     uint32_t nb_sectors_abs;
91 };
92
93 static void read_partition(uint8_t *p, struct partition_record *r)
94 {
95     r->bootable = p[0];
96     r->start_head = p[1];
97     r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
98     r->start_sector = p[2] & 0x3f;
99     r->system = p[4];
100     r->end_head = p[5];
101     r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
102     r->end_sector = p[6] & 0x3f;
103     r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
104     r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
105 }
106
107 static int find_partition(BlockDriverState *bs, int partition,
108                           off_t *offset, off_t *size)
109 {
110     struct partition_record mbr[4];
111     uint8_t data[512];
112     int i;
113     int ext_partnum = 4;
114
115     if (bdrv_read(bs, 0, data, 1))
116         errx(EINVAL, "error while reading");
117
118     if (data[510] != 0x55 || data[511] != 0xaa) {
119         errno = -EINVAL;
120         return -1;
121     }
122
123     for (i = 0; i < 4; i++) {
124         read_partition(&data[446 + 16 * i], &mbr[i]);
125
126         if (!mbr[i].nb_sectors_abs)
127             continue;
128
129         if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
130             struct partition_record ext[4];
131             uint8_t data1[512];
132             int j;
133
134             if (bdrv_read(bs, mbr[i].start_sector_abs, data1, 1))
135                 errx(EINVAL, "error while reading");
136
137             for (j = 0; j < 4; j++) {
138                 read_partition(&data1[446 + 16 * j], &ext[j]);
139                 if (!ext[j].nb_sectors_abs)
140                     continue;
141
142                 if ((ext_partnum + j + 1) == partition) {
143                     *offset = (uint64_t)ext[j].start_sector_abs << 9;
144                     *size = (uint64_t)ext[j].nb_sectors_abs << 9;
145                     return 0;
146                 }
147             }
148             ext_partnum += 4;
149         } else if ((i + 1) == partition) {
150             *offset = (uint64_t)mbr[i].start_sector_abs << 9;
151             *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
152             return 0;
153         }
154     }
155
156     errno = -ENOENT;
157     return -1;
158 }
159
160 static void show_parts(const char *device)
161 {
162     if (fork() == 0) {
163         int nbd;
164
165         /* linux just needs an open() to trigger
166          * the partition table update
167          * but remember to load the module with max_part != 0 :
168          *     modprobe nbd max_part=63
169          */
170         nbd = open(device, O_RDWR);
171         if (nbd != -1)
172               close(nbd);
173         exit(0);
174     }
175 }
176
177 int main(int argc, char **argv)
178 {
179     BlockDriverState *bs;
180     off_t dev_offset = 0;
181     off_t offset = 0;
182     bool readonly = false;
183     bool disconnect = false;
184     const char *bindto = "0.0.0.0";
185     int port = 1024;
186     struct sockaddr_in addr;
187     socklen_t addr_len = sizeof(addr);
188     off_t fd_size;
189     char *device = NULL;
190     char *socket = NULL;
191     char sockpath[128];
192     const char *sopt = "hVbo:p:rsnP:c:dvk:e:";
193     struct option lopt[] = {
194         { "help", 0, 0, 'h' },
195         { "version", 0, 0, 'V' },
196         { "bind", 1, 0, 'b' },
197         { "port", 1, 0, 'p' },
198         { "socket", 1, 0, 'k' },
199         { "offset", 1, 0, 'o' },
200         { "read-only", 0, 0, 'r' },
201         { "partition", 1, 0, 'P' },
202         { "connect", 1, 0, 'c' },
203         { "disconnect", 0, 0, 'd' },
204         { "snapshot", 0, 0, 's' },
205         { "nocache", 0, 0, 'n' },
206         { "shared", 1, 0, 'e' },
207         { "verbose", 0, 0, 'v' },
208         { NULL, 0, 0, 0 }
209     };
210     int ch;
211     int opt_ind = 0;
212     int li;
213     char *end;
214     int flags = 0;
215     int partition = -1;
216     int ret;
217     int shared = 1;
218     uint8_t *data;
219     fd_set fds;
220     int *sharing_fds;
221     int fd;
222     int i;
223     int nb_fds = 0;
224     int max_fd;
225
226     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
227         switch (ch) {
228         case 's':
229             flags |= BDRV_O_SNAPSHOT;
230             break;
231         case 'n':
232             flags |= BDRV_O_DIRECT;
233             break;
234         case 'b':
235             bindto = optarg;
236             break;
237         case 'p':
238             li = strtol(optarg, &end, 0);
239             if (*end) {
240                 errx(EINVAL, "Invalid port `%s'", optarg);
241             }
242             if (li < 1 || li > 65535) {
243                 errx(EINVAL, "Port out of range `%s'", optarg);
244             }
245             port = (uint16_t)li;
246             break;
247         case 'o':
248                 dev_offset = strtoll (optarg, &end, 0);
249             if (*end) {
250                 errx(EINVAL, "Invalid offset `%s'", optarg);
251             }
252             if (dev_offset < 0) {
253                 errx(EINVAL, "Offset must be positive `%s'", optarg);
254             }
255             break;
256         case 'r':
257             readonly = true;
258             break;
259         case 'P':
260             partition = strtol(optarg, &end, 0);
261             if (*end)
262                 errx(EINVAL, "Invalid partition `%s'", optarg);
263             if (partition < 1 || partition > 8)
264                 errx(EINVAL, "Invalid partition %d", partition);
265             break;
266         case 'k':
267             socket = optarg;
268             if (socket[0] != '/')
269                 errx(EINVAL, "socket path must be absolute\n");
270             break;
271         case 'd':
272             disconnect = true;
273             break;
274         case 'c':
275             device = optarg;
276             break;
277         case 'e':
278             shared = strtol(optarg, &end, 0);
279             if (*end) {
280                 errx(EINVAL, "Invalid shared device number '%s'", optarg);
281             }
282             if (shared < 1) {
283                 errx(EINVAL, "Shared device number must be greater than 0\n");
284             }
285             break;
286         case 'v':
287             verbose = 1;
288             break;
289         case 'V':
290             version(argv[0]);
291             exit(0);
292             break;
293         case 'h':
294             usage(argv[0]);
295             exit(0);
296             break;
297         case '?':
298             errx(EINVAL, "Try `%s --help' for more information.",
299                  argv[0]);
300         }
301     }
302
303     if ((argc - optind) != 1) {
304         errx(EINVAL, "Invalid number of argument.\n"
305              "Try `%s --help' for more information.",
306              argv[0]);
307     }
308
309     if (disconnect) {
310         fd = open(argv[optind], O_RDWR);
311         if (fd == -1)
312             errx(errno, "Cannot open %s", argv[optind]);
313
314         nbd_disconnect(fd);
315
316         close(fd);
317
318         printf("%s disconnected\n", argv[optind]);
319
320         return 0;
321     }
322
323     bdrv_init();
324
325     bs = bdrv_new("hda");
326     if (bs == NULL)
327         return 1;
328
329     if (bdrv_open(bs, argv[optind], flags) == -1)
330         return 1;
331
332     fd_size = bs->total_sectors * 512;
333
334     if (partition != -1 &&
335         find_partition(bs, partition, &dev_offset, &fd_size))
336         errx(errno, "Could not find partition %d", partition);
337
338     if (device) {
339         pid_t pid;
340         int sock;
341
342         if (!verbose)
343             daemon(0, 0);       /* detach client and server */
344
345         if (socket == NULL) {
346             sprintf(sockpath, SOCKET_PATH, basename(device));
347             socket = sockpath;
348         }
349
350         pid = fork();
351         if (pid < 0)
352             return 1;
353         if (pid != 0) {
354             off_t size;
355             size_t blocksize;
356
357             ret = 0;
358             bdrv_close(bs);
359
360             do {
361                 sock = unix_socket_outgoing(socket);
362                 if (sock == -1) {
363                     if (errno != ENOENT && errno != ECONNREFUSED)
364                         goto out;
365                     sleep(1);   /* wait children */
366                 }
367             } while (sock == -1);
368
369             fd = open(device, O_RDWR);
370             if (fd == -1) {
371                 ret = 1;
372                 goto out;
373             }
374
375             ret = nbd_receive_negotiate(sock, &size, &blocksize);
376             if (ret == -1) {
377                 ret = 1;
378                 goto out;
379             }
380
381             ret = nbd_init(fd, sock, size, blocksize);
382             if (ret == -1) {
383                 ret = 1;
384                 goto out;
385             }
386
387             printf("NBD device %s is now connected to file %s\n",
388                     device, argv[optind]);
389
390             /* update partition table */
391
392             show_parts(device);
393
394             nbd_client(fd, sock);
395             close(fd);
396  out:
397             kill(pid, SIGTERM);
398             unlink(socket);
399
400             return ret;
401         }
402         /* children */
403     }
404
405     sharing_fds = qemu_malloc((shared + 1) * sizeof(int));
406     if (sharing_fds == NULL)
407         errx(ENOMEM, "Cannot allocate sharing fds");
408
409     if (socket) {
410         sharing_fds[0] = unix_socket_incoming(socket);
411     } else {
412         sharing_fds[0] = tcp_socket_incoming(bindto, port);
413     }
414
415     if (sharing_fds[0] == -1)
416         return 1;
417     max_fd = sharing_fds[0];
418     nb_fds++;
419
420     data = qemu_memalign(512, NBD_BUFFER_SIZE);
421     if (data == NULL)
422         errx(ENOMEM, "Cannot allocate data buffer");
423
424     do {
425
426         FD_ZERO(&fds);
427         for (i = 0; i < nb_fds; i++)
428             FD_SET(sharing_fds[i], &fds);
429
430         ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
431         if (ret == -1)
432             break;
433
434         if (FD_ISSET(sharing_fds[0], &fds))
435             ret--;
436         for (i = 1; i < nb_fds && ret; i++) {
437             if (FD_ISSET(sharing_fds[i], &fds)) {
438                 if (nbd_trip(bs, sharing_fds[i], fd_size, dev_offset,
439                     &offset, readonly, data, NBD_BUFFER_SIZE) != 0) {
440                     close(sharing_fds[i]);
441                     nb_fds--;
442                     sharing_fds[i] = sharing_fds[nb_fds];
443                     i--;
444                 }
445                 ret--;
446             }
447         }
448         /* new connection ? */
449         if (FD_ISSET(sharing_fds[0], &fds)) {
450             if (nb_fds < shared + 1) {
451                 sharing_fds[nb_fds] = accept(sharing_fds[0],
452                                              (struct sockaddr *)&addr,
453                                              &addr_len);
454                 if (sharing_fds[nb_fds] != -1 &&
455                     nbd_negotiate(bs, sharing_fds[nb_fds], fd_size) != -1) {
456                         if (sharing_fds[nb_fds] > max_fd)
457                             max_fd = sharing_fds[nb_fds];
458                         nb_fds++;
459                 }
460             }
461         }
462     } while (nb_fds > 1);
463     qemu_free(data);
464
465     close(sharing_fds[0]);
466     bdrv_close(bs);
467     qemu_free(sharing_fds);
468     if (socket)
469         unlink(socket);
470
471     return 0;
472 }