2
0

qemu-nbd.c 23 KB

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