qemu-nbd: reorganize help message
[qemu-kvm.git] / qemu-nbd.c
blob1c32290a8ee9c6f4366dbbd7beb7948b9c6af0f2
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.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>
34 #include <pthread.h>
36 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
38 static NBDExport *exp;
39 static int verbose;
40 static char *srcpath;
41 static char *sockpath;
42 static bool sigterm_reported;
43 static bool nbd_started;
44 static int shared = 1;
45 static int nb_fds;
47 static void usage(const char *name)
49 (printf) (
50 "Usage: %s [OPTIONS] FILE\n"
51 "QEMU Disk Network Block Device Server\n"
52 "\n"
53 " -h, --help display this help and exit\n"
54 " -V, --version output version information and exit\n"
55 "\n"
56 "Connection properties:\n"
57 " -p, --port=PORT port to listen on (default `%d')\n"
58 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
59 " -k, --socket=PATH path to the unix socket\n"
60 " (default '"SOCKET_PATH"')\n"
61 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
62 " -t, --persistent don't exit on the last connection\n"
63 " -v, --verbose display extra debugging information\n"
64 "\n"
65 "Exposing part of the image:\n"
66 " -o, --offset=OFFSET offset into the image\n"
67 " -P, --partition=NUM only expose partition NUM\n"
68 "\n"
69 #ifdef __linux__
70 "Kernel NBD client support:\n"
71 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
72 " -d, --disconnect disconnect the specified device\n"
73 "\n"
74 #endif
75 "\n"
76 "Block device options:\n"
77 " -r, --read-only export read-only\n"
78 " -s, --snapshot use snapshot file\n"
79 " -n, --nocache disable host cache\n"
80 "\n"
81 "Report bugs to <qemu-devel@nongnu.org>\n"
82 , name, NBD_DEFAULT_PORT, "DEVICE");
85 static void version(const char *name)
87 printf(
88 "%s version 0.0.1\n"
89 "Written by Anthony Liguori.\n"
90 "\n"
91 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
92 "This is free software; see the source for copying conditions. There is NO\n"
93 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
94 , name);
97 struct partition_record
99 uint8_t bootable;
100 uint8_t start_head;
101 uint32_t start_cylinder;
102 uint8_t start_sector;
103 uint8_t system;
104 uint8_t end_head;
105 uint8_t end_cylinder;
106 uint8_t end_sector;
107 uint32_t start_sector_abs;
108 uint32_t nb_sectors_abs;
111 static void read_partition(uint8_t *p, struct partition_record *r)
113 r->bootable = p[0];
114 r->start_head = p[1];
115 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
116 r->start_sector = p[2] & 0x3f;
117 r->system = p[4];
118 r->end_head = p[5];
119 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
120 r->end_sector = p[6] & 0x3f;
121 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
122 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
125 static int find_partition(BlockDriverState *bs, int partition,
126 off_t *offset, off_t *size)
128 struct partition_record mbr[4];
129 uint8_t data[512];
130 int i;
131 int ext_partnum = 4;
132 int ret;
134 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
135 errno = -ret;
136 err(EXIT_FAILURE, "error while reading");
139 if (data[510] != 0x55 || data[511] != 0xaa) {
140 return -EINVAL;
143 for (i = 0; i < 4; i++) {
144 read_partition(&data[446 + 16 * i], &mbr[i]);
146 if (!mbr[i].nb_sectors_abs)
147 continue;
149 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
150 struct partition_record ext[4];
151 uint8_t data1[512];
152 int j;
154 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
155 errno = -ret;
156 err(EXIT_FAILURE, "error while reading");
159 for (j = 0; j < 4; j++) {
160 read_partition(&data1[446 + 16 * j], &ext[j]);
161 if (!ext[j].nb_sectors_abs)
162 continue;
164 if ((ext_partnum + j + 1) == partition) {
165 *offset = (uint64_t)ext[j].start_sector_abs << 9;
166 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
167 return 0;
170 ext_partnum += 4;
171 } else if ((i + 1) == partition) {
172 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
173 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
174 return 0;
178 return -ENOENT;
181 static void termsig_handler(int signum)
183 sigterm_reported = true;
184 qemu_notify_event();
187 static void *show_parts(void *arg)
189 char *device = arg;
190 int nbd;
192 /* linux just needs an open() to trigger
193 * the partition table update
194 * but remember to load the module with max_part != 0 :
195 * modprobe nbd max_part=63
197 nbd = open(device, O_RDWR);
198 if (nbd >= 0) {
199 close(nbd);
201 return NULL;
204 static void *nbd_client_thread(void *arg)
206 char *device = arg;
207 off_t size;
208 size_t blocksize;
209 uint32_t nbdflags;
210 int fd, sock;
211 int ret;
212 pthread_t show_parts_thread;
214 sock = unix_socket_outgoing(sockpath);
215 if (sock < 0) {
216 goto out;
219 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
220 &size, &blocksize);
221 if (ret < 0) {
222 goto out;
225 fd = open(device, O_RDWR);
226 if (fd < 0) {
227 /* Linux-only, we can use %m in printf. */
228 fprintf(stderr, "Failed to open %s: %m", device);
229 goto out;
232 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
233 if (ret < 0) {
234 goto out;
237 /* update partition table */
238 pthread_create(&show_parts_thread, NULL, show_parts, device);
240 if (verbose) {
241 fprintf(stderr, "NBD device %s is now connected to %s\n",
242 device, srcpath);
243 } else {
244 /* Close stderr so that the qemu-nbd process exits. */
245 dup2(STDOUT_FILENO, STDERR_FILENO);
248 ret = nbd_client(fd);
249 if (ret) {
250 goto out;
252 close(fd);
253 kill(getpid(), SIGTERM);
254 return (void *) EXIT_SUCCESS;
256 out:
257 kill(getpid(), SIGTERM);
258 return (void *) EXIT_FAILURE;
261 static int nbd_can_accept(void *opaque)
263 return nb_fds < shared;
266 static void nbd_client_closed(NBDClient *client)
268 nb_fds--;
269 qemu_notify_event();
272 static void nbd_accept(void *opaque)
274 int server_fd = (uintptr_t) opaque;
275 struct sockaddr_in addr;
276 socklen_t addr_len = sizeof(addr);
278 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
279 nbd_started = true;
280 if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {
281 nb_fds++;
285 int main(int argc, char **argv)
287 BlockDriverState *bs;
288 off_t dev_offset = 0;
289 uint32_t nbdflags = 0;
290 bool disconnect = false;
291 const char *bindto = "0.0.0.0";
292 char *device = NULL;
293 int port = NBD_DEFAULT_PORT;
294 off_t fd_size;
295 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
296 struct option lopt[] = {
297 { "help", 0, NULL, 'h' },
298 { "version", 0, NULL, 'V' },
299 { "bind", 1, NULL, 'b' },
300 { "port", 1, NULL, 'p' },
301 { "socket", 1, NULL, 'k' },
302 { "offset", 1, NULL, 'o' },
303 { "read-only", 0, NULL, 'r' },
304 { "partition", 1, NULL, 'P' },
305 { "connect", 1, NULL, 'c' },
306 { "disconnect", 0, NULL, 'd' },
307 { "snapshot", 0, NULL, 's' },
308 { "nocache", 0, NULL, 'n' },
309 { "shared", 1, NULL, 'e' },
310 { "persistent", 0, NULL, 't' },
311 { "verbose", 0, NULL, 'v' },
312 { NULL, 0, NULL, 0 }
314 int ch;
315 int opt_ind = 0;
316 int li;
317 char *end;
318 int flags = BDRV_O_RDWR;
319 int partition = -1;
320 int ret;
321 int fd;
322 int persistent = 0;
323 pthread_t client_thread;
325 /* The client thread uses SIGTERM to interrupt the server. A signal
326 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
328 struct sigaction sa_sigterm;
329 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
330 sa_sigterm.sa_handler = termsig_handler;
331 sigaction(SIGTERM, &sa_sigterm, NULL);
333 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
334 switch (ch) {
335 case 's':
336 flags |= BDRV_O_SNAPSHOT;
337 break;
338 case 'n':
339 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
340 break;
341 case 'b':
342 bindto = optarg;
343 break;
344 case 'p':
345 li = strtol(optarg, &end, 0);
346 if (*end) {
347 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
349 if (li < 1 || li > 65535) {
350 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
352 port = (uint16_t)li;
353 break;
354 case 'o':
355 dev_offset = strtoll (optarg, &end, 0);
356 if (*end) {
357 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
359 if (dev_offset < 0) {
360 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
362 break;
363 case 'r':
364 nbdflags |= NBD_FLAG_READ_ONLY;
365 flags &= ~BDRV_O_RDWR;
366 break;
367 case 'P':
368 partition = strtol(optarg, &end, 0);
369 if (*end)
370 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
371 if (partition < 1 || partition > 8)
372 errx(EXIT_FAILURE, "Invalid partition %d", partition);
373 break;
374 case 'k':
375 sockpath = optarg;
376 if (sockpath[0] != '/')
377 errx(EXIT_FAILURE, "socket path must be absolute\n");
378 break;
379 case 'd':
380 disconnect = true;
381 break;
382 case 'c':
383 device = optarg;
384 break;
385 case 'e':
386 shared = strtol(optarg, &end, 0);
387 if (*end) {
388 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
390 if (shared < 1) {
391 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
393 break;
394 case 't':
395 persistent = 1;
396 break;
397 case 'v':
398 verbose = 1;
399 break;
400 case 'V':
401 version(argv[0]);
402 exit(0);
403 break;
404 case 'h':
405 usage(argv[0]);
406 exit(0);
407 break;
408 case '?':
409 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
410 argv[0]);
414 if ((argc - optind) != 1) {
415 errx(EXIT_FAILURE, "Invalid number of argument.\n"
416 "Try `%s --help' for more information.",
417 argv[0]);
420 if (disconnect) {
421 fd = open(argv[optind], O_RDWR);
422 if (fd < 0) {
423 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
425 nbd_disconnect(fd);
427 close(fd);
429 printf("%s disconnected\n", argv[optind]);
431 return 0;
434 if (device && !verbose) {
435 int stderr_fd[2];
436 pid_t pid;
437 int ret;
439 if (qemu_pipe(stderr_fd) < 0) {
440 err(EXIT_FAILURE, "Error setting up communication pipe");
443 /* Now daemonize, but keep a communication channel open to
444 * print errors and exit with the proper status code.
446 pid = fork();
447 if (pid == 0) {
448 close(stderr_fd[0]);
449 ret = qemu_daemon(1, 0);
451 /* Temporarily redirect stderr to the parent's pipe... */
452 dup2(stderr_fd[1], STDERR_FILENO);
453 if (ret < 0) {
454 err(EXIT_FAILURE, "Failed to daemonize");
457 /* ... close the descriptor we inherited and go on. */
458 close(stderr_fd[1]);
459 } else {
460 bool errors = false;
461 char *buf;
463 /* In the parent. Print error messages from the child until
464 * it closes the pipe.
466 close(stderr_fd[1]);
467 buf = g_malloc(1024);
468 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
469 errors = true;
470 ret = qemu_write_full(STDERR_FILENO, buf, ret);
471 if (ret < 0) {
472 exit(EXIT_FAILURE);
475 if (ret < 0) {
476 err(EXIT_FAILURE, "Cannot read from daemon");
479 /* Usually the daemon should not print any message.
480 * Exit with zero status in that case.
482 exit(errors);
486 if (device != NULL && sockpath == NULL) {
487 sockpath = g_malloc(128);
488 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
491 bdrv_init();
492 atexit(bdrv_close_all);
494 bs = bdrv_new("hda");
495 srcpath = argv[optind];
496 if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
497 errno = -ret;
498 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
501 fd_size = bdrv_getlength(bs);
503 if (partition != -1) {
504 ret = find_partition(bs, partition, &dev_offset, &fd_size);
505 if (ret < 0) {
506 errno = -ret;
507 err(EXIT_FAILURE, "Could not find partition %d", partition);
511 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags);
513 if (sockpath) {
514 fd = unix_socket_incoming(sockpath);
515 } else {
516 fd = tcp_socket_incoming(bindto, port);
519 if (fd < 0) {
520 return 1;
523 if (device) {
524 int ret;
526 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
527 if (ret != 0) {
528 errx(EXIT_FAILURE, "Failed to create client thread: %s",
529 strerror(ret));
531 } else {
532 /* Shut up GCC warnings. */
533 memset(&client_thread, 0, sizeof(client_thread));
536 qemu_init_main_loop();
537 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
538 (void *)(uintptr_t)fd);
540 /* now when the initialization is (almost) complete, chdir("/")
541 * to free any busy filesystems */
542 if (chdir("/") < 0) {
543 err(EXIT_FAILURE, "Could not chdir to root directory");
546 do {
547 main_loop_wait(false);
548 } while (!sigterm_reported && (persistent || !nbd_started || nb_fds > 0));
550 nbd_export_close(exp);
551 if (sockpath) {
552 unlink(sockpath);
555 if (device) {
556 void *ret;
557 pthread_join(client_thread, &ret);
558 exit(ret != NULL);
559 } else {
560 exit(EXIT_SUCCESS);