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"
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>
36 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
38 static NBDExport *exp;
41 static char *sockpath;
42 static bool sigterm_reported;
43 static bool nbd_started;
44 static int shared = 1;
47 static void usage(const char *name)
50 "Usage: %s [OPTIONS] FILE\n"
51 "QEMU Disk Network Block Device Server\n"
53 " -p, --port=PORT port to listen on (default `%d')\n"
54 " -o, --offset=OFFSET offset into the image\n"
55 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
56 " -k, --socket=PATH path to the unix socket\n"
57 " (default '"SOCKET_PATH"')\n"
58 " -r, --read-only export read-only\n"
59 " -P, --partition=NUM only expose partition NUM\n"
60 " -s, --snapshot use snapshot file\n"
61 " -n, --nocache disable host cache\n"
62 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
63 " -d, --disconnect disconnect the specified device\n"
64 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
65 " -t, --persistent don't exit on the last connection\n"
66 " -v, --verbose display extra debugging information\n"
67 " -h, --help display this help and exit\n"
68 " -V, --version output version information and exit\n"
71 , name, NBD_DEFAULT_PORT, "DEVICE");
74 static void version(const char *name)
78 "Written by Anthony Liguori.\n"
81 "This is free software; see the source for copying conditions. There is NO\n"
82 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
86 struct partition_record
90 uint32_t start_cylinder;
96 uint32_t start_sector_abs;
97 uint32_t nb_sectors_abs;
100 static void read_partition(uint8_t *p, struct partition_record *r)
103 r->start_head = p[1];
104 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
105 r->start_sector = p[2] & 0x3f;
108 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
109 r->end_sector = p[6] & 0x3f;
110 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
111 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
114 static int find_partition(BlockDriverState *bs, int partition,
115 off_t *offset, off_t *size)
117 struct partition_record mbr[4];
123 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
125 err(EXIT_FAILURE, "error while reading");
128 if (data[510] != 0x55 || data[511] != 0xaa) {
132 for (i = 0; i < 4; i++) {
133 read_partition(&data[446 + 16 * i], &mbr[i]);
135 if (!mbr[i].nb_sectors_abs)
138 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
139 struct partition_record ext[4];
143 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
145 err(EXIT_FAILURE, "error while reading");
148 for (j = 0; j < 4; j++) {
149 read_partition(&data1[446 + 16 * j], &ext[j]);
150 if (!ext[j].nb_sectors_abs)
153 if ((ext_partnum + j + 1) == partition) {
154 *offset = (uint64_t)ext[j].start_sector_abs << 9;
155 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
160 } else if ((i + 1) == partition) {
161 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
162 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
170 static void termsig_handler(int signum)
172 sigterm_reported = true;
176 static void *show_parts(void *arg)
181 /* linux just needs an open() to trigger
182 * the partition table update
183 * but remember to load the module with max_part != 0 :
184 * modprobe nbd max_part=63
186 nbd = open(device, O_RDWR);
193 static void *nbd_client_thread(void *arg)
201 pthread_t show_parts_thread;
203 sock = unix_socket_outgoing(sockpath);
208 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
214 fd = open(device, O_RDWR);
216 /* Linux-only, we can use %m in printf. */
217 fprintf(stderr, "Failed to open %s: %m", device);
221 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
226 /* update partition table */
227 pthread_create(&show_parts_thread, NULL, show_parts, device);
230 fprintf(stderr, "NBD device %s is now connected to %s\n",
233 /* Close stderr so that the qemu-nbd process exits. */
234 dup2(STDOUT_FILENO, STDERR_FILENO);
237 ret = nbd_client(fd);
242 kill(getpid(), SIGTERM);
243 return (void *) EXIT_SUCCESS;
246 kill(getpid(), SIGTERM);
247 return (void *) EXIT_FAILURE;
250 static int nbd_can_accept(void *opaque)
252 return nb_fds < shared;
255 static void nbd_client_closed(NBDClient *client)
261 static void nbd_accept(void *opaque)
263 int server_fd = (uintptr_t) opaque;
264 struct sockaddr_in addr;
265 socklen_t addr_len = sizeof(addr);
267 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
269 if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {
274 int main(int argc, char **argv)
276 BlockDriverState *bs;
277 off_t dev_offset = 0;
278 uint32_t nbdflags = 0;
279 bool disconnect = false;
280 const char *bindto = "0.0.0.0";
282 int port = NBD_DEFAULT_PORT;
284 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
285 struct option lopt[] = {
286 { "help", 0, NULL, 'h' },
287 { "version", 0, NULL, 'V' },
288 { "bind", 1, NULL, 'b' },
289 { "port", 1, NULL, 'p' },
290 { "socket", 1, NULL, 'k' },
291 { "offset", 1, NULL, 'o' },
292 { "read-only", 0, NULL, 'r' },
293 { "partition", 1, NULL, 'P' },
294 { "connect", 1, NULL, 'c' },
295 { "disconnect", 0, NULL, 'd' },
296 { "snapshot", 0, NULL, 's' },
297 { "nocache", 0, NULL, 'n' },
298 { "shared", 1, NULL, 'e' },
299 { "persistent", 0, NULL, 't' },
300 { "verbose", 0, NULL, 'v' },
307 int flags = BDRV_O_RDWR;
312 pthread_t client_thread;
314 /* The client thread uses SIGTERM to interrupt the server. A signal
315 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
317 struct sigaction sa_sigterm;
318 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
319 sa_sigterm.sa_handler = termsig_handler;
320 sigaction(SIGTERM, &sa_sigterm, NULL);
322 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
325 flags |= BDRV_O_SNAPSHOT;
328 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
334 li = strtol(optarg, &end, 0);
336 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
338 if (li < 1 || li > 65535) {
339 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
344 dev_offset = strtoll (optarg, &end, 0);
346 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
348 if (dev_offset < 0) {
349 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
353 nbdflags |= NBD_FLAG_READ_ONLY;
354 flags &= ~BDRV_O_RDWR;
357 partition = strtol(optarg, &end, 0);
359 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
360 if (partition < 1 || partition > 8)
361 errx(EXIT_FAILURE, "Invalid partition %d", partition);
365 if (sockpath[0] != '/')
366 errx(EXIT_FAILURE, "socket path must be absolute\n");
375 shared = strtol(optarg, &end, 0);
377 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
380 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
398 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
403 if ((argc - optind) != 1) {
404 errx(EXIT_FAILURE, "Invalid number of argument.\n"
405 "Try `%s --help' for more information.",
410 fd = open(argv[optind], O_RDWR);
412 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
418 printf("%s disconnected\n", argv[optind]);
423 if (device && !verbose) {
428 if (qemu_pipe(stderr_fd) < 0) {
429 err(EXIT_FAILURE, "Error setting up communication pipe");
432 /* Now daemonize, but keep a communication channel open to
433 * print errors and exit with the proper status code.
438 ret = qemu_daemon(1, 0);
440 /* Temporarily redirect stderr to the parent's pipe... */
441 dup2(stderr_fd[1], STDERR_FILENO);
443 err(EXIT_FAILURE, "Failed to daemonize");
446 /* ... close the descriptor we inherited and go on. */
452 /* In the parent. Print error messages from the child until
453 * it closes the pipe.
456 buf = g_malloc(1024);
457 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
459 ret = qemu_write_full(STDERR_FILENO, buf, ret);
465 err(EXIT_FAILURE, "Cannot read from daemon");
468 /* Usually the daemon should not print any message.
469 * Exit with zero status in that case.
475 if (device != NULL && sockpath == NULL) {
476 sockpath = g_malloc(128);
477 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
481 atexit(bdrv_close_all);
483 bs = bdrv_new("hda");
484 srcpath = argv[optind];
485 if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
487 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
490 fd_size = bdrv_getlength(bs);
492 if (partition != -1) {
493 ret = find_partition(bs, partition, &dev_offset, &fd_size);
496 err(EXIT_FAILURE, "Could not find partition %d", partition);
500 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags);
503 fd = unix_socket_incoming(sockpath);
505 fd = tcp_socket_incoming(bindto, port);
515 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
517 errx(EXIT_FAILURE, "Failed to create client thread: %s",
521 /* Shut up GCC warnings. */
522 memset(&client_thread, 0, sizeof(client_thread));
525 qemu_init_main_loop();
526 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
527 (void *)(uintptr_t)fd);
529 /* now when the initialization is (almost) complete, chdir("/")
530 * to free any busy filesystems */
531 if (chdir("/") < 0) {
532 err(EXIT_FAILURE, "Could not chdir to root directory");
536 main_loop_wait(false);
537 } while (!sigterm_reported && (persistent || !nbd_started || nb_fds > 0));
539 nbd_export_close(exp);
546 pthread_join(client_thread, &ret);