]> git.proxmox.com Git - qemu.git/blame - qemu-nbd.c
softfloat: Replace int16 type with int_fast16_t
[qemu.git] / qemu-nbd.c
CommitLineData
cd831bd7 1/*
7a5ca864
FB
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
4 * Network Block Device
5 *
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.
9 *
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.
14 *
15 * You should have received a copy of the GNU General Public License
8167ee88 16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7a5ca864
FB
17 */
18
5a61cb60 19#include "qemu-common.h"
38ceff04 20#include "block.h"
7a5ca864
FB
21#include "nbd.h"
22
7a5ca864
FB
23#include <stdarg.h>
24#include <stdio.h>
25#include <getopt.h>
26#include <err.h>
cd831bd7 27#include <sys/types.h>
7a5ca864
FB
28#include <sys/socket.h>
29#include <netinet/in.h>
30#include <netinet/tcp.h>
31#include <arpa/inet.h>
cd831bd7 32#include <signal.h>
2bff4b6f 33#include <libgen.h>
a517e88b 34#include <pthread.h>
cd831bd7
TS
35
36#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
7a5ca864 37
af49bbbe 38static NBDExport *exp;
b1d8e52e 39static int verbose;
a517e88b
PB
40static char *srcpath;
41static char *sockpath;
a61c6782
PB
42static bool sigterm_reported;
43static bool nbd_started;
44static int shared = 1;
45static int nb_fds;
7a5ca864
FB
46
47static void usage(const char *name)
48{
49 printf(
50"Usage: %s [OPTIONS] FILE\n"
51"QEMU Disk Network Block Device Server\n"
52"\n"
c2e2872b 53" -p, --port=PORT port to listen on (default `%d')\n"
7a5ca864
FB
54" -o, --offset=OFFSET offset into the image\n"
55" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
cd831bd7
TS
56" -k, --socket=PATH path to the unix socket\n"
57" (default '"SOCKET_PATH"')\n"
7a5ca864
FB
58" -r, --read-only export read-only\n"
59" -P, --partition=NUM only expose partition NUM\n"
2f726488
TS
60" -s, --snapshot use snapshot file\n"
61" -n, --nocache disable host cache\n"
cd831bd7
TS
62" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
63" -d, --disconnect disconnect the specified device\n"
3b05a8e9 64" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
75818250 65" -t, --persistent don't exit on the last connection\n"
7a5ca864
FB
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"
69"\n"
70"Report bugs to <anthony@codemonkey.ws>\n"
c2e2872b 71 , name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
72}
73
74static void version(const char *name)
75{
76 printf(
315bc7aa 77"%s version 0.0.1\n"
7a5ca864
FB
78"Written by Anthony Liguori.\n"
79"\n"
80"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\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"
315bc7aa 83 , name);
7a5ca864
FB
84}
85
86struct partition_record
87{
88 uint8_t bootable;
89 uint8_t start_head;
90 uint32_t start_cylinder;
91 uint8_t start_sector;
92 uint8_t system;
93 uint8_t end_head;
94 uint8_t end_cylinder;
95 uint8_t end_sector;
96 uint32_t start_sector_abs;
97 uint32_t nb_sectors_abs;
98};
99
100static void read_partition(uint8_t *p, struct partition_record *r)
101{
102 r->bootable = p[0];
103 r->start_head = p[1];
104 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
105 r->start_sector = p[2] & 0x3f;
106 r->system = p[4];
107 r->end_head = p[5];
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;
112}
113
114static int find_partition(BlockDriverState *bs, int partition,
115 off_t *offset, off_t *size)
116{
117 struct partition_record mbr[4];
118 uint8_t data[512];
119 int i;
120 int ext_partnum = 4;
cb7cf0e3 121 int ret;
7a5ca864 122
cb7cf0e3
RO
123 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
124 errno = -ret;
125 err(EXIT_FAILURE, "error while reading");
126 }
7a5ca864
FB
127
128 if (data[510] != 0x55 || data[511] != 0xaa) {
185b4338 129 return -EINVAL;
7a5ca864
FB
130 }
131
132 for (i = 0; i < 4; i++) {
133 read_partition(&data[446 + 16 * i], &mbr[i]);
134
135 if (!mbr[i].nb_sectors_abs)
136 continue;
137
138 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
139 struct partition_record ext[4];
140 uint8_t data1[512];
141 int j;
142
cb7cf0e3
RO
143 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
144 errno = -ret;
145 err(EXIT_FAILURE, "error while reading");
146 }
7a5ca864
FB
147
148 for (j = 0; j < 4; j++) {
149 read_partition(&data1[446 + 16 * j], &ext[j]);
150 if (!ext[j].nb_sectors_abs)
151 continue;
152
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;
156 return 0;
157 }
158 }
159 ext_partnum += 4;
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;
163 return 0;
164 }
165 }
166
185b4338 167 return -ENOENT;
7a5ca864
FB
168}
169
bb345110
PB
170static void termsig_handler(int signum)
171{
a61c6782
PB
172 sigterm_reported = true;
173 qemu_notify_event();
bb345110
PB
174}
175
a517e88b 176static void *show_parts(void *arg)
cd831bd7 177{
a6ac2313 178 char *device = arg;
a517e88b
PB
179 int nbd;
180
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
185 */
186 nbd = open(device, O_RDWR);
fc19f8a0 187 if (nbd >= 0) {
a517e88b
PB
188 close(nbd);
189 }
190 return NULL;
191}
cd831bd7 192
a517e88b
PB
193static void *nbd_client_thread(void *arg)
194{
a6ac2313 195 char *device = arg;
a517e88b
PB
196 off_t size;
197 size_t blocksize;
198 uint32_t nbdflags;
a6ac2313 199 int fd, sock;
a517e88b
PB
200 int ret;
201 pthread_t show_parts_thread;
202
dc10e8b3 203 sock = unix_socket_outgoing(sockpath);
fc19f8a0 204 if (sock < 0) {
dc10e8b3
SH
205 goto out;
206 }
a517e88b
PB
207
208 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
209 &size, &blocksize);
fc19f8a0 210 if (ret < 0) {
a517e88b
PB
211 goto out;
212 }
213
a6ac2313 214 fd = open(device, O_RDWR);
fc19f8a0 215 if (fd < 0) {
a6ac2313
PB
216 /* Linux-only, we can use %m in printf. */
217 fprintf(stderr, "Failed to open %s: %m", device);
218 goto out;
219 }
220
a517e88b 221 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
fc19f8a0 222 if (ret < 0) {
a517e88b
PB
223 goto out;
224 }
225
226 /* update partition table */
a6ac2313 227 pthread_create(&show_parts_thread, NULL, show_parts, device);
a517e88b 228
c1f8fdc3
PB
229 if (verbose) {
230 fprintf(stderr, "NBD device %s is now connected to %s\n",
231 device, srcpath);
232 } else {
233 /* Close stderr so that the qemu-nbd process exits. */
234 dup2(STDOUT_FILENO, STDERR_FILENO);
235 }
a517e88b
PB
236
237 ret = nbd_client(fd);
238 if (ret) {
239 goto out;
cd831bd7 240 }
a517e88b
PB
241 close(fd);
242 kill(getpid(), SIGTERM);
243 return (void *) EXIT_SUCCESS;
244
245out:
246 kill(getpid(), SIGTERM);
247 return (void *) EXIT_FAILURE;
cd831bd7
TS
248}
249
a61c6782
PB
250static int nbd_can_accept(void *opaque)
251{
252 return nb_fds < shared;
253}
254
1743b515 255static void nbd_client_closed(NBDClient *client)
a61c6782 256{
1743b515
PB
257 nb_fds--;
258 qemu_notify_event();
a61c6782
PB
259}
260
261static void nbd_accept(void *opaque)
262{
263 int server_fd = (uintptr_t) opaque;
264 struct sockaddr_in addr;
265 socklen_t addr_len = sizeof(addr);
266
267 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
268 nbd_started = true;
fc19f8a0 269 if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {
a61c6782
PB
270 nb_fds++;
271 }
272}
273
7a5ca864
FB
274int main(int argc, char **argv)
275{
276 BlockDriverState *bs;
277 off_t dev_offset = 0;
b90fb4b8 278 uint32_t nbdflags = 0;
cd831bd7 279 bool disconnect = false;
7a5ca864 280 const char *bindto = "0.0.0.0";
a6ac2313 281 char *device = NULL;
c2e2872b 282 int port = NBD_DEFAULT_PORT;
7a5ca864 283 off_t fd_size;
d6aa671f 284 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
7a5ca864 285 struct option lopt[] = {
660f11be
BS
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' },
301 { NULL, 0, NULL, 0 }
7a5ca864
FB
302 };
303 int ch;
304 int opt_ind = 0;
305 int li;
306 char *end;
f5edb014 307 int flags = BDRV_O_RDWR;
7a5ca864 308 int partition = -1;
cd831bd7 309 int ret;
3b05a8e9 310 int fd;
75818250 311 int persistent = 0;
a517e88b 312 pthread_t client_thread;
7a5ca864 313
a517e88b
PB
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.
316 */
bb345110 317 struct sigaction sa_sigterm;
bb345110
PB
318 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
319 sa_sigterm.sa_handler = termsig_handler;
320 sigaction(SIGTERM, &sa_sigterm, NULL);
321
7a5ca864
FB
322 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
323 switch (ch) {
324 case 's':
2f726488
TS
325 flags |= BDRV_O_SNAPSHOT;
326 break;
327 case 'n':
a6599793 328 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
7a5ca864
FB
329 break;
330 case 'b':
331 bindto = optarg;
332 break;
333 case 'p':
334 li = strtol(optarg, &end, 0);
335 if (*end) {
b6353bea 336 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
7a5ca864
FB
337 }
338 if (li < 1 || li > 65535) {
b6353bea 339 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
7a5ca864
FB
340 }
341 port = (uint16_t)li;
342 break;
343 case 'o':
344 dev_offset = strtoll (optarg, &end, 0);
345 if (*end) {
b6353bea 346 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
7a5ca864
FB
347 }
348 if (dev_offset < 0) {
b6353bea 349 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
7a5ca864
FB
350 }
351 break;
352 case 'r':
b90fb4b8 353 nbdflags |= NBD_FLAG_READ_ONLY;
07108b29 354 flags &= ~BDRV_O_RDWR;
7a5ca864
FB
355 break;
356 case 'P':
357 partition = strtol(optarg, &end, 0);
358 if (*end)
b6353bea 359 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
7a5ca864 360 if (partition < 1 || partition > 8)
b6353bea 361 errx(EXIT_FAILURE, "Invalid partition %d", partition);
7a5ca864 362 break;
cd831bd7 363 case 'k':
b32f6c28
PB
364 sockpath = optarg;
365 if (sockpath[0] != '/')
b6353bea 366 errx(EXIT_FAILURE, "socket path must be absolute\n");
cd831bd7
TS
367 break;
368 case 'd':
369 disconnect = true;
370 break;
371 case 'c':
372 device = optarg;
373 break;
3b05a8e9
TS
374 case 'e':
375 shared = strtol(optarg, &end, 0);
376 if (*end) {
b6353bea 377 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
3b05a8e9
TS
378 }
379 if (shared < 1) {
b6353bea 380 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
3b05a8e9
TS
381 }
382 break;
75818250
TS
383 case 't':
384 persistent = 1;
385 break;
7a5ca864
FB
386 case 'v':
387 verbose = 1;
388 break;
389 case 'V':
390 version(argv[0]);
391 exit(0);
392 break;
393 case 'h':
394 usage(argv[0]);
395 exit(0);
396 break;
397 case '?':
b6353bea 398 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
7a5ca864
FB
399 argv[0]);
400 }
401 }
402
403 if ((argc - optind) != 1) {
b6353bea 404 errx(EXIT_FAILURE, "Invalid number of argument.\n"
7a5ca864
FB
405 "Try `%s --help' for more information.",
406 argv[0]);
407 }
408
cd831bd7
TS
409 if (disconnect) {
410 fd = open(argv[optind], O_RDWR);
fc19f8a0 411 if (fd < 0) {
cb7cf0e3 412 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
fc19f8a0 413 }
cd831bd7
TS
414 nbd_disconnect(fd);
415
416 close(fd);
417
418 printf("%s disconnected\n", argv[optind]);
419
420 return 0;
421 }
422
c1f8fdc3
PB
423 if (device && !verbose) {
424 int stderr_fd[2];
425 pid_t pid;
426 int ret;
427
fc19f8a0 428 if (qemu_pipe(stderr_fd) < 0) {
c1f8fdc3
PB
429 err(EXIT_FAILURE, "Error setting up communication pipe");
430 }
431
432 /* Now daemonize, but keep a communication channel open to
433 * print errors and exit with the proper status code.
434 */
435 pid = fork();
436 if (pid == 0) {
437 close(stderr_fd[0]);
9faf31b6 438 ret = qemu_daemon(1, 0);
c1f8fdc3
PB
439
440 /* Temporarily redirect stderr to the parent's pipe... */
441 dup2(stderr_fd[1], STDERR_FILENO);
fc19f8a0 442 if (ret < 0) {
c1f8fdc3
PB
443 err(EXIT_FAILURE, "Failed to daemonize");
444 }
445
446 /* ... close the descriptor we inherited and go on. */
447 close(stderr_fd[1]);
448 } else {
449 bool errors = false;
450 char *buf;
451
452 /* In the parent. Print error messages from the child until
453 * it closes the pipe.
454 */
455 close(stderr_fd[1]);
456 buf = g_malloc(1024);
457 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
458 errors = true;
459 ret = qemu_write_full(STDERR_FILENO, buf, ret);
fc19f8a0 460 if (ret < 0) {
c1f8fdc3
PB
461 exit(EXIT_FAILURE);
462 }
463 }
fc19f8a0 464 if (ret < 0) {
c1f8fdc3
PB
465 err(EXIT_FAILURE, "Cannot read from daemon");
466 }
467
468 /* Usually the daemon should not print any message.
469 * Exit with zero status in that case.
470 */
471 exit(errors);
472 }
473 }
474
a6ac2313
PB
475 if (device != NULL && sockpath == NULL) {
476 sockpath = g_malloc(128);
477 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7
TS
478 }
479
802ddc37
PB
480 bdrv_init();
481 atexit(bdrv_close_all);
482
483 bs = bdrv_new("hda");
484 srcpath = argv[optind];
485 if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
486 errno = -ret;
487 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
488 }
489
38ceff04 490 fd_size = bdrv_getlength(bs);
802ddc37 491
185b4338
PB
492 if (partition != -1) {
493 ret = find_partition(bs, partition, &dev_offset, &fd_size);
494 if (ret < 0) {
495 errno = -ret;
496 err(EXIT_FAILURE, "Could not find partition %d", partition);
497 }
802ddc37
PB
498 }
499
af49bbbe 500 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags);
3b05a8e9 501
b32f6c28 502 if (sockpath) {
a61c6782 503 fd = unix_socket_incoming(sockpath);
cd831bd7 504 } else {
a61c6782 505 fd = tcp_socket_incoming(bindto, port);
cd831bd7
TS
506 }
507
fc19f8a0 508 if (fd < 0) {
7a5ca864 509 return 1;
a61c6782 510 }
f1ef5555
PB
511
512 if (device) {
513 int ret;
514
a6ac2313 515 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
f1ef5555
PB
516 if (ret != 0) {
517 errx(EXIT_FAILURE, "Failed to create client thread: %s",
518 strerror(ret));
519 }
520 } else {
521 /* Shut up GCC warnings. */
522 memset(&client_thread, 0, sizeof(client_thread));
523 }
524
a61c6782
PB
525 qemu_init_main_loop();
526 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
527 (void *)(uintptr_t)fd);
7a5ca864 528
9faf31b6
MT
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");
533 }
534
3b05a8e9 535 do {
a61c6782
PB
536 main_loop_wait(false);
537 } while (!sigterm_reported && (persistent || !nbd_started || nb_fds > 0));
7a5ca864 538
af49bbbe 539 nbd_export_close(exp);
b32f6c28
PB
540 if (sockpath) {
541 unlink(sockpath);
542 }
7a5ca864 543
a517e88b
PB
544 if (device) {
545 void *ret;
546 pthread_join(client_thread, &ret);
547 exit(ret != NULL);
548 } else {
549 exit(EXIT_SUCCESS);
550 }
7a5ca864 551}