1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19#include "qemu-common.h"
20#include "block/block.h"
21#include "block/nbd.h"
22
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>
34#include <pthread.h>
35
36#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
37#define QEMU_NBD_OPT_CACHE 1
38#define QEMU_NBD_OPT_AIO 2
39
40static NBDExport *exp;
41static int verbose;
42static char *srcpath;
43static char *sockpath;
44static int persistent = 0;
45static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
46static int shared = 1;
47static int nb_fds;
48
49static void usage(const char *name)
50{
51 (printf) (
52"Usage: %s [OPTIONS] FILE\n"
53"QEMU Disk Network Block Device Server\n"
54"\n"
55" -h, --help display this help and exit\n"
56" -V, --version output version information and exit\n"
57"\n"
58"Connection properties:\n"
59" -p, --port=PORT port to listen on (default `%d')\n"
60" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
61" -k, --socket=PATH path to the unix socket\n"
62" (default '"SOCKET_PATH"')\n"
63" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
64" -t, --persistent don't exit on the last connection\n"
65" -v, --verbose display extra debugging information\n"
66"\n"
67"Exposing part of the image:\n"
68" -o, --offset=OFFSET offset into the image\n"
69" -P, --partition=NUM only expose partition NUM\n"
70"\n"
71#ifdef __linux__
72"Kernel NBD client support:\n"
73" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
74" -d, --disconnect disconnect the specified device\n"
75"\n"
76#endif
77"\n"
78"Block device options:\n"
79" -r, --read-only export read-only\n"
80" -s, --snapshot use snapshot file\n"
81" -n, --nocache disable host cache\n"
82" --cache=MODE set cache mode (none, writeback, ...)\n"
83#ifdef CONFIG_LINUX_AIO
84" --aio=MODE set AIO mode (native or threads)\n"
85#endif
86"\n"
87"Report bugs to <qemu-devel@nongnu.org>\n"
88 , name, NBD_DEFAULT_PORT, "DEVICE");
89}
90
91static void version(const char *name)
92{
93 printf(
94"%s version 0.0.1\n"
95"Written by Anthony Liguori.\n"
96"\n"
97"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
98"This is free software; see the source for copying conditions. There is NO\n"
99"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
100 , name);
101}
102
103struct partition_record
104{
105 uint8_t bootable;
106 uint8_t start_head;
107 uint32_t start_cylinder;
108 uint8_t start_sector;
109 uint8_t system;
110 uint8_t end_head;
111 uint8_t end_cylinder;
112 uint8_t end_sector;
113 uint32_t start_sector_abs;
114 uint32_t nb_sectors_abs;
115};
116
117static void read_partition(uint8_t *p, struct partition_record *r)
118{
119 r->bootable = p[0];
120 r->start_head = p[1];
121 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
122 r->start_sector = p[2] & 0x3f;
123 r->system = p[4];
124 r->end_head = p[5];
125 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
126 r->end_sector = p[6] & 0x3f;
127 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
128 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
129}
130
131static int find_partition(BlockDriverState *bs, int partition,
132 off_t *offset, off_t *size)
133{
134 struct partition_record mbr[4];
135 uint8_t data[512];
136 int i;
137 int ext_partnum = 4;
138 int ret;
139
140 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
141 errno = -ret;
142 err(EXIT_FAILURE, "error while reading");
143 }
144
145 if (data[510] != 0x55 || data[511] != 0xaa) {
146 return -EINVAL;
147 }
148
149 for (i = 0; i < 4; i++) {
150 read_partition(&data[446 + 16 * i], &mbr[i]);
151
152 if (!mbr[i].nb_sectors_abs)
153 continue;
154
155 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
156 struct partition_record ext[4];
157 uint8_t data1[512];
158 int j;
159
160 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
161 errno = -ret;
162 err(EXIT_FAILURE, "error while reading");
163 }
164
165 for (j = 0; j < 4; j++) {
166 read_partition(&data1[446 + 16 * j], &ext[j]);
167 if (!ext[j].nb_sectors_abs)
168 continue;
169
170 if ((ext_partnum + j + 1) == partition) {
171 *offset = (uint64_t)ext[j].start_sector_abs << 9;
172 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
173 return 0;
174 }
175 }
176 ext_partnum += 4;
177 } else if ((i + 1) == partition) {
178 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
179 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
180 return 0;
181 }
182 }
183
184 return -ENOENT;
185}
186
187static void termsig_handler(int signum)
188{
189 state = TERMINATE;
190 qemu_notify_event();
191}
192
193static void *show_parts(void *arg)
194{
195 char *device = arg;
196 int nbd;
197
198
199
200
201
202
203 nbd = open(device, O_RDWR);
204 if (nbd >= 0) {
205 close(nbd);
206 }
207 return NULL;
208}
209
210static void *nbd_client_thread(void *arg)
211{
212 char *device = arg;
213 off_t size;
214 size_t blocksize;
215 uint32_t nbdflags;
216 int fd, sock;
217 int ret;
218 pthread_t show_parts_thread;
219
220 sock = unix_socket_outgoing(sockpath);
221 if (sock < 0) {
222 goto out;
223 }
224
225 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
226 &size, &blocksize);
227 if (ret < 0) {
228 goto out;
229 }
230
231 fd = open(device, O_RDWR);
232 if (fd < 0) {
233
234 fprintf(stderr, "Failed to open %s: %m", device);
235 goto out;
236 }
237
238 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
239 if (ret < 0) {
240 goto out;
241 }
242
243
244 pthread_create(&show_parts_thread, NULL, show_parts, device);
245
246 if (verbose) {
247 fprintf(stderr, "NBD device %s is now connected to %s\n",
248 device, srcpath);
249 } else {
250
251 dup2(STDOUT_FILENO, STDERR_FILENO);
252 }
253
254 ret = nbd_client(fd);
255 if (ret) {
256 goto out;
257 }
258 close(fd);
259 kill(getpid(), SIGTERM);
260 return (void *) EXIT_SUCCESS;
261
262out:
263 kill(getpid(), SIGTERM);
264 return (void *) EXIT_FAILURE;
265}
266
267static int nbd_can_accept(void *opaque)
268{
269 return nb_fds < shared;
270}
271
272static void nbd_export_closed(NBDExport *exp)
273{
274 assert(state == TERMINATING);
275 state = TERMINATED;
276}
277
278static void nbd_client_closed(NBDClient *client)
279{
280 nb_fds--;
281 if (nb_fds == 0 && !persistent && state == RUNNING) {
282 state = TERMINATE;
283 }
284 qemu_notify_event();
285 nbd_client_put(client);
286}
287
288static void nbd_accept(void *opaque)
289{
290 int server_fd = (uintptr_t) opaque;
291 struct sockaddr_in addr;
292 socklen_t addr_len = sizeof(addr);
293
294 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
295 if (state >= TERMINATE) {
296 close(fd);
297 return;
298 }
299
300 if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {
301 nb_fds++;
302 }
303}
304
305int main(int argc, char **argv)
306{
307 BlockDriverState *bs;
308 BlockDriver *drv;
309 off_t dev_offset = 0;
310 uint32_t nbdflags = 0;
311 bool disconnect = false;
312 const char *bindto = "0.0.0.0";
313 char *device = NULL;
314 int port = NBD_DEFAULT_PORT;
315 off_t fd_size;
316 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:t";
317 struct option lopt[] = {
318 { "help", 0, NULL, 'h' },
319 { "version", 0, NULL, 'V' },
320 { "bind", 1, NULL, 'b' },
321 { "port", 1, NULL, 'p' },
322 { "socket", 1, NULL, 'k' },
323 { "offset", 1, NULL, 'o' },
324 { "read-only", 0, NULL, 'r' },
325 { "partition", 1, NULL, 'P' },
326 { "connect", 1, NULL, 'c' },
327 { "disconnect", 0, NULL, 'd' },
328 { "snapshot", 0, NULL, 's' },
329 { "nocache", 0, NULL, 'n' },
330 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
331#ifdef CONFIG_LINUX_AIO
332 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
333#endif
334 { "shared", 1, NULL, 'e' },
335 { "format", 1, NULL, 'f' },
336 { "persistent", 0, NULL, 't' },
337 { "verbose", 0, NULL, 'v' },
338 { NULL, 0, NULL, 0 }
339 };
340 int ch;
341 int opt_ind = 0;
342 int li;
343 char *end;
344 int flags = BDRV_O_RDWR;
345 int partition = -1;
346 int ret;
347 int fd;
348 bool seen_cache = false;
349#ifdef CONFIG_LINUX_AIO
350 bool seen_aio = false;
351#endif
352 pthread_t client_thread;
353 const char *fmt = NULL;
354
355
356
357
358 struct sigaction sa_sigterm;
359 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
360 sa_sigterm.sa_handler = termsig_handler;
361 sigaction(SIGTERM, &sa_sigterm, NULL);
362
363 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
364 switch (ch) {
365 case 's':
366 flags |= BDRV_O_SNAPSHOT;
367 break;
368 case 'n':
369 optarg = (char *) "none";
370
371 case QEMU_NBD_OPT_CACHE:
372 if (seen_cache) {
373 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
374 }
375 seen_cache = true;
376 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
377 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
378 }
379 break;
380#ifdef CONFIG_LINUX_AIO
381 case QEMU_NBD_OPT_AIO:
382 if (seen_aio) {
383 errx(EXIT_FAILURE, "--aio can only be specified once");
384 }
385 seen_aio = true;
386 if (!strcmp(optarg, "native")) {
387 flags |= BDRV_O_NATIVE_AIO;
388 } else if (!strcmp(optarg, "threads")) {
389
390 } else {
391 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
392 }
393 break;
394#endif
395 case 'b':
396 bindto = optarg;
397 break;
398 case 'p':
399 li = strtol(optarg, &end, 0);
400 if (*end) {
401 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
402 }
403 if (li < 1 || li > 65535) {
404 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
405 }
406 port = (uint16_t)li;
407 break;
408 case 'o':
409 dev_offset = strtoll (optarg, &end, 0);
410 if (*end) {
411 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
412 }
413 if (dev_offset < 0) {
414 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
415 }
416 break;
417 case 'r':
418 nbdflags |= NBD_FLAG_READ_ONLY;
419 flags &= ~BDRV_O_RDWR;
420 break;
421 case 'P':
422 partition = strtol(optarg, &end, 0);
423 if (*end)
424 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
425 if (partition < 1 || partition > 8)
426 errx(EXIT_FAILURE, "Invalid partition %d", partition);
427 break;
428 case 'k':
429 sockpath = optarg;
430 if (sockpath[0] != '/')
431 errx(EXIT_FAILURE, "socket path must be absolute\n");
432 break;
433 case 'd':
434 disconnect = true;
435 break;
436 case 'c':
437 device = optarg;
438 break;
439 case 'e':
440 shared = strtol(optarg, &end, 0);
441 if (*end) {
442 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
443 }
444 if (shared < 1) {
445 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
446 }
447 break;
448 case 'f':
449 fmt = optarg;
450 break;
451 case 't':
452 persistent = 1;
453 break;
454 case 'v':
455 verbose = 1;
456 break;
457 case 'V':
458 version(argv[0]);
459 exit(0);
460 break;
461 case 'h':
462 usage(argv[0]);
463 exit(0);
464 break;
465 case '?':
466 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
467 argv[0]);
468 }
469 }
470
471 if ((argc - optind) != 1) {
472 errx(EXIT_FAILURE, "Invalid number of argument.\n"
473 "Try `%s --help' for more information.",
474 argv[0]);
475 }
476
477 if (disconnect) {
478 fd = open(argv[optind], O_RDWR);
479 if (fd < 0) {
480 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
481 }
482 nbd_disconnect(fd);
483
484 close(fd);
485
486 printf("%s disconnected\n", argv[optind]);
487
488 return 0;
489 }
490
491 if (device && !verbose) {
492 int stderr_fd[2];
493 pid_t pid;
494 int ret;
495
496 if (qemu_pipe(stderr_fd) < 0) {
497 err(EXIT_FAILURE, "Error setting up communication pipe");
498 }
499
500
501
502
503 pid = fork();
504 if (pid == 0) {
505 close(stderr_fd[0]);
506 ret = qemu_daemon(1, 0);
507
508
509 dup2(stderr_fd[1], STDERR_FILENO);
510 if (ret < 0) {
511 err(EXIT_FAILURE, "Failed to daemonize");
512 }
513
514
515 close(stderr_fd[1]);
516 } else {
517 bool errors = false;
518 char *buf;
519
520
521
522
523 close(stderr_fd[1]);
524 buf = g_malloc(1024);
525 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
526 errors = true;
527 ret = qemu_write_full(STDERR_FILENO, buf, ret);
528 if (ret < 0) {
529 exit(EXIT_FAILURE);
530 }
531 }
532 if (ret < 0) {
533 err(EXIT_FAILURE, "Cannot read from daemon");
534 }
535
536
537
538
539 exit(errors);
540 }
541 }
542
543 if (device != NULL && sockpath == NULL) {
544 sockpath = g_malloc(128);
545 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
546 }
547
548 qemu_init_main_loop();
549 bdrv_init();
550 atexit(bdrv_close_all);
551
552 if (fmt) {
553 drv = bdrv_find_format(fmt);
554 if (!drv) {
555 errx(EXIT_FAILURE, "Unknown file format '%s'", fmt);
556 }
557 } else {
558 drv = NULL;
559 }
560
561 bs = bdrv_new("hda");
562 srcpath = argv[optind];
563 ret = bdrv_open(bs, srcpath, flags, drv);
564 if (ret < 0) {
565 errno = -ret;
566 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
567 }
568
569 fd_size = bdrv_getlength(bs);
570
571 if (partition != -1) {
572 ret = find_partition(bs, partition, &dev_offset, &fd_size);
573 if (ret < 0) {
574 errno = -ret;
575 err(EXIT_FAILURE, "Could not find partition %d", partition);
576 }
577 }
578
579 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags, nbd_export_closed);
580
581 if (sockpath) {
582 fd = unix_socket_incoming(sockpath);
583 } else {
584 fd = tcp_socket_incoming(bindto, port);
585 }
586
587 if (fd < 0) {
588 return 1;
589 }
590
591 if (device) {
592 int ret;
593
594 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
595 if (ret != 0) {
596 errx(EXIT_FAILURE, "Failed to create client thread: %s",
597 strerror(ret));
598 }
599 } else {
600
601 memset(&client_thread, 0, sizeof(client_thread));
602 }
603
604 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
605 (void *)(uintptr_t)fd);
606
607
608
609 if (chdir("/") < 0) {
610 err(EXIT_FAILURE, "Could not chdir to root directory");
611 }
612
613 state = RUNNING;
614 do {
615 main_loop_wait(false);
616 if (state == TERMINATE) {
617 state = TERMINATING;
618 nbd_export_close(exp);
619 nbd_export_put(exp);
620 exp = NULL;
621 }
622 } while (state != TERMINATED);
623
624 bdrv_close(bs);
625 if (sockpath) {
626 unlink(sockpath);
627 }
628
629 if (device) {
630 void *ret;
631 pthread_join(client_thread, &ret);
632 exit(ret != NULL);
633 } else {
634 exit(EXIT_SUCCESS);
635 }
636}
637