]> git.proxmox.com Git - qemu.git/blame - qemu-nbd.c
link the main loop and its dependencies into the tools
[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"
7a5ca864
FB
20#include "block_int.h"
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
bb345110 38static int sigterm_wfd;
af49bbbe 39static NBDExport *exp;
b1d8e52e 40static int verbose;
a517e88b
PB
41static char *device;
42static char *srcpath;
43static char *sockpath;
7a5ca864
FB
44
45static void usage(const char *name)
46{
47 printf(
48"Usage: %s [OPTIONS] FILE\n"
49"QEMU Disk Network Block Device Server\n"
50"\n"
c2e2872b 51" -p, --port=PORT port to listen on (default `%d')\n"
7a5ca864
FB
52" -o, --offset=OFFSET offset into the image\n"
53" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
cd831bd7
TS
54" -k, --socket=PATH path to the unix socket\n"
55" (default '"SOCKET_PATH"')\n"
7a5ca864
FB
56" -r, --read-only export read-only\n"
57" -P, --partition=NUM only expose partition NUM\n"
2f726488
TS
58" -s, --snapshot use snapshot file\n"
59" -n, --nocache disable host cache\n"
cd831bd7
TS
60" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
61" -d, --disconnect disconnect the specified device\n"
3b05a8e9 62" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
75818250 63" -t, --persistent don't exit on the last connection\n"
7a5ca864
FB
64" -v, --verbose display extra debugging information\n"
65" -h, --help display this help and exit\n"
66" -V, --version output version information and exit\n"
67"\n"
68"Report bugs to <anthony@codemonkey.ws>\n"
c2e2872b 69 , name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
70}
71
72static void version(const char *name)
73{
74 printf(
315bc7aa 75"%s version 0.0.1\n"
7a5ca864
FB
76"Written by Anthony Liguori.\n"
77"\n"
78"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
79"This is free software; see the source for copying conditions. There is NO\n"
80"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
315bc7aa 81 , name);
7a5ca864
FB
82}
83
84struct partition_record
85{
86 uint8_t bootable;
87 uint8_t start_head;
88 uint32_t start_cylinder;
89 uint8_t start_sector;
90 uint8_t system;
91 uint8_t end_head;
92 uint8_t end_cylinder;
93 uint8_t end_sector;
94 uint32_t start_sector_abs;
95 uint32_t nb_sectors_abs;
96};
97
98static void read_partition(uint8_t *p, struct partition_record *r)
99{
100 r->bootable = p[0];
101 r->start_head = p[1];
102 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
103 r->start_sector = p[2] & 0x3f;
104 r->system = p[4];
105 r->end_head = p[5];
106 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
107 r->end_sector = p[6] & 0x3f;
108 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
109 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
110}
111
112static int find_partition(BlockDriverState *bs, int partition,
113 off_t *offset, off_t *size)
114{
115 struct partition_record mbr[4];
116 uint8_t data[512];
117 int i;
118 int ext_partnum = 4;
cb7cf0e3 119 int ret;
7a5ca864 120
cb7cf0e3
RO
121 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
122 errno = -ret;
123 err(EXIT_FAILURE, "error while reading");
124 }
7a5ca864
FB
125
126 if (data[510] != 0x55 || data[511] != 0xaa) {
127 errno = -EINVAL;
128 return -1;
129 }
130
131 for (i = 0; i < 4; i++) {
132 read_partition(&data[446 + 16 * i], &mbr[i]);
133
134 if (!mbr[i].nb_sectors_abs)
135 continue;
136
137 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
138 struct partition_record ext[4];
139 uint8_t data1[512];
140 int j;
141
cb7cf0e3
RO
142 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
143 errno = -ret;
144 err(EXIT_FAILURE, "error while reading");
145 }
7a5ca864
FB
146
147 for (j = 0; j < 4; j++) {
148 read_partition(&data1[446 + 16 * j], &ext[j]);
149 if (!ext[j].nb_sectors_abs)
150 continue;
151
152 if ((ext_partnum + j + 1) == partition) {
153 *offset = (uint64_t)ext[j].start_sector_abs << 9;
154 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
155 return 0;
156 }
157 }
158 ext_partnum += 4;
159 } else if ((i + 1) == partition) {
160 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
161 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
162 return 0;
163 }
164 }
165
166 errno = -ENOENT;
167 return -1;
168}
169
bb345110
PB
170static void termsig_handler(int signum)
171{
172 static int sigterm_reported;
173 if (!sigterm_reported) {
174 sigterm_reported = (write(sigterm_wfd, "", 1) == 1);
175 }
176}
177
a517e88b 178static void *show_parts(void *arg)
cd831bd7 179{
a517e88b
PB
180 int nbd;
181
182 /* linux just needs an open() to trigger
183 * the partition table update
184 * but remember to load the module with max_part != 0 :
185 * modprobe nbd max_part=63
186 */
187 nbd = open(device, O_RDWR);
188 if (nbd != -1) {
189 close(nbd);
190 }
191 return NULL;
192}
cd831bd7 193
a517e88b
PB
194static void *nbd_client_thread(void *arg)
195{
196 int fd = *(int *)arg;
197 off_t size;
198 size_t blocksize;
199 uint32_t nbdflags;
200 int sock;
201 int ret;
202 pthread_t show_parts_thread;
203
204 do {
205 sock = unix_socket_outgoing(sockpath);
206 if (sock == -1) {
f1ef5555 207 goto out;
a517e88b
PB
208 }
209 } while (sock == -1);
210
211 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
212 &size, &blocksize);
213 if (ret == -1) {
214 goto out;
215 }
216
217 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
218 if (ret == -1) {
219 goto out;
220 }
221
222 /* update partition table */
223 pthread_create(&show_parts_thread, NULL, show_parts, NULL);
224
c1f8fdc3
PB
225 if (verbose) {
226 fprintf(stderr, "NBD device %s is now connected to %s\n",
227 device, srcpath);
228 } else {
229 /* Close stderr so that the qemu-nbd process exits. */
230 dup2(STDOUT_FILENO, STDERR_FILENO);
231 }
a517e88b
PB
232
233 ret = nbd_client(fd);
234 if (ret) {
235 goto out;
cd831bd7 236 }
a517e88b
PB
237 close(fd);
238 kill(getpid(), SIGTERM);
239 return (void *) EXIT_SUCCESS;
240
241out:
242 kill(getpid(), SIGTERM);
243 return (void *) EXIT_FAILURE;
cd831bd7
TS
244}
245
7a5ca864
FB
246int main(int argc, char **argv)
247{
248 BlockDriverState *bs;
249 off_t dev_offset = 0;
b90fb4b8 250 uint32_t nbdflags = 0;
cd831bd7 251 bool disconnect = false;
7a5ca864 252 const char *bindto = "0.0.0.0";
c2e2872b 253 int port = NBD_DEFAULT_PORT;
7a5ca864
FB
254 struct sockaddr_in addr;
255 socklen_t addr_len = sizeof(addr);
256 off_t fd_size;
d6aa671f 257 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
7a5ca864 258 struct option lopt[] = {
660f11be
BS
259 { "help", 0, NULL, 'h' },
260 { "version", 0, NULL, 'V' },
261 { "bind", 1, NULL, 'b' },
262 { "port", 1, NULL, 'p' },
263 { "socket", 1, NULL, 'k' },
264 { "offset", 1, NULL, 'o' },
265 { "read-only", 0, NULL, 'r' },
266 { "partition", 1, NULL, 'P' },
267 { "connect", 1, NULL, 'c' },
268 { "disconnect", 0, NULL, 'd' },
269 { "snapshot", 0, NULL, 's' },
270 { "nocache", 0, NULL, 'n' },
271 { "shared", 1, NULL, 'e' },
272 { "persistent", 0, NULL, 't' },
273 { "verbose", 0, NULL, 'v' },
274 { NULL, 0, NULL, 0 }
7a5ca864
FB
275 };
276 int ch;
277 int opt_ind = 0;
278 int li;
279 char *end;
f5edb014 280 int flags = BDRV_O_RDWR;
7a5ca864 281 int partition = -1;
cd831bd7 282 int ret;
3b05a8e9 283 int shared = 1;
3b05a8e9
TS
284 fd_set fds;
285 int *sharing_fds;
286 int fd;
287 int i;
288 int nb_fds = 0;
289 int max_fd;
75818250 290 int persistent = 0;
a517e88b 291 pthread_t client_thread;
7a5ca864 292
a517e88b
PB
293 /* The client thread uses SIGTERM to interrupt the server. A signal
294 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
295 */
bb345110
PB
296 struct sigaction sa_sigterm;
297 int sigterm_fd[2];
298 if (qemu_pipe(sigterm_fd) == -1) {
299 err(EXIT_FAILURE, "Error setting up communication pipe");
300 }
301
302 sigterm_wfd = sigterm_fd[1];
303 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
304 sa_sigterm.sa_handler = termsig_handler;
305 sigaction(SIGTERM, &sa_sigterm, NULL);
306
7a5ca864
FB
307 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
308 switch (ch) {
309 case 's':
2f726488
TS
310 flags |= BDRV_O_SNAPSHOT;
311 break;
312 case 'n':
a6599793 313 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
7a5ca864
FB
314 break;
315 case 'b':
316 bindto = optarg;
317 break;
318 case 'p':
319 li = strtol(optarg, &end, 0);
320 if (*end) {
b6353bea 321 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
7a5ca864
FB
322 }
323 if (li < 1 || li > 65535) {
b6353bea 324 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
7a5ca864
FB
325 }
326 port = (uint16_t)li;
327 break;
328 case 'o':
329 dev_offset = strtoll (optarg, &end, 0);
330 if (*end) {
b6353bea 331 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
7a5ca864
FB
332 }
333 if (dev_offset < 0) {
b6353bea 334 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
7a5ca864
FB
335 }
336 break;
337 case 'r':
b90fb4b8 338 nbdflags |= NBD_FLAG_READ_ONLY;
07108b29 339 flags &= ~BDRV_O_RDWR;
7a5ca864
FB
340 break;
341 case 'P':
342 partition = strtol(optarg, &end, 0);
343 if (*end)
b6353bea 344 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
7a5ca864 345 if (partition < 1 || partition > 8)
b6353bea 346 errx(EXIT_FAILURE, "Invalid partition %d", partition);
7a5ca864 347 break;
cd831bd7 348 case 'k':
b32f6c28
PB
349 sockpath = optarg;
350 if (sockpath[0] != '/')
b6353bea 351 errx(EXIT_FAILURE, "socket path must be absolute\n");
cd831bd7
TS
352 break;
353 case 'd':
354 disconnect = true;
355 break;
356 case 'c':
357 device = optarg;
358 break;
3b05a8e9
TS
359 case 'e':
360 shared = strtol(optarg, &end, 0);
361 if (*end) {
b6353bea 362 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
3b05a8e9
TS
363 }
364 if (shared < 1) {
b6353bea 365 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
3b05a8e9
TS
366 }
367 break;
75818250
TS
368 case 't':
369 persistent = 1;
370 break;
7a5ca864
FB
371 case 'v':
372 verbose = 1;
373 break;
374 case 'V':
375 version(argv[0]);
376 exit(0);
377 break;
378 case 'h':
379 usage(argv[0]);
380 exit(0);
381 break;
382 case '?':
b6353bea 383 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
7a5ca864
FB
384 argv[0]);
385 }
386 }
387
388 if ((argc - optind) != 1) {
b6353bea 389 errx(EXIT_FAILURE, "Invalid number of argument.\n"
7a5ca864
FB
390 "Try `%s --help' for more information.",
391 argv[0]);
392 }
393
cd831bd7
TS
394 if (disconnect) {
395 fd = open(argv[optind], O_RDWR);
396 if (fd == -1)
cb7cf0e3 397 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
cd831bd7
TS
398
399 nbd_disconnect(fd);
400
401 close(fd);
402
403 printf("%s disconnected\n", argv[optind]);
404
405 return 0;
406 }
407
c1f8fdc3
PB
408 if (device && !verbose) {
409 int stderr_fd[2];
410 pid_t pid;
411 int ret;
412
413 if (qemu_pipe(stderr_fd) == -1) {
414 err(EXIT_FAILURE, "Error setting up communication pipe");
415 }
416
417 /* Now daemonize, but keep a communication channel open to
418 * print errors and exit with the proper status code.
419 */
420 pid = fork();
421 if (pid == 0) {
422 close(stderr_fd[0]);
423 ret = qemu_daemon(0, 0);
424
425 /* Temporarily redirect stderr to the parent's pipe... */
426 dup2(stderr_fd[1], STDERR_FILENO);
427 if (ret == -1) {
428 err(EXIT_FAILURE, "Failed to daemonize");
429 }
430
431 /* ... close the descriptor we inherited and go on. */
432 close(stderr_fd[1]);
433 } else {
434 bool errors = false;
435 char *buf;
436
437 /* In the parent. Print error messages from the child until
438 * it closes the pipe.
439 */
440 close(stderr_fd[1]);
441 buf = g_malloc(1024);
442 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
443 errors = true;
444 ret = qemu_write_full(STDERR_FILENO, buf, ret);
445 if (ret == -1) {
446 exit(EXIT_FAILURE);
447 }
448 }
449 if (ret == -1) {
450 err(EXIT_FAILURE, "Cannot read from daemon");
451 }
452
453 /* Usually the daemon should not print any message.
454 * Exit with zero status in that case.
455 */
456 exit(errors);
457 }
458 }
459
cd831bd7 460 if (device) {
a517e88b
PB
461 /* Open before spawning new threads. In the future, we may
462 * drop privileges after opening.
463 */
464 fd = open(device, O_RDWR);
465 if (fd == -1) {
466 err(EXIT_FAILURE, "Failed to open %s", device);
cb7cf0e3
RO
467 }
468
b32f6c28
PB
469 if (sockpath == NULL) {
470 sockpath = g_malloc(128);
471 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7 472 }
cd831bd7
TS
473 }
474
802ddc37
PB
475 bdrv_init();
476 atexit(bdrv_close_all);
477
478 bs = bdrv_new("hda");
479 srcpath = argv[optind];
480 if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
481 errno = -ret;
482 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
483 }
484
485 fd_size = bs->total_sectors * 512;
486
487 if (partition != -1 &&
488 find_partition(bs, partition, &dev_offset, &fd_size)) {
489 err(EXIT_FAILURE, "Could not find partition %d", partition);
490 }
491
af49bbbe 492 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags);
7267c094 493 sharing_fds = g_malloc((shared + 1) * sizeof(int));
3b05a8e9 494
b32f6c28
PB
495 if (sockpath) {
496 sharing_fds[0] = unix_socket_incoming(sockpath);
cd831bd7 497 } else {
3b05a8e9 498 sharing_fds[0] = tcp_socket_incoming(bindto, port);
cd831bd7
TS
499 }
500
3b05a8e9 501 if (sharing_fds[0] == -1)
7a5ca864 502 return 1;
f1ef5555
PB
503
504 if (device) {
505 int ret;
506
507 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &fd);
508 if (ret != 0) {
509 errx(EXIT_FAILURE, "Failed to create client thread: %s",
510 strerror(ret));
511 }
512 } else {
513 /* Shut up GCC warnings. */
514 memset(&client_thread, 0, sizeof(client_thread));
515 }
516
3b05a8e9
TS
517 max_fd = sharing_fds[0];
518 nb_fds++;
7a5ca864 519
3b05a8e9 520 do {
3b05a8e9 521 FD_ZERO(&fds);
bb345110 522 FD_SET(sigterm_fd[0], &fds);
3b05a8e9
TS
523 for (i = 0; i < nb_fds; i++)
524 FD_SET(sharing_fds[i], &fds);
525
bb345110
PB
526 do {
527 ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
528 } while (ret == -1 && errno == EINTR);
529 if (ret == -1 || FD_ISSET(sigterm_fd[0], &fds)) {
3b05a8e9 530 break;
bb345110 531 }
3b05a8e9
TS
532
533 if (FD_ISSET(sharing_fds[0], &fds))
534 ret--;
535 for (i = 1; i < nb_fds && ret; i++) {
536 if (FD_ISSET(sharing_fds[i], &fds)) {
af49bbbe 537 if (nbd_trip(exp, sharing_fds[i]) != 0) {
3b05a8e9
TS
538 close(sharing_fds[i]);
539 nb_fds--;
540 sharing_fds[i] = sharing_fds[nb_fds];
541 i--;
542 }
543 ret--;
544 }
545 }
546 /* new connection ? */
547 if (FD_ISSET(sharing_fds[0], &fds)) {
548 if (nb_fds < shared + 1) {
549 sharing_fds[nb_fds] = accept(sharing_fds[0],
550 (struct sockaddr *)&addr,
551 &addr_len);
552 if (sharing_fds[nb_fds] != -1 &&
af49bbbe 553 nbd_negotiate(exp, sharing_fds[nb_fds]) != -1) {
3b05a8e9
TS
554 if (sharing_fds[nb_fds] > max_fd)
555 max_fd = sharing_fds[nb_fds];
556 nb_fds++;
557 }
558 }
559 }
75818250 560 } while (persistent || nb_fds > 1);
7a5ca864 561
3b05a8e9 562 close(sharing_fds[0]);
af49bbbe 563 nbd_export_close(exp);
7267c094 564 g_free(sharing_fds);
b32f6c28
PB
565 if (sockpath) {
566 unlink(sockpath);
567 }
7a5ca864 568
a517e88b
PB
569 if (device) {
570 void *ret;
571 pthread_join(client_thread, &ret);
572 exit(ret != NULL);
573 } else {
574 exit(EXIT_SUCCESS);
575 }
7a5ca864 576}