qemu-nbd.c 15 KB

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