]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-nbd.c
nbd: Fix potential signed overflow issues
[mirror_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"
26f54e9a 20#include "sysemu/block-backend.h"
b3838a40 21#include "block/block_int.h"
737e150e 22#include "block/nbd.h"
6a1751b7 23#include "qemu/main-loop.h"
537b41f5
PB
24#include "qemu/sockets.h"
25#include "qemu/error-report.h"
8c116b0e 26#include "block/snapshot.h"
b3838a40 27#include "qapi/util.h"
7a5ca864 28
7a5ca864
FB
29#include <stdarg.h>
30#include <stdio.h>
31#include <getopt.h>
32#include <err.h>
cd831bd7 33#include <sys/types.h>
7a5ca864
FB
34#include <sys/socket.h>
35#include <netinet/in.h>
36#include <netinet/tcp.h>
37#include <arpa/inet.h>
cd831bd7 38#include <signal.h>
2bff4b6f 39#include <libgen.h>
a517e88b 40#include <pthread.h>
cd831bd7 41
713cc671
PL
42#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
43#define QEMU_NBD_OPT_CACHE 1
44#define QEMU_NBD_OPT_AIO 2
45#define QEMU_NBD_OPT_DISCARD 3
b3838a40 46#define QEMU_NBD_OPT_DETECT_ZEROES 4
7a5ca864 47
af49bbbe 48static NBDExport *exp;
b1d8e52e 49static int verbose;
a517e88b
PB
50static char *srcpath;
51static char *sockpath;
7860a380
PB
52static int persistent = 0;
53static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
a61c6782
PB
54static int shared = 1;
55static int nb_fds;
7a5ca864
FB
56
57static void usage(const char *name)
58{
b033cd86 59 (printf) (
7a5ca864
FB
60"Usage: %s [OPTIONS] FILE\n"
61"QEMU Disk Network Block Device Server\n"
62"\n"
713cc671
PL
63" -h, --help display this help and exit\n"
64" -V, --version output version information and exit\n"
b033cd86
PB
65"\n"
66"Connection properties:\n"
713cc671
PL
67" -p, --port=PORT port to listen on (default `%d')\n"
68" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
69" -k, --socket=PATH path to the unix socket\n"
70" (default '"SOCKET_PATH"')\n"
71" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
72" -t, --persistent don't exit on the last connection\n"
73" -v, --verbose display extra debugging information\n"
7a5ca864 74"\n"
b033cd86 75"Exposing part of the image:\n"
713cc671
PL
76" -o, --offset=OFFSET offset into the image\n"
77" -P, --partition=NUM only expose partition NUM\n"
b033cd86
PB
78"\n"
79#ifdef __linux__
80"Kernel NBD client support:\n"
713cc671
PL
81" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
82" -d, --disconnect disconnect the specified device\n"
b033cd86
PB
83"\n"
84#endif
85"\n"
86"Block device options:\n"
713cc671
PL
87" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
88" -r, --read-only export read-only\n"
89" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
90" file with backing_file=FILE, redirect the write to\n"
91" the temporary one\n"
8c116b0e 92" -l, --load-snapshot=SNAPSHOT_PARAM\n"
713cc671
PL
93" load an internal snapshot inside FILE and export it\n"
94" as an read-only device, SNAPSHOT_PARAM format is\n"
95" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
96" '[ID_OR_NAME]'\n"
97" -n, --nocache disable host cache\n"
98" --cache=MODE set cache mode (none, writeback, ...)\n"
39a5235c 99#ifdef CONFIG_LINUX_AIO
713cc671 100" --aio=MODE set AIO mode (native or threads)\n"
39a5235c 101#endif
b3838a40
PL
102" --discard=MODE set discard mode (ignore, unmap)\n"
103" --detect-zeroes=MODE set detect-zeroes mode (off, on, discard)\n"
b033cd86
PB
104"\n"
105"Report bugs to <qemu-devel@nongnu.org>\n"
c2e2872b 106 , name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
107}
108
109static void version(const char *name)
110{
111 printf(
315bc7aa 112"%s version 0.0.1\n"
7a5ca864
FB
113"Written by Anthony Liguori.\n"
114"\n"
115"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
116"This is free software; see the source for copying conditions. There is NO\n"
117"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
315bc7aa 118 , name);
7a5ca864
FB
119}
120
121struct partition_record
122{
123 uint8_t bootable;
124 uint8_t start_head;
125 uint32_t start_cylinder;
126 uint8_t start_sector;
127 uint8_t system;
128 uint8_t end_head;
129 uint8_t end_cylinder;
130 uint8_t end_sector;
131 uint32_t start_sector_abs;
132 uint32_t nb_sectors_abs;
133};
134
135static void read_partition(uint8_t *p, struct partition_record *r)
136{
137 r->bootable = p[0];
138 r->start_head = p[1];
139 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
140 r->start_sector = p[2] & 0x3f;
141 r->system = p[4];
142 r->end_head = p[5];
143 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
144 r->end_sector = p[6] & 0x3f;
ac97393d
HR
145
146 r->start_sector_abs = le32_to_cpup((uint32_t *)(p + 8));
147 r->nb_sectors_abs = le32_to_cpup((uint32_t *)(p + 12));
7a5ca864
FB
148}
149
4c58e80a 150static int find_partition(BlockBackend *blk, int partition,
7a5ca864
FB
151 off_t *offset, off_t *size)
152{
153 struct partition_record mbr[4];
154 uint8_t data[512];
155 int i;
156 int ext_partnum = 4;
cb7cf0e3 157 int ret;
7a5ca864 158
4c58e80a 159 if ((ret = blk_read(blk, 0, data, 1)) < 0) {
cb7cf0e3
RO
160 errno = -ret;
161 err(EXIT_FAILURE, "error while reading");
162 }
7a5ca864
FB
163
164 if (data[510] != 0x55 || data[511] != 0xaa) {
185b4338 165 return -EINVAL;
7a5ca864
FB
166 }
167
168 for (i = 0; i < 4; i++) {
169 read_partition(&data[446 + 16 * i], &mbr[i]);
170
453b07b1 171 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
7a5ca864 172 continue;
453b07b1 173 }
7a5ca864
FB
174
175 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
176 struct partition_record ext[4];
177 uint8_t data1[512];
178 int j;
179
4c58e80a 180 if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
cb7cf0e3
RO
181 errno = -ret;
182 err(EXIT_FAILURE, "error while reading");
183 }
7a5ca864
FB
184
185 for (j = 0; j < 4; j++) {
186 read_partition(&data1[446 + 16 * j], &ext[j]);
453b07b1 187 if (!ext[j].system || !ext[j].nb_sectors_abs) {
7a5ca864 188 continue;
453b07b1 189 }
7a5ca864
FB
190
191 if ((ext_partnum + j + 1) == partition) {
192 *offset = (uint64_t)ext[j].start_sector_abs << 9;
193 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
194 return 0;
195 }
196 }
197 ext_partnum += 4;
198 } else if ((i + 1) == partition) {
199 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
200 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
201 return 0;
202 }
203 }
204
185b4338 205 return -ENOENT;
7a5ca864
FB
206}
207
bb345110
PB
208static void termsig_handler(int signum)
209{
7860a380 210 state = TERMINATE;
a61c6782 211 qemu_notify_event();
bb345110
PB
212}
213
537b41f5
PB
214static void combine_addr(char *buf, size_t len, const char* address,
215 uint16_t port)
216{
217 /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
218 if (strstr(address, ":")) {
219 snprintf(buf, len, "[%s]:%u", address, port);
220 } else {
221 snprintf(buf, len, "%s:%u", address, port);
222 }
223}
224
225static int tcp_socket_incoming(const char *address, uint16_t port)
226{
227 char address_and_port[128];
228 Error *local_err = NULL;
229
230 combine_addr(address_and_port, 128, address, port);
231 int fd = inet_listen(address_and_port, NULL, 0, SOCK_STREAM, 0, &local_err);
232
233 if (local_err != NULL) {
565f65d2 234 error_report_err(local_err);
537b41f5
PB
235 }
236 return fd;
237}
238
239static int unix_socket_incoming(const char *path)
240{
241 Error *local_err = NULL;
242 int fd = unix_listen(path, NULL, 0, &local_err);
243
244 if (local_err != NULL) {
565f65d2 245 error_report_err(local_err);
537b41f5
PB
246 }
247 return fd;
248}
249
250static int unix_socket_outgoing(const char *path)
251{
252 Error *local_err = NULL;
253 int fd = unix_connect(path, &local_err);
254
255 if (local_err != NULL) {
565f65d2 256 error_report_err(local_err);
537b41f5
PB
257 }
258 return fd;
259}
260
a517e88b 261static void *show_parts(void *arg)
cd831bd7 262{
a6ac2313 263 char *device = arg;
a517e88b
PB
264 int nbd;
265
266 /* linux just needs an open() to trigger
267 * the partition table update
268 * but remember to load the module with max_part != 0 :
269 * modprobe nbd max_part=63
270 */
271 nbd = open(device, O_RDWR);
fc19f8a0 272 if (nbd >= 0) {
a517e88b
PB
273 close(nbd);
274 }
275 return NULL;
276}
cd831bd7 277
a517e88b
PB
278static void *nbd_client_thread(void *arg)
279{
a6ac2313 280 char *device = arg;
a517e88b
PB
281 off_t size;
282 size_t blocksize;
283 uint32_t nbdflags;
a6ac2313 284 int fd, sock;
a517e88b
PB
285 int ret;
286 pthread_t show_parts_thread;
1ce52846 287 Error *local_error = NULL;
a517e88b 288
dc10e8b3 289 sock = unix_socket_outgoing(sockpath);
fc19f8a0 290 if (sock < 0) {
dc10e8b3
SH
291 goto out;
292 }
a517e88b
PB
293
294 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
1ce52846 295 &size, &blocksize, &local_error);
fc19f8a0 296 if (ret < 0) {
1ce52846
HR
297 if (local_error) {
298 fprintf(stderr, "%s\n", error_get_pretty(local_error));
299 error_free(local_error);
300 }
0c544d73 301 goto out_socket;
a517e88b
PB
302 }
303
a6ac2313 304 fd = open(device, O_RDWR);
fc19f8a0 305 if (fd < 0) {
a6ac2313 306 /* Linux-only, we can use %m in printf. */
5672ee54 307 fprintf(stderr, "Failed to open %s: %m\n", device);
0c544d73 308 goto out_socket;
a6ac2313
PB
309 }
310
a517e88b 311 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
fc19f8a0 312 if (ret < 0) {
0c544d73 313 goto out_fd;
a517e88b
PB
314 }
315
316 /* update partition table */
a6ac2313 317 pthread_create(&show_parts_thread, NULL, show_parts, device);
a517e88b 318
c1f8fdc3
PB
319 if (verbose) {
320 fprintf(stderr, "NBD device %s is now connected to %s\n",
321 device, srcpath);
322 } else {
323 /* Close stderr so that the qemu-nbd process exits. */
324 dup2(STDOUT_FILENO, STDERR_FILENO);
325 }
a517e88b
PB
326
327 ret = nbd_client(fd);
328 if (ret) {
0c544d73 329 goto out_fd;
cd831bd7 330 }
a517e88b
PB
331 close(fd);
332 kill(getpid(), SIGTERM);
333 return (void *) EXIT_SUCCESS;
334
0c544d73
PB
335out_fd:
336 close(fd);
337out_socket:
338 closesocket(sock);
a517e88b
PB
339out:
340 kill(getpid(), SIGTERM);
341 return (void *) EXIT_FAILURE;
cd831bd7
TS
342}
343
a61c6782
PB
344static int nbd_can_accept(void *opaque)
345{
346 return nb_fds < shared;
347}
348
7860a380
PB
349static void nbd_export_closed(NBDExport *exp)
350{
351 assert(state == TERMINATING);
352 state = TERMINATED;
353}
354
1743b515 355static void nbd_client_closed(NBDClient *client)
a61c6782 356{
1743b515 357 nb_fds--;
7860a380
PB
358 if (nb_fds == 0 && !persistent && state == RUNNING) {
359 state = TERMINATE;
360 }
1743b515 361 qemu_notify_event();
7860a380 362 nbd_client_put(client);
a61c6782
PB
363}
364
365static void nbd_accept(void *opaque)
366{
367 int server_fd = (uintptr_t) opaque;
368 struct sockaddr_in addr;
369 socklen_t addr_len = sizeof(addr);
370
371 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
0c544d73
PB
372 if (fd < 0) {
373 perror("accept");
374 return;
375 }
376
7860a380
PB
377 if (state >= TERMINATE) {
378 close(fd);
379 return;
380 }
381
36af5994 382 if (nbd_client_new(exp, fd, nbd_client_closed)) {
a61c6782 383 nb_fds++;
36af5994 384 } else {
27e5eae4 385 shutdown(fd, 2);
36af5994 386 close(fd);
a61c6782
PB
387 }
388}
389
7a5ca864
FB
390int main(int argc, char **argv)
391{
26f54e9a 392 BlockBackend *blk;
7a5ca864
FB
393 BlockDriverState *bs;
394 off_t dev_offset = 0;
b90fb4b8 395 uint32_t nbdflags = 0;
cd831bd7 396 bool disconnect = false;
7a5ca864 397 const char *bindto = "0.0.0.0";
a6ac2313 398 char *device = NULL;
c2e2872b 399 int port = NBD_DEFAULT_PORT;
7a5ca864 400 off_t fd_size;
8c116b0e
WX
401 QemuOpts *sn_opts = NULL;
402 const char *sn_id_or_name = NULL;
403 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
7a5ca864 404 struct option lopt[] = {
660f11be
BS
405 { "help", 0, NULL, 'h' },
406 { "version", 0, NULL, 'V' },
407 { "bind", 1, NULL, 'b' },
408 { "port", 1, NULL, 'p' },
409 { "socket", 1, NULL, 'k' },
410 { "offset", 1, NULL, 'o' },
411 { "read-only", 0, NULL, 'r' },
412 { "partition", 1, NULL, 'P' },
413 { "connect", 1, NULL, 'c' },
414 { "disconnect", 0, NULL, 'd' },
415 { "snapshot", 0, NULL, 's' },
8c116b0e 416 { "load-snapshot", 1, NULL, 'l' },
660f11be 417 { "nocache", 0, NULL, 'n' },
39a5235c
PB
418 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
419#ifdef CONFIG_LINUX_AIO
420 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
421#endif
ded9d2d5 422 { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
b3838a40 423 { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
660f11be 424 { "shared", 1, NULL, 'e' },
e6b63677 425 { "format", 1, NULL, 'f' },
660f11be
BS
426 { "persistent", 0, NULL, 't' },
427 { "verbose", 0, NULL, 'v' },
428 { NULL, 0, NULL, 0 }
7a5ca864
FB
429 };
430 int ch;
431 int opt_ind = 0;
432 int li;
433 char *end;
f5edb014 434 int flags = BDRV_O_RDWR;
7a5ca864 435 int partition = -1;
4fbec260 436 int ret = 0;
3b05a8e9 437 int fd;
39a5235c 438 bool seen_cache = false;
ded9d2d5 439 bool seen_discard = false;
39a5235c
PB
440#ifdef CONFIG_LINUX_AIO
441 bool seen_aio = false;
442#endif
a517e88b 443 pthread_t client_thread;
e6b63677 444 const char *fmt = NULL;
34b5d2c6 445 Error *local_err = NULL;
b3838a40 446 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
4fbec260 447 QDict *options = NULL;
7a5ca864 448
a517e88b
PB
449 /* The client thread uses SIGTERM to interrupt the server. A signal
450 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
451 */
bb345110 452 struct sigaction sa_sigterm;
bb345110
PB
453 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
454 sa_sigterm.sa_handler = termsig_handler;
455 sigaction(SIGTERM, &sa_sigterm, NULL);
10f5bff6 456 qemu_init_exec_dir(argv[0]);
bb345110 457
7a5ca864
FB
458 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
459 switch (ch) {
460 case 's':
2f726488
TS
461 flags |= BDRV_O_SNAPSHOT;
462 break;
463 case 'n':
39a5235c
PB
464 optarg = (char *) "none";
465 /* fallthrough */
466 case QEMU_NBD_OPT_CACHE:
467 if (seen_cache) {
468 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
469 }
470 seen_cache = true;
471 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
472 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
473 }
7a5ca864 474 break;
39a5235c
PB
475#ifdef CONFIG_LINUX_AIO
476 case QEMU_NBD_OPT_AIO:
477 if (seen_aio) {
478 errx(EXIT_FAILURE, "--aio can only be specified once");
479 }
480 seen_aio = true;
481 if (!strcmp(optarg, "native")) {
482 flags |= BDRV_O_NATIVE_AIO;
483 } else if (!strcmp(optarg, "threads")) {
484 /* this is the default */
485 } else {
486 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
487 }
488 break;
489#endif
ded9d2d5
PB
490 case QEMU_NBD_OPT_DISCARD:
491 if (seen_discard) {
492 errx(EXIT_FAILURE, "--discard can only be specified once");
493 }
494 seen_discard = true;
495 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
496 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
497 }
498 break;
b3838a40
PL
499 case QEMU_NBD_OPT_DETECT_ZEROES:
500 detect_zeroes =
501 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
502 optarg,
503 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
504 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
505 &local_err);
506 if (local_err) {
507 errx(EXIT_FAILURE, "Failed to parse detect_zeroes mode: %s",
508 error_get_pretty(local_err));
509 }
510 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
511 !(flags & BDRV_O_UNMAP)) {
512 errx(EXIT_FAILURE, "setting detect-zeroes to unmap is not allowed "
513 "without setting discard operation to unmap");
514 }
515 break;
7a5ca864
FB
516 case 'b':
517 bindto = optarg;
518 break;
519 case 'p':
520 li = strtol(optarg, &end, 0);
521 if (*end) {
b6353bea 522 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
7a5ca864
FB
523 }
524 if (li < 1 || li > 65535) {
b6353bea 525 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
7a5ca864
FB
526 }
527 port = (uint16_t)li;
528 break;
529 case 'o':
530 dev_offset = strtoll (optarg, &end, 0);
531 if (*end) {
b6353bea 532 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
7a5ca864
FB
533 }
534 if (dev_offset < 0) {
b6353bea 535 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
7a5ca864
FB
536 }
537 break;
8c116b0e
WX
538 case 'l':
539 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
540 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
541 if (!sn_opts) {
542 errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
543 optarg);
544 }
545 } else {
546 sn_id_or_name = optarg;
547 }
548 /* fall through */
7a5ca864 549 case 'r':
b90fb4b8 550 nbdflags |= NBD_FLAG_READ_ONLY;
07108b29 551 flags &= ~BDRV_O_RDWR;
7a5ca864
FB
552 break;
553 case 'P':
554 partition = strtol(optarg, &end, 0);
713cc671 555 if (*end) {
b6353bea 556 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
713cc671
PL
557 }
558 if (partition < 1 || partition > 8) {
b6353bea 559 errx(EXIT_FAILURE, "Invalid partition %d", partition);
713cc671 560 }
7a5ca864 561 break;
cd831bd7 562 case 'k':
b32f6c28 563 sockpath = optarg;
713cc671 564 if (sockpath[0] != '/') {
b6353bea 565 errx(EXIT_FAILURE, "socket path must be absolute\n");
713cc671 566 }
cd831bd7
TS
567 break;
568 case 'd':
569 disconnect = true;
570 break;
571 case 'c':
572 device = optarg;
573 break;
3b05a8e9
TS
574 case 'e':
575 shared = strtol(optarg, &end, 0);
576 if (*end) {
b6353bea 577 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
3b05a8e9
TS
578 }
579 if (shared < 1) {
b6353bea 580 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
3b05a8e9
TS
581 }
582 break;
e6b63677
DB
583 case 'f':
584 fmt = optarg;
585 break;
713cc671
PL
586 case 't':
587 persistent = 1;
588 break;
7a5ca864
FB
589 case 'v':
590 verbose = 1;
591 break;
592 case 'V':
593 version(argv[0]);
594 exit(0);
595 break;
596 case 'h':
597 usage(argv[0]);
598 exit(0);
599 break;
600 case '?':
b6353bea 601 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
7a5ca864
FB
602 argv[0]);
603 }
604 }
605
606 if ((argc - optind) != 1) {
b6353bea 607 errx(EXIT_FAILURE, "Invalid number of argument.\n"
7a5ca864
FB
608 "Try `%s --help' for more information.",
609 argv[0]);
610 }
611
cd831bd7
TS
612 if (disconnect) {
613 fd = open(argv[optind], O_RDWR);
fc19f8a0 614 if (fd < 0) {
cb7cf0e3 615 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
fc19f8a0 616 }
cd831bd7
TS
617 nbd_disconnect(fd);
618
619 close(fd);
620
621 printf("%s disconnected\n", argv[optind]);
622
713cc671 623 return 0;
cd831bd7
TS
624 }
625
c1f8fdc3
PB
626 if (device && !verbose) {
627 int stderr_fd[2];
628 pid_t pid;
629 int ret;
630
fc19f8a0 631 if (qemu_pipe(stderr_fd) < 0) {
c1f8fdc3
PB
632 err(EXIT_FAILURE, "Error setting up communication pipe");
633 }
634
635 /* Now daemonize, but keep a communication channel open to
636 * print errors and exit with the proper status code.
637 */
638 pid = fork();
70d4739e
HR
639 if (pid < 0) {
640 err(EXIT_FAILURE, "Failed to fork");
641 } else if (pid == 0) {
c1f8fdc3 642 close(stderr_fd[0]);
9faf31b6 643 ret = qemu_daemon(1, 0);
c1f8fdc3
PB
644
645 /* Temporarily redirect stderr to the parent's pipe... */
646 dup2(stderr_fd[1], STDERR_FILENO);
fc19f8a0 647 if (ret < 0) {
c1f8fdc3
PB
648 err(EXIT_FAILURE, "Failed to daemonize");
649 }
650
651 /* ... close the descriptor we inherited and go on. */
652 close(stderr_fd[1]);
653 } else {
654 bool errors = false;
655 char *buf;
656
657 /* In the parent. Print error messages from the child until
658 * it closes the pipe.
659 */
660 close(stderr_fd[1]);
661 buf = g_malloc(1024);
662 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
663 errors = true;
664 ret = qemu_write_full(STDERR_FILENO, buf, ret);
fc19f8a0 665 if (ret < 0) {
c1f8fdc3
PB
666 exit(EXIT_FAILURE);
667 }
668 }
fc19f8a0 669 if (ret < 0) {
c1f8fdc3
PB
670 err(EXIT_FAILURE, "Cannot read from daemon");
671 }
672
673 /* Usually the daemon should not print any message.
674 * Exit with zero status in that case.
675 */
676 exit(errors);
677 }
678 }
679
a6ac2313
PB
680 if (device != NULL && sockpath == NULL) {
681 sockpath = g_malloc(128);
682 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7
TS
683 }
684
2f78e491 685 if (qemu_init_main_loop(&local_err)) {
565f65d2 686 error_report_err(local_err);
2f78e491
CN
687 exit(EXIT_FAILURE);
688 }
802ddc37
PB
689 bdrv_init();
690 atexit(bdrv_close_all);
691
e6b63677 692 if (fmt) {
4fbec260
HR
693 options = qdict_new();
694 qdict_put(options, "driver", qstring_from_str(fmt));
e6b63677
DB
695 }
696
802ddc37 697 srcpath = argv[optind];
4fbec260
HR
698 blk = blk_new_open("hda", srcpath, NULL, options, flags, &local_err);
699 if (!blk) {
700 errx(EXIT_FAILURE, "Failed to blk_new_open '%s': %s", argv[optind],
701 error_get_pretty(local_err));
802ddc37 702 }
4fbec260 703 bs = blk_bs(blk);
802ddc37 704
8c116b0e
WX
705 if (sn_opts) {
706 ret = bdrv_snapshot_load_tmp(bs,
707 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
708 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
709 &local_err);
710 } else if (sn_id_or_name) {
711 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
712 &local_err);
713 }
714 if (ret < 0) {
715 errno = -ret;
716 err(EXIT_FAILURE,
717 "Failed to load snapshot: %s",
718 error_get_pretty(local_err));
719 }
720
b3838a40 721 bs->detect_zeroes = detect_zeroes;
4c58e80a 722 fd_size = blk_getlength(blk);
98f44bbe
HR
723 if (fd_size < 0) {
724 errx(EXIT_FAILURE, "Failed to determine the image length: %s",
725 strerror(-fd_size));
726 }
802ddc37 727
185b4338 728 if (partition != -1) {
4c58e80a 729 ret = find_partition(blk, partition, &dev_offset, &fd_size);
185b4338
PB
730 if (ret < 0) {
731 errno = -ret;
732 err(EXIT_FAILURE, "Could not find partition %d", partition);
733 }
802ddc37
PB
734 }
735
98f44bbe
HR
736 exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
737 &local_err);
738 if (!exp) {
739 errx(EXIT_FAILURE, "%s", error_get_pretty(local_err));
740 }
3b05a8e9 741
b32f6c28 742 if (sockpath) {
a61c6782 743 fd = unix_socket_incoming(sockpath);
cd831bd7 744 } else {
a61c6782 745 fd = tcp_socket_incoming(bindto, port);
cd831bd7
TS
746 }
747
fc19f8a0 748 if (fd < 0) {
7a5ca864 749 return 1;
a61c6782 750 }
f1ef5555
PB
751
752 if (device) {
753 int ret;
754
a6ac2313 755 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
f1ef5555
PB
756 if (ret != 0) {
757 errx(EXIT_FAILURE, "Failed to create client thread: %s",
758 strerror(ret));
759 }
760 } else {
761 /* Shut up GCC warnings. */
762 memset(&client_thread, 0, sizeof(client_thread));
763 }
764
a61c6782
PB
765 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
766 (void *)(uintptr_t)fd);
7a5ca864 767
9faf31b6
MT
768 /* now when the initialization is (almost) complete, chdir("/")
769 * to free any busy filesystems */
770 if (chdir("/") < 0) {
771 err(EXIT_FAILURE, "Could not chdir to root directory");
772 }
773
7860a380 774 state = RUNNING;
3b05a8e9 775 do {
a61c6782 776 main_loop_wait(false);
7860a380
PB
777 if (state == TERMINATE) {
778 state = TERMINATING;
779 nbd_export_close(exp);
780 nbd_export_put(exp);
781 exp = NULL;
782 }
783 } while (state != TERMINATED);
7a5ca864 784
26f54e9a 785 blk_unref(blk);
b32f6c28
PB
786 if (sockpath) {
787 unlink(sockpath);
788 }
7a5ca864 789
fbf28a43 790 qemu_opts_del(sn_opts);
8c116b0e 791
a517e88b
PB
792 if (device) {
793 void *ret;
794 pthread_join(client_thread, &ret);
795 exit(ret != NULL);
796 } else {
797 exit(EXIT_SUCCESS);
798 }
7a5ca864 799}