hda-codec: convert to QEMU Object Model
[qemu.git] / qemu-nbd.c
blobeb61c33acd490f3aa786db4b9388aa2823d17447
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>
34 #include <pthread.h>
36 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
38 static NBDExport *exp;
39 static int verbose;
40 static char *device;
41 static char *srcpath;
42 static char *sockpath;
43 static bool sigterm_reported;
44 static bool nbd_started;
45 static int shared = 1;
46 static int nb_fds;
48 static void usage(const char *name)
50 printf(
51 "Usage: %s [OPTIONS] FILE\n"
52 "QEMU Disk Network Block Device Server\n"
53 "\n"
54 " -p, --port=PORT port to listen on (default `%d')\n"
55 " -o, --offset=OFFSET offset into the image\n"
56 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
57 " -k, --socket=PATH path to the unix socket\n"
58 " (default '"SOCKET_PATH"')\n"
59 " -r, --read-only export read-only\n"
60 " -P, --partition=NUM only expose partition NUM\n"
61 " -s, --snapshot use snapshot file\n"
62 " -n, --nocache disable host cache\n"
63 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
64 " -d, --disconnect disconnect the specified device\n"
65 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
66 " -t, --persistent don't exit on the last connection\n"
67 " -v, --verbose display extra debugging information\n"
68 " -h, --help display this help and exit\n"
69 " -V, --version output version information and exit\n"
70 "\n"
71 "Report bugs to <anthony@codemonkey.ws>\n"
72 , name, NBD_DEFAULT_PORT, "DEVICE");
75 static void version(const char *name)
77 printf(
78 "%s version 0.0.1\n"
79 "Written by Anthony Liguori.\n"
80 "\n"
81 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
82 "This is free software; see the source for copying conditions. There is NO\n"
83 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
84 , name);
87 struct partition_record
89 uint8_t bootable;
90 uint8_t start_head;
91 uint32_t start_cylinder;
92 uint8_t start_sector;
93 uint8_t system;
94 uint8_t end_head;
95 uint8_t end_cylinder;
96 uint8_t end_sector;
97 uint32_t start_sector_abs;
98 uint32_t nb_sectors_abs;
101 static void read_partition(uint8_t *p, struct partition_record *r)
103 r->bootable = p[0];
104 r->start_head = p[1];
105 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
106 r->start_sector = p[2] & 0x3f;
107 r->system = p[4];
108 r->end_head = p[5];
109 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
110 r->end_sector = p[6] & 0x3f;
111 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
112 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
115 static int find_partition(BlockDriverState *bs, int partition,
116 off_t *offset, off_t *size)
118 struct partition_record mbr[4];
119 uint8_t data[512];
120 int i;
121 int ext_partnum = 4;
122 int ret;
124 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
125 errno = -ret;
126 err(EXIT_FAILURE, "error while reading");
129 if (data[510] != 0x55 || data[511] != 0xaa) {
130 errno = -EINVAL;
131 return -1;
134 for (i = 0; i < 4; i++) {
135 read_partition(&data[446 + 16 * i], &mbr[i]);
137 if (!mbr[i].nb_sectors_abs)
138 continue;
140 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
141 struct partition_record ext[4];
142 uint8_t data1[512];
143 int j;
145 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
146 errno = -ret;
147 err(EXIT_FAILURE, "error while reading");
150 for (j = 0; j < 4; j++) {
151 read_partition(&data1[446 + 16 * j], &ext[j]);
152 if (!ext[j].nb_sectors_abs)
153 continue;
155 if ((ext_partnum + j + 1) == partition) {
156 *offset = (uint64_t)ext[j].start_sector_abs << 9;
157 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
158 return 0;
161 ext_partnum += 4;
162 } else if ((i + 1) == partition) {
163 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
164 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
165 return 0;
169 errno = -ENOENT;
170 return -1;
173 static void termsig_handler(int signum)
175 sigterm_reported = true;
176 qemu_notify_event();
179 static void *show_parts(void *arg)
181 int nbd;
183 /* linux just needs an open() to trigger
184 * the partition table update
185 * but remember to load the module with max_part != 0 :
186 * modprobe nbd max_part=63
188 nbd = open(device, O_RDWR);
189 if (nbd != -1) {
190 close(nbd);
192 return NULL;
195 static void *nbd_client_thread(void *arg)
197 int fd = *(int *)arg;
198 off_t size;
199 size_t blocksize;
200 uint32_t nbdflags;
201 int sock;
202 int ret;
203 pthread_t show_parts_thread;
205 sock = unix_socket_outgoing(sockpath);
206 if (sock == -1) {
207 goto out;
210 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
211 &size, &blocksize);
212 if (ret == -1) {
213 goto out;
216 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
217 if (ret == -1) {
218 goto out;
221 /* update partition table */
222 pthread_create(&show_parts_thread, NULL, show_parts, NULL);
224 if (verbose) {
225 fprintf(stderr, "NBD device %s is now connected to %s\n",
226 device, srcpath);
227 } else {
228 /* Close stderr so that the qemu-nbd process exits. */
229 dup2(STDOUT_FILENO, STDERR_FILENO);
232 ret = nbd_client(fd);
233 if (ret) {
234 goto out;
236 close(fd);
237 kill(getpid(), SIGTERM);
238 return (void *) EXIT_SUCCESS;
240 out:
241 kill(getpid(), SIGTERM);
242 return (void *) EXIT_FAILURE;
245 static int nbd_can_accept(void *opaque)
247 return nb_fds < shared;
250 static void nbd_client_closed(NBDClient *client)
252 nb_fds--;
253 qemu_notify_event();
256 static void nbd_accept(void *opaque)
258 int server_fd = (uintptr_t) opaque;
259 struct sockaddr_in addr;
260 socklen_t addr_len = sizeof(addr);
262 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
263 nbd_started = true;
264 if (fd != -1 && nbd_client_new(exp, fd, nbd_client_closed)) {
265 nb_fds++;
269 int main(int argc, char **argv)
271 BlockDriverState *bs;
272 off_t dev_offset = 0;
273 uint32_t nbdflags = 0;
274 bool disconnect = false;
275 const char *bindto = "0.0.0.0";
276 int port = NBD_DEFAULT_PORT;
277 off_t fd_size;
278 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
279 struct option lopt[] = {
280 { "help", 0, NULL, 'h' },
281 { "version", 0, NULL, 'V' },
282 { "bind", 1, NULL, 'b' },
283 { "port", 1, NULL, 'p' },
284 { "socket", 1, NULL, 'k' },
285 { "offset", 1, NULL, 'o' },
286 { "read-only", 0, NULL, 'r' },
287 { "partition", 1, NULL, 'P' },
288 { "connect", 1, NULL, 'c' },
289 { "disconnect", 0, NULL, 'd' },
290 { "snapshot", 0, NULL, 's' },
291 { "nocache", 0, NULL, 'n' },
292 { "shared", 1, NULL, 'e' },
293 { "persistent", 0, NULL, 't' },
294 { "verbose", 0, NULL, 'v' },
295 { NULL, 0, NULL, 0 }
297 int ch;
298 int opt_ind = 0;
299 int li;
300 char *end;
301 int flags = BDRV_O_RDWR;
302 int partition = -1;
303 int ret;
304 int fd;
305 int persistent = 0;
306 pthread_t client_thread;
308 /* The client thread uses SIGTERM to interrupt the server. A signal
309 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
311 struct sigaction sa_sigterm;
312 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
313 sa_sigterm.sa_handler = termsig_handler;
314 sigaction(SIGTERM, &sa_sigterm, NULL);
316 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
317 switch (ch) {
318 case 's':
319 flags |= BDRV_O_SNAPSHOT;
320 break;
321 case 'n':
322 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
323 break;
324 case 'b':
325 bindto = optarg;
326 break;
327 case 'p':
328 li = strtol(optarg, &end, 0);
329 if (*end) {
330 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
332 if (li < 1 || li > 65535) {
333 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
335 port = (uint16_t)li;
336 break;
337 case 'o':
338 dev_offset = strtoll (optarg, &end, 0);
339 if (*end) {
340 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
342 if (dev_offset < 0) {
343 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
345 break;
346 case 'r':
347 nbdflags |= NBD_FLAG_READ_ONLY;
348 flags &= ~BDRV_O_RDWR;
349 break;
350 case 'P':
351 partition = strtol(optarg, &end, 0);
352 if (*end)
353 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
354 if (partition < 1 || partition > 8)
355 errx(EXIT_FAILURE, "Invalid partition %d", partition);
356 break;
357 case 'k':
358 sockpath = optarg;
359 if (sockpath[0] != '/')
360 errx(EXIT_FAILURE, "socket path must be absolute\n");
361 break;
362 case 'd':
363 disconnect = true;
364 break;
365 case 'c':
366 device = optarg;
367 break;
368 case 'e':
369 shared = strtol(optarg, &end, 0);
370 if (*end) {
371 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
373 if (shared < 1) {
374 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
376 break;
377 case 't':
378 persistent = 1;
379 break;
380 case 'v':
381 verbose = 1;
382 break;
383 case 'V':
384 version(argv[0]);
385 exit(0);
386 break;
387 case 'h':
388 usage(argv[0]);
389 exit(0);
390 break;
391 case '?':
392 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
393 argv[0]);
397 if ((argc - optind) != 1) {
398 errx(EXIT_FAILURE, "Invalid number of argument.\n"
399 "Try `%s --help' for more information.",
400 argv[0]);
403 if (disconnect) {
404 fd = open(argv[optind], O_RDWR);
405 if (fd == -1)
406 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
408 nbd_disconnect(fd);
410 close(fd);
412 printf("%s disconnected\n", argv[optind]);
414 return 0;
417 if (device && !verbose) {
418 int stderr_fd[2];
419 pid_t pid;
420 int ret;
422 if (qemu_pipe(stderr_fd) == -1) {
423 err(EXIT_FAILURE, "Error setting up communication pipe");
426 /* Now daemonize, but keep a communication channel open to
427 * print errors and exit with the proper status code.
429 pid = fork();
430 if (pid == 0) {
431 close(stderr_fd[0]);
432 ret = qemu_daemon(0, 0);
434 /* Temporarily redirect stderr to the parent's pipe... */
435 dup2(stderr_fd[1], STDERR_FILENO);
436 if (ret == -1) {
437 err(EXIT_FAILURE, "Failed to daemonize");
440 /* ... close the descriptor we inherited and go on. */
441 close(stderr_fd[1]);
442 } else {
443 bool errors = false;
444 char *buf;
446 /* In the parent. Print error messages from the child until
447 * it closes the pipe.
449 close(stderr_fd[1]);
450 buf = g_malloc(1024);
451 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
452 errors = true;
453 ret = qemu_write_full(STDERR_FILENO, buf, ret);
454 if (ret == -1) {
455 exit(EXIT_FAILURE);
458 if (ret == -1) {
459 err(EXIT_FAILURE, "Cannot read from daemon");
462 /* Usually the daemon should not print any message.
463 * Exit with zero status in that case.
465 exit(errors);
469 if (device) {
470 /* Open before spawning new threads. In the future, we may
471 * drop privileges after opening.
473 fd = open(device, O_RDWR);
474 if (fd == -1) {
475 err(EXIT_FAILURE, "Failed to open %s", device);
478 if (sockpath == NULL) {
479 sockpath = g_malloc(128);
480 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
484 bdrv_init();
485 atexit(bdrv_close_all);
487 bs = bdrv_new("hda");
488 srcpath = argv[optind];
489 if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
490 errno = -ret;
491 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
494 fd_size = bs->total_sectors * 512;
496 if (partition != -1 &&
497 find_partition(bs, partition, &dev_offset, &fd_size)) {
498 err(EXIT_FAILURE, "Could not find partition %d", partition);
501 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags);
503 if (sockpath) {
504 fd = unix_socket_incoming(sockpath);
505 } else {
506 fd = tcp_socket_incoming(bindto, port);
509 if (fd == -1) {
510 return 1;
513 if (device) {
514 int ret;
516 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &fd);
517 if (ret != 0) {
518 errx(EXIT_FAILURE, "Failed to create client thread: %s",
519 strerror(ret));
521 } else {
522 /* Shut up GCC warnings. */
523 memset(&client_thread, 0, sizeof(client_thread));
526 qemu_init_main_loop();
527 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
528 (void *)(uintptr_t)fd);
530 do {
531 main_loop_wait(false);
532 } while (!sigterm_reported && (persistent || !nbd_started || nb_fds > 0));
534 nbd_export_close(exp);
535 if (sockpath) {
536 unlink(sockpath);
539 if (device) {
540 void *ret;
541 pthread_join(client_thread, &ret);
542 exit(ret != NULL);
543 } else {
544 exit(EXIT_SUCCESS);