Merge remote-tracking branch 'kwolf/for-anthony' into staging
[qemu.git] / qemu-nbd.c
blobd8d3e15a843acd7852a7b8b502ac37abe85d4a54
1 /*
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 * Network Block Device
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.
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.
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/>.
19 #include "qemu-common.h"
20 #include "block_int.h"
21 #include "nbd.h"
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <getopt.h>
26 #include <err.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <netinet/tcp.h>
31 #include <arpa/inet.h>
32 #include <signal.h>
33 #include <libgen.h>
35 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
37 #define NBD_BUFFER_SIZE (1024*1024)
39 static int verbose;
41 static void usage(const char *name)
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 `%d')\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 " -t, --persistent don't exit on the last connection\n"
60 " -v, --verbose display extra debugging information\n"
61 " -h, --help display this help and exit\n"
62 " -V, --version output version information and exit\n"
63 "\n"
64 "Report bugs to <anthony@codemonkey.ws>\n"
65 , name, NBD_DEFAULT_PORT, "DEVICE");
68 static void version(const char *name)
70 printf(
71 "%s version 0.0.1\n"
72 "Written by Anthony Liguori.\n"
73 "\n"
74 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
75 "This is free software; see the source for copying conditions. There is NO\n"
76 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
77 , name);
80 struct partition_record
82 uint8_t bootable;
83 uint8_t start_head;
84 uint32_t start_cylinder;
85 uint8_t start_sector;
86 uint8_t system;
87 uint8_t end_head;
88 uint8_t end_cylinder;
89 uint8_t end_sector;
90 uint32_t start_sector_abs;
91 uint32_t nb_sectors_abs;
94 static void read_partition(uint8_t *p, struct partition_record *r)
96 r->bootable = p[0];
97 r->start_head = p[1];
98 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
99 r->start_sector = p[2] & 0x3f;
100 r->system = p[4];
101 r->end_head = p[5];
102 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
103 r->end_sector = p[6] & 0x3f;
104 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
105 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
108 static int find_partition(BlockDriverState *bs, int partition,
109 off_t *offset, off_t *size)
111 struct partition_record mbr[4];
112 uint8_t data[512];
113 int i;
114 int ext_partnum = 4;
115 int ret;
117 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
118 errno = -ret;
119 err(EXIT_FAILURE, "error while reading");
122 if (data[510] != 0x55 || data[511] != 0xaa) {
123 errno = -EINVAL;
124 return -1;
127 for (i = 0; i < 4; i++) {
128 read_partition(&data[446 + 16 * i], &mbr[i]);
130 if (!mbr[i].nb_sectors_abs)
131 continue;
133 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
134 struct partition_record ext[4];
135 uint8_t data1[512];
136 int j;
138 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
139 errno = -ret;
140 err(EXIT_FAILURE, "error while reading");
143 for (j = 0; j < 4; j++) {
144 read_partition(&data1[446 + 16 * j], &ext[j]);
145 if (!ext[j].nb_sectors_abs)
146 continue;
148 if ((ext_partnum + j + 1) == partition) {
149 *offset = (uint64_t)ext[j].start_sector_abs << 9;
150 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
151 return 0;
154 ext_partnum += 4;
155 } else if ((i + 1) == partition) {
156 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
157 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
158 return 0;
162 errno = -ENOENT;
163 return -1;
166 static void show_parts(const char *device)
168 if (fork() == 0) {
169 int nbd;
171 /* linux just needs an open() to trigger
172 * the partition table update
173 * but remember to load the module with max_part != 0 :
174 * modprobe nbd max_part=63
176 nbd = open(device, O_RDWR);
177 if (nbd != -1)
178 close(nbd);
179 exit(0);
183 int main(int argc, char **argv)
185 BlockDriverState *bs;
186 off_t dev_offset = 0;
187 off_t offset = 0;
188 uint32_t nbdflags = 0;
189 bool disconnect = false;
190 const char *bindto = "0.0.0.0";
191 int port = NBD_DEFAULT_PORT;
192 struct sockaddr_in addr;
193 socklen_t addr_len = sizeof(addr);
194 off_t fd_size;
195 char *device = NULL;
196 char *socket = NULL;
197 char sockpath[128];
198 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
199 struct option lopt[] = {
200 { "help", 0, NULL, 'h' },
201 { "version", 0, NULL, 'V' },
202 { "bind", 1, NULL, 'b' },
203 { "port", 1, NULL, 'p' },
204 { "socket", 1, NULL, 'k' },
205 { "offset", 1, NULL, 'o' },
206 { "read-only", 0, NULL, 'r' },
207 { "partition", 1, NULL, 'P' },
208 { "connect", 1, NULL, 'c' },
209 { "disconnect", 0, NULL, 'd' },
210 { "snapshot", 0, NULL, 's' },
211 { "nocache", 0, NULL, 'n' },
212 { "shared", 1, NULL, 'e' },
213 { "persistent", 0, NULL, 't' },
214 { "verbose", 0, NULL, 'v' },
215 { NULL, 0, NULL, 0 }
217 int ch;
218 int opt_ind = 0;
219 int li;
220 char *end;
221 int flags = BDRV_O_RDWR;
222 int partition = -1;
223 int ret;
224 int shared = 1;
225 uint8_t *data;
226 fd_set fds;
227 int *sharing_fds;
228 int fd;
229 int i;
230 int nb_fds = 0;
231 int max_fd;
232 int persistent = 0;
234 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
235 switch (ch) {
236 case 's':
237 flags |= BDRV_O_SNAPSHOT;
238 break;
239 case 'n':
240 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
241 break;
242 case 'b':
243 bindto = optarg;
244 break;
245 case 'p':
246 li = strtol(optarg, &end, 0);
247 if (*end) {
248 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
250 if (li < 1 || li > 65535) {
251 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
253 port = (uint16_t)li;
254 break;
255 case 'o':
256 dev_offset = strtoll (optarg, &end, 0);
257 if (*end) {
258 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
260 if (dev_offset < 0) {
261 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
263 break;
264 case 'r':
265 nbdflags |= NBD_FLAG_READ_ONLY;
266 flags &= ~BDRV_O_RDWR;
267 break;
268 case 'P':
269 partition = strtol(optarg, &end, 0);
270 if (*end)
271 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
272 if (partition < 1 || partition > 8)
273 errx(EXIT_FAILURE, "Invalid partition %d", partition);
274 break;
275 case 'k':
276 socket = optarg;
277 if (socket[0] != '/')
278 errx(EXIT_FAILURE, "socket path must be absolute\n");
279 break;
280 case 'd':
281 disconnect = true;
282 break;
283 case 'c':
284 device = optarg;
285 break;
286 case 'e':
287 shared = strtol(optarg, &end, 0);
288 if (*end) {
289 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
291 if (shared < 1) {
292 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
294 break;
295 case 't':
296 persistent = 1;
297 break;
298 case 'v':
299 verbose = 1;
300 break;
301 case 'V':
302 version(argv[0]);
303 exit(0);
304 break;
305 case 'h':
306 usage(argv[0]);
307 exit(0);
308 break;
309 case '?':
310 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
311 argv[0]);
315 if ((argc - optind) != 1) {
316 errx(EXIT_FAILURE, "Invalid number of argument.\n"
317 "Try `%s --help' for more information.",
318 argv[0]);
321 if (disconnect) {
322 fd = open(argv[optind], O_RDWR);
323 if (fd == -1)
324 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
326 nbd_disconnect(fd);
328 close(fd);
330 printf("%s disconnected\n", argv[optind]);
332 return 0;
335 bdrv_init();
337 bs = bdrv_new("hda");
339 if ((ret = bdrv_open(bs, argv[optind], flags, NULL)) < 0) {
340 errno = -ret;
341 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
344 fd_size = bs->total_sectors * 512;
346 if (partition != -1 &&
347 find_partition(bs, partition, &dev_offset, &fd_size))
348 err(EXIT_FAILURE, "Could not find partition %d", partition);
350 if (device) {
351 pid_t pid;
352 int sock;
354 /* want to fail before daemonizing */
355 if (access(device, R_OK|W_OK) == -1) {
356 err(EXIT_FAILURE, "Could not access '%s'", device);
359 if (!verbose) {
360 /* detach client and server */
361 if (qemu_daemon(0, 0) == -1) {
362 err(EXIT_FAILURE, "Failed to daemonize");
366 if (socket == NULL) {
367 snprintf(sockpath, sizeof(sockpath), SOCKET_PATH,
368 basename(device));
369 socket = sockpath;
372 pid = fork();
373 if (pid < 0)
374 return 1;
375 if (pid != 0) {
376 off_t size;
377 size_t blocksize;
379 ret = 0;
380 bdrv_close(bs);
382 do {
383 sock = unix_socket_outgoing(socket);
384 if (sock == -1) {
385 if (errno != ENOENT && errno != ECONNREFUSED) {
386 ret = 1;
387 goto out;
389 sleep(1); /* wait children */
391 } while (sock == -1);
393 fd = open(device, O_RDWR);
394 if (fd == -1) {
395 ret = 1;
396 goto out;
399 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
400 &size, &blocksize);
401 if (ret == -1) {
402 ret = 1;
403 goto out;
406 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
407 if (ret == -1) {
408 ret = 1;
409 goto out;
412 printf("NBD device %s is now connected to file %s\n",
413 device, argv[optind]);
415 /* update partition table */
417 show_parts(device);
419 ret = nbd_client(fd);
420 if (ret) {
421 ret = 1;
423 close(fd);
424 out:
425 kill(pid, SIGTERM);
426 unlink(socket);
428 return ret;
430 /* children */
433 sharing_fds = g_malloc((shared + 1) * sizeof(int));
435 if (socket) {
436 sharing_fds[0] = unix_socket_incoming(socket);
437 } else {
438 sharing_fds[0] = tcp_socket_incoming(bindto, port);
441 if (sharing_fds[0] == -1)
442 return 1;
443 max_fd = sharing_fds[0];
444 nb_fds++;
446 data = qemu_blockalign(bs, NBD_BUFFER_SIZE);
447 if (data == NULL)
448 errx(EXIT_FAILURE, "Cannot allocate data buffer");
450 do {
452 FD_ZERO(&fds);
453 for (i = 0; i < nb_fds; i++)
454 FD_SET(sharing_fds[i], &fds);
456 ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
457 if (ret == -1)
458 break;
460 if (FD_ISSET(sharing_fds[0], &fds))
461 ret--;
462 for (i = 1; i < nb_fds && ret; i++) {
463 if (FD_ISSET(sharing_fds[i], &fds)) {
464 if (nbd_trip(bs, sharing_fds[i], fd_size, dev_offset,
465 &offset, nbdflags, data, NBD_BUFFER_SIZE) != 0) {
466 close(sharing_fds[i]);
467 nb_fds--;
468 sharing_fds[i] = sharing_fds[nb_fds];
469 i--;
471 ret--;
474 /* new connection ? */
475 if (FD_ISSET(sharing_fds[0], &fds)) {
476 if (nb_fds < shared + 1) {
477 sharing_fds[nb_fds] = accept(sharing_fds[0],
478 (struct sockaddr *)&addr,
479 &addr_len);
480 if (sharing_fds[nb_fds] != -1 &&
481 nbd_negotiate(sharing_fds[nb_fds], fd_size, nbdflags) != -1) {
482 if (sharing_fds[nb_fds] > max_fd)
483 max_fd = sharing_fds[nb_fds];
484 nb_fds++;
488 } while (persistent || nb_fds > 1);
489 qemu_vfree(data);
491 close(sharing_fds[0]);
492 bdrv_close(bs);
493 g_free(sharing_fds);
494 if (socket)
495 unlink(socket);
497 return 0;