qemu-nbd.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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/osdep.h"
  19. #include "qemu-common.h"
  20. #include "sysemu/block-backend.h"
  21. #include "block/block_int.h"
  22. #include "block/nbd.h"
  23. #include "qemu/main-loop.h"
  24. #include "qemu/error-report.h"
  25. #include "qemu/config-file.h"
  26. #include "block/snapshot.h"
  27. #include "qapi/util.h"
  28. #include "qapi/qmp/qstring.h"
  29. #include "qom/object_interfaces.h"
  30. #include "io/channel-socket.h"
  31. #include <getopt.h>
  32. #include <libgen.h>
  33. #include <pthread.h>
  34. #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
  35. #define QEMU_NBD_OPT_CACHE 256
  36. #define QEMU_NBD_OPT_AIO 257
  37. #define QEMU_NBD_OPT_DISCARD 258
  38. #define QEMU_NBD_OPT_DETECT_ZEROES 259
  39. #define QEMU_NBD_OPT_OBJECT 260
  40. #define QEMU_NBD_OPT_TLSCREDS 261
  41. #define QEMU_NBD_OPT_IMAGE_OPTS 262
  42. static NBDExport *exp;
  43. static bool newproto;
  44. static int verbose;
  45. static char *srcpath;
  46. static SocketAddress *saddr;
  47. static int persistent = 0;
  48. static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
  49. static int shared = 1;
  50. static int nb_fds;
  51. static QIOChannelSocket *server_ioc;
  52. static int server_watch = -1;
  53. static QCryptoTLSCreds *tlscreds;
  54. static void usage(const char *name)
  55. {
  56. (printf) (
  57. "Usage: %s [OPTIONS] FILE\n"
  58. "QEMU Disk Network Block Device Server\n"
  59. "\n"
  60. " -h, --help display this help and exit\n"
  61. " -V, --version output version information and exit\n"
  62. "\n"
  63. "Connection properties:\n"
  64. " -p, --port=PORT port to listen on (default `%d')\n"
  65. " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
  66. " -k, --socket=PATH path to the unix socket\n"
  67. " (default '"SOCKET_PATH"')\n"
  68. " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
  69. " -t, --persistent don't exit on the last connection\n"
  70. " -v, --verbose display extra debugging information\n"
  71. "\n"
  72. "Exposing part of the image:\n"
  73. " -o, --offset=OFFSET offset into the image\n"
  74. " -P, --partition=NUM only expose partition NUM\n"
  75. "\n"
  76. "General purpose options:\n"
  77. " --object type,id=ID,... define an object such as 'secret' for providing\n"
  78. " passwords and/or encryption keys\n"
  79. #ifdef __linux__
  80. "Kernel NBD client support:\n"
  81. " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
  82. " -d, --disconnect disconnect the specified device\n"
  83. "\n"
  84. #endif
  85. "\n"
  86. "Block device options:\n"
  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"
  92. " -l, --load-snapshot=SNAPSHOT_PARAM\n"
  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"
  99. " --aio=MODE set AIO mode (native or threads)\n"
  100. " --discard=MODE set discard mode (ignore, unmap)\n"
  101. " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
  102. " --image-opts treat FILE as a full set of image options\n"
  103. "\n"
  104. "Report bugs to <qemu-devel@nongnu.org>\n"
  105. , name, NBD_DEFAULT_PORT, "DEVICE");
  106. }
  107. static void version(const char *name)
  108. {
  109. printf(
  110. "%s version 0.0.1\n"
  111. "Written by Anthony Liguori.\n"
  112. "\n"
  113. "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
  114. "This is free software; see the source for copying conditions. There is NO\n"
  115. "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
  116. , name);
  117. }
  118. struct partition_record
  119. {
  120. uint8_t bootable;
  121. uint8_t start_head;
  122. uint32_t start_cylinder;
  123. uint8_t start_sector;
  124. uint8_t system;
  125. uint8_t end_head;
  126. uint8_t end_cylinder;
  127. uint8_t end_sector;
  128. uint32_t start_sector_abs;
  129. uint32_t nb_sectors_abs;
  130. };
  131. static void read_partition(uint8_t *p, struct partition_record *r)
  132. {
  133. r->bootable = p[0];
  134. r->start_head = p[1];
  135. r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
  136. r->start_sector = p[2] & 0x3f;
  137. r->system = p[4];
  138. r->end_head = p[5];
  139. r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
  140. r->end_sector = p[6] & 0x3f;
  141. r->start_sector_abs = le32_to_cpup((uint32_t *)(p + 8));
  142. r->nb_sectors_abs = le32_to_cpup((uint32_t *)(p + 12));
  143. }
  144. static int find_partition(BlockBackend *blk, int partition,
  145. off_t *offset, off_t *size)
  146. {
  147. struct partition_record mbr[4];
  148. uint8_t data[512];
  149. int i;
  150. int ext_partnum = 4;
  151. int ret;
  152. if ((ret = blk_read(blk, 0, data, 1)) < 0) {
  153. error_report("error while reading: %s", strerror(-ret));
  154. exit(EXIT_FAILURE);
  155. }
  156. if (data[510] != 0x55 || data[511] != 0xaa) {
  157. return -EINVAL;
  158. }
  159. for (i = 0; i < 4; i++) {
  160. read_partition(&data[446 + 16 * i], &mbr[i]);
  161. if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
  162. continue;
  163. }
  164. if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
  165. struct partition_record ext[4];
  166. uint8_t data1[512];
  167. int j;
  168. if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
  169. error_report("error while reading: %s", strerror(-ret));
  170. exit(EXIT_FAILURE);
  171. }
  172. for (j = 0; j < 4; j++) {
  173. read_partition(&data1[446 + 16 * j], &ext[j]);
  174. if (!ext[j].system || !ext[j].nb_sectors_abs) {
  175. continue;
  176. }
  177. if ((ext_partnum + j + 1) == partition) {
  178. *offset = (uint64_t)ext[j].start_sector_abs << 9;
  179. *size = (uint64_t)ext[j].nb_sectors_abs << 9;
  180. return 0;
  181. }
  182. }
  183. ext_partnum += 4;
  184. } else if ((i + 1) == partition) {
  185. *offset = (uint64_t)mbr[i].start_sector_abs << 9;
  186. *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
  187. return 0;
  188. }
  189. }
  190. return -ENOENT;
  191. }
  192. static void termsig_handler(int signum)
  193. {
  194. state = TERMINATE;
  195. qemu_notify_event();
  196. }
  197. static void *show_parts(void *arg)
  198. {
  199. char *device = arg;
  200. int nbd;
  201. /* linux just needs an open() to trigger
  202. * the partition table update
  203. * but remember to load the module with max_part != 0 :
  204. * modprobe nbd max_part=63
  205. */
  206. nbd = open(device, O_RDWR);
  207. if (nbd >= 0) {
  208. close(nbd);
  209. }
  210. return NULL;
  211. }
  212. static void *nbd_client_thread(void *arg)
  213. {
  214. char *device = arg;
  215. off_t size;
  216. uint32_t nbdflags;
  217. QIOChannelSocket *sioc;
  218. int fd;
  219. int ret;
  220. pthread_t show_parts_thread;
  221. Error *local_error = NULL;
  222. sioc = qio_channel_socket_new();
  223. if (qio_channel_socket_connect_sync(sioc,
  224. saddr,
  225. &local_error) < 0) {
  226. error_report_err(local_error);
  227. goto out;
  228. }
  229. ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, &nbdflags,
  230. NULL, NULL, NULL,
  231. &size, &local_error);
  232. if (ret < 0) {
  233. if (local_error) {
  234. error_report_err(local_error);
  235. }
  236. goto out_socket;
  237. }
  238. fd = open(device, O_RDWR);
  239. if (fd < 0) {
  240. /* Linux-only, we can use %m in printf. */
  241. error_report("Failed to open %s: %m", device);
  242. goto out_socket;
  243. }
  244. ret = nbd_init(fd, sioc, nbdflags, size);
  245. if (ret < 0) {
  246. goto out_fd;
  247. }
  248. /* update partition table */
  249. pthread_create(&show_parts_thread, NULL, show_parts, device);
  250. if (verbose) {
  251. fprintf(stderr, "NBD device %s is now connected to %s\n",
  252. device, srcpath);
  253. } else {
  254. /* Close stderr so that the qemu-nbd process exits. */
  255. dup2(STDOUT_FILENO, STDERR_FILENO);
  256. }
  257. ret = nbd_client(fd);
  258. if (ret) {
  259. goto out_fd;
  260. }
  261. close(fd);
  262. object_unref(OBJECT(sioc));
  263. kill(getpid(), SIGTERM);
  264. return (void *) EXIT_SUCCESS;
  265. out_fd:
  266. close(fd);
  267. out_socket:
  268. object_unref(OBJECT(sioc));
  269. out:
  270. kill(getpid(), SIGTERM);
  271. return (void *) EXIT_FAILURE;
  272. }
  273. static int nbd_can_accept(void)
  274. {
  275. return nb_fds < shared;
  276. }
  277. static void nbd_export_closed(NBDExport *exp)
  278. {
  279. assert(state == TERMINATING);
  280. state = TERMINATED;
  281. }
  282. static void nbd_update_server_watch(void);
  283. static void nbd_client_closed(NBDClient *client)
  284. {
  285. nb_fds--;
  286. if (nb_fds == 0 && !persistent && state == RUNNING) {
  287. state = TERMINATE;
  288. }
  289. nbd_update_server_watch();
  290. nbd_client_put(client);
  291. }
  292. static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
  293. {
  294. QIOChannelSocket *cioc;
  295. cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
  296. NULL);
  297. if (!cioc) {
  298. return TRUE;
  299. }
  300. if (state >= TERMINATE) {
  301. object_unref(OBJECT(cioc));
  302. return TRUE;
  303. }
  304. nb_fds++;
  305. nbd_update_server_watch();
  306. nbd_client_new(newproto ? NULL : exp, cioc,
  307. tlscreds, NULL, nbd_client_closed);
  308. object_unref(OBJECT(cioc));
  309. return TRUE;
  310. }
  311. static void nbd_update_server_watch(void)
  312. {
  313. if (nbd_can_accept()) {
  314. if (server_watch == -1) {
  315. server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
  316. G_IO_IN,
  317. nbd_accept,
  318. NULL, NULL);
  319. }
  320. } else {
  321. if (server_watch != -1) {
  322. g_source_remove(server_watch);
  323. server_watch = -1;
  324. }
  325. }
  326. }
  327. static SocketAddress *nbd_build_socket_address(const char *sockpath,
  328. const char *bindto,
  329. const char *port)
  330. {
  331. SocketAddress *saddr;
  332. saddr = g_new0(SocketAddress, 1);
  333. if (sockpath) {
  334. saddr->type = SOCKET_ADDRESS_KIND_UNIX;
  335. saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
  336. saddr->u.q_unix->path = g_strdup(sockpath);
  337. } else {
  338. InetSocketAddress *inet;
  339. saddr->type = SOCKET_ADDRESS_KIND_INET;
  340. inet = saddr->u.inet = g_new0(InetSocketAddress, 1);
  341. inet->host = g_strdup(bindto);
  342. if (port) {
  343. inet->port = g_strdup(port);
  344. } else {
  345. inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
  346. }
  347. }
  348. return saddr;
  349. }
  350. static QemuOptsList file_opts = {
  351. .name = "file",
  352. .implied_opt_name = "file",
  353. .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
  354. .desc = {
  355. /* no elements => accept any params */
  356. { /* end of list */ }
  357. },
  358. };
  359. static QemuOptsList qemu_object_opts = {
  360. .name = "object",
  361. .implied_opt_name = "qom-type",
  362. .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
  363. .desc = {
  364. { }
  365. },
  366. };
  367. static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
  368. {
  369. Object *obj;
  370. QCryptoTLSCreds *creds;
  371. obj = object_resolve_path_component(
  372. object_get_objects_root(), id);
  373. if (!obj) {
  374. error_setg(errp, "No TLS credentials with id '%s'",
  375. id);
  376. return NULL;
  377. }
  378. creds = (QCryptoTLSCreds *)
  379. object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
  380. if (!creds) {
  381. error_setg(errp, "Object with id '%s' is not TLS credentials",
  382. id);
  383. return NULL;
  384. }
  385. if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
  386. error_setg(errp,
  387. "Expecting TLS credentials with a server endpoint");
  388. return NULL;
  389. }
  390. object_ref(obj);
  391. return creds;
  392. }
  393. int main(int argc, char **argv)
  394. {
  395. BlockBackend *blk;
  396. BlockDriverState *bs;
  397. off_t dev_offset = 0;
  398. uint32_t nbdflags = 0;
  399. bool disconnect = false;
  400. const char *bindto = "0.0.0.0";
  401. const char *port = NULL;
  402. char *sockpath = NULL;
  403. char *device = NULL;
  404. off_t fd_size;
  405. QemuOpts *sn_opts = NULL;
  406. const char *sn_id_or_name = NULL;
  407. const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:";
  408. struct option lopt[] = {
  409. { "help", no_argument, NULL, 'h' },
  410. { "version", no_argument, NULL, 'V' },
  411. { "bind", required_argument, NULL, 'b' },
  412. { "port", required_argument, NULL, 'p' },
  413. { "socket", required_argument, NULL, 'k' },
  414. { "offset", required_argument, NULL, 'o' },
  415. { "read-only", no_argument, NULL, 'r' },
  416. { "partition", required_argument, NULL, 'P' },
  417. { "connect", required_argument, NULL, 'c' },
  418. { "disconnect", no_argument, NULL, 'd' },
  419. { "snapshot", no_argument, NULL, 's' },
  420. { "load-snapshot", required_argument, NULL, 'l' },
  421. { "nocache", no_argument, NULL, 'n' },
  422. { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
  423. { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
  424. { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
  425. { "detect-zeroes", required_argument, NULL,
  426. QEMU_NBD_OPT_DETECT_ZEROES },
  427. { "shared", required_argument, NULL, 'e' },
  428. { "format", required_argument, NULL, 'f' },
  429. { "persistent", no_argument, NULL, 't' },
  430. { "verbose", no_argument, NULL, 'v' },
  431. { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
  432. { "export-name", required_argument, NULL, 'x' },
  433. { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
  434. { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
  435. { NULL, 0, NULL, 0 }
  436. };
  437. int ch;
  438. int opt_ind = 0;
  439. char *end;
  440. int flags = BDRV_O_RDWR;
  441. int partition = -1;
  442. int ret = 0;
  443. bool seen_cache = false;
  444. bool seen_discard = false;
  445. bool seen_aio = false;
  446. pthread_t client_thread;
  447. const char *fmt = NULL;
  448. Error *local_err = NULL;
  449. BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
  450. QDict *options = NULL;
  451. const char *export_name = NULL;
  452. const char *tlscredsid = NULL;
  453. bool imageOpts = false;
  454. /* The client thread uses SIGTERM to interrupt the server. A signal
  455. * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
  456. */
  457. struct sigaction sa_sigterm;
  458. memset(&sa_sigterm, 0, sizeof(sa_sigterm));
  459. sa_sigterm.sa_handler = termsig_handler;
  460. sigaction(SIGTERM, &sa_sigterm, NULL);
  461. module_call_init(MODULE_INIT_QOM);
  462. qemu_add_opts(&qemu_object_opts);
  463. qemu_init_exec_dir(argv[0]);
  464. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  465. switch (ch) {
  466. case 's':
  467. flags |= BDRV_O_SNAPSHOT;
  468. break;
  469. case 'n':
  470. optarg = (char *) "none";
  471. /* fallthrough */
  472. case QEMU_NBD_OPT_CACHE:
  473. if (seen_cache) {
  474. error_report("-n and --cache can only be specified once");
  475. exit(EXIT_FAILURE);
  476. }
  477. seen_cache = true;
  478. if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
  479. error_report("Invalid cache mode `%s'", optarg);
  480. exit(EXIT_FAILURE);
  481. }
  482. break;
  483. case QEMU_NBD_OPT_AIO:
  484. if (seen_aio) {
  485. error_report("--aio can only be specified once");
  486. exit(EXIT_FAILURE);
  487. }
  488. seen_aio = true;
  489. if (!strcmp(optarg, "native")) {
  490. flags |= BDRV_O_NATIVE_AIO;
  491. } else if (!strcmp(optarg, "threads")) {
  492. /* this is the default */
  493. } else {
  494. error_report("invalid aio mode `%s'", optarg);
  495. exit(EXIT_FAILURE);
  496. }
  497. break;
  498. case QEMU_NBD_OPT_DISCARD:
  499. if (seen_discard) {
  500. error_report("--discard can only be specified once");
  501. exit(EXIT_FAILURE);
  502. }
  503. seen_discard = true;
  504. if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
  505. error_report("Invalid discard mode `%s'", optarg);
  506. exit(EXIT_FAILURE);
  507. }
  508. break;
  509. case QEMU_NBD_OPT_DETECT_ZEROES:
  510. detect_zeroes =
  511. qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
  512. optarg,
  513. BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
  514. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
  515. &local_err);
  516. if (local_err) {
  517. error_reportf_err(local_err,
  518. "Failed to parse detect_zeroes mode: ");
  519. exit(EXIT_FAILURE);
  520. }
  521. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  522. !(flags & BDRV_O_UNMAP)) {
  523. error_report("setting detect-zeroes to unmap is not allowed "
  524. "without setting discard operation to unmap");
  525. exit(EXIT_FAILURE);
  526. }
  527. break;
  528. case 'b':
  529. bindto = optarg;
  530. break;
  531. case 'p':
  532. port = optarg;
  533. break;
  534. case 'o':
  535. dev_offset = strtoll (optarg, &end, 0);
  536. if (*end) {
  537. error_report("Invalid offset `%s'", optarg);
  538. exit(EXIT_FAILURE);
  539. }
  540. if (dev_offset < 0) {
  541. error_report("Offset must be positive `%s'", optarg);
  542. exit(EXIT_FAILURE);
  543. }
  544. break;
  545. case 'l':
  546. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  547. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  548. optarg, false);
  549. if (!sn_opts) {
  550. error_report("Failed in parsing snapshot param `%s'",
  551. optarg);
  552. exit(EXIT_FAILURE);
  553. }
  554. } else {
  555. sn_id_or_name = optarg;
  556. }
  557. /* fall through */
  558. case 'r':
  559. nbdflags |= NBD_FLAG_READ_ONLY;
  560. flags &= ~BDRV_O_RDWR;
  561. break;
  562. case 'P':
  563. partition = strtol(optarg, &end, 0);
  564. if (*end) {
  565. error_report("Invalid partition `%s'", optarg);
  566. exit(EXIT_FAILURE);
  567. }
  568. if (partition < 1 || partition > 8) {
  569. error_report("Invalid partition %d", partition);
  570. exit(EXIT_FAILURE);
  571. }
  572. break;
  573. case 'k':
  574. sockpath = optarg;
  575. if (sockpath[0] != '/') {
  576. error_report("socket path must be absolute");
  577. exit(EXIT_FAILURE);
  578. }
  579. break;
  580. case 'd':
  581. disconnect = true;
  582. break;
  583. case 'c':
  584. device = optarg;
  585. break;
  586. case 'e':
  587. shared = strtol(optarg, &end, 0);
  588. if (*end) {
  589. error_report("Invalid shared device number '%s'", optarg);
  590. exit(EXIT_FAILURE);
  591. }
  592. if (shared < 1) {
  593. error_report("Shared device number must be greater than 0");
  594. exit(EXIT_FAILURE);
  595. }
  596. break;
  597. case 'f':
  598. fmt = optarg;
  599. break;
  600. case 't':
  601. persistent = 1;
  602. break;
  603. case 'x':
  604. export_name = optarg;
  605. break;
  606. case 'v':
  607. verbose = 1;
  608. break;
  609. case 'V':
  610. version(argv[0]);
  611. exit(0);
  612. break;
  613. case 'h':
  614. usage(argv[0]);
  615. exit(0);
  616. break;
  617. case '?':
  618. error_report("Try `%s --help' for more information.", argv[0]);
  619. exit(EXIT_FAILURE);
  620. case QEMU_NBD_OPT_OBJECT: {
  621. QemuOpts *opts;
  622. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  623. optarg, true);
  624. if (!opts) {
  625. exit(EXIT_FAILURE);
  626. }
  627. } break;
  628. case QEMU_NBD_OPT_TLSCREDS:
  629. tlscredsid = optarg;
  630. break;
  631. case QEMU_NBD_OPT_IMAGE_OPTS:
  632. imageOpts = true;
  633. break;
  634. }
  635. }
  636. if ((argc - optind) != 1) {
  637. error_report("Invalid number of arguments");
  638. error_printf("Try `%s --help' for more information.\n", argv[0]);
  639. exit(EXIT_FAILURE);
  640. }
  641. if (qemu_opts_foreach(&qemu_object_opts,
  642. user_creatable_add_opts_foreach,
  643. NULL, &local_err)) {
  644. error_report_err(local_err);
  645. exit(EXIT_FAILURE);
  646. }
  647. if (tlscredsid) {
  648. if (sockpath) {
  649. error_report("TLS is only supported with IPv4/IPv6");
  650. exit(EXIT_FAILURE);
  651. }
  652. if (device) {
  653. error_report("TLS is not supported with a host device");
  654. exit(EXIT_FAILURE);
  655. }
  656. if (!export_name) {
  657. /* Set the default NBD protocol export name, since
  658. * we *must* use new style protocol for TLS */
  659. export_name = "";
  660. }
  661. tlscreds = nbd_get_tls_creds(tlscredsid, &local_err);
  662. if (local_err) {
  663. error_report("Failed to get TLS creds %s",
  664. error_get_pretty(local_err));
  665. exit(EXIT_FAILURE);
  666. }
  667. }
  668. if (disconnect) {
  669. int nbdfd = open(argv[optind], O_RDWR);
  670. if (nbdfd < 0) {
  671. error_report("Cannot open %s: %s", argv[optind],
  672. strerror(errno));
  673. exit(EXIT_FAILURE);
  674. }
  675. nbd_disconnect(nbdfd);
  676. close(nbdfd);
  677. printf("%s disconnected\n", argv[optind]);
  678. return 0;
  679. }
  680. if (device && !verbose) {
  681. int stderr_fd[2];
  682. pid_t pid;
  683. int ret;
  684. if (qemu_pipe(stderr_fd) < 0) {
  685. error_report("Error setting up communication pipe: %s",
  686. strerror(errno));
  687. exit(EXIT_FAILURE);
  688. }
  689. /* Now daemonize, but keep a communication channel open to
  690. * print errors and exit with the proper status code.
  691. */
  692. pid = fork();
  693. if (pid < 0) {
  694. error_report("Failed to fork: %s", strerror(errno));
  695. exit(EXIT_FAILURE);
  696. } else if (pid == 0) {
  697. close(stderr_fd[0]);
  698. ret = qemu_daemon(1, 0);
  699. /* Temporarily redirect stderr to the parent's pipe... */
  700. dup2(stderr_fd[1], STDERR_FILENO);
  701. if (ret < 0) {
  702. error_report("Failed to daemonize: %s", strerror(errno));
  703. exit(EXIT_FAILURE);
  704. }
  705. /* ... close the descriptor we inherited and go on. */
  706. close(stderr_fd[1]);
  707. } else {
  708. bool errors = false;
  709. char *buf;
  710. /* In the parent. Print error messages from the child until
  711. * it closes the pipe.
  712. */
  713. close(stderr_fd[1]);
  714. buf = g_malloc(1024);
  715. while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
  716. errors = true;
  717. ret = qemu_write_full(STDERR_FILENO, buf, ret);
  718. if (ret < 0) {
  719. exit(EXIT_FAILURE);
  720. }
  721. }
  722. if (ret < 0) {
  723. error_report("Cannot read from daemon: %s",
  724. strerror(errno));
  725. exit(EXIT_FAILURE);
  726. }
  727. /* Usually the daemon should not print any message.
  728. * Exit with zero status in that case.
  729. */
  730. exit(errors);
  731. }
  732. }
  733. if (device != NULL && sockpath == NULL) {
  734. sockpath = g_malloc(128);
  735. snprintf(sockpath, 128, SOCKET_PATH, basename(device));
  736. }
  737. saddr = nbd_build_socket_address(sockpath, bindto, port);
  738. if (qemu_init_main_loop(&local_err)) {
  739. error_report_err(local_err);
  740. exit(EXIT_FAILURE);
  741. }
  742. bdrv_init();
  743. atexit(bdrv_close_all);
  744. srcpath = argv[optind];
  745. if (imageOpts) {
  746. QemuOpts *opts;
  747. if (fmt) {
  748. error_report("--image-opts and -f are mutually exclusive");
  749. exit(EXIT_FAILURE);
  750. }
  751. opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
  752. if (!opts) {
  753. qemu_opts_reset(&file_opts);
  754. exit(EXIT_FAILURE);
  755. }
  756. options = qemu_opts_to_qdict(opts, NULL);
  757. qemu_opts_reset(&file_opts);
  758. blk = blk_new_open(NULL, NULL, options, flags, &local_err);
  759. } else {
  760. if (fmt) {
  761. options = qdict_new();
  762. qdict_put(options, "driver", qstring_from_str(fmt));
  763. }
  764. blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
  765. }
  766. if (!blk) {
  767. error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
  768. argv[optind]);
  769. exit(EXIT_FAILURE);
  770. }
  771. bs = blk_bs(blk);
  772. if (sn_opts) {
  773. ret = bdrv_snapshot_load_tmp(bs,
  774. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  775. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  776. &local_err);
  777. } else if (sn_id_or_name) {
  778. ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
  779. &local_err);
  780. }
  781. if (ret < 0) {
  782. error_reportf_err(local_err, "Failed to load snapshot: ");
  783. exit(EXIT_FAILURE);
  784. }
  785. bs->detect_zeroes = detect_zeroes;
  786. fd_size = blk_getlength(blk);
  787. if (fd_size < 0) {
  788. error_report("Failed to determine the image length: %s",
  789. strerror(-fd_size));
  790. exit(EXIT_FAILURE);
  791. }
  792. if (partition != -1) {
  793. ret = find_partition(blk, partition, &dev_offset, &fd_size);
  794. if (ret < 0) {
  795. error_report("Could not find partition %d: %s", partition,
  796. strerror(-ret));
  797. exit(EXIT_FAILURE);
  798. }
  799. }
  800. exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
  801. &local_err);
  802. if (!exp) {
  803. error_report_err(local_err);
  804. exit(EXIT_FAILURE);
  805. }
  806. if (export_name) {
  807. nbd_export_set_name(exp, export_name);
  808. newproto = true;
  809. }
  810. server_ioc = qio_channel_socket_new();
  811. if (qio_channel_socket_listen_sync(server_ioc, saddr, &local_err) < 0) {
  812. object_unref(OBJECT(server_ioc));
  813. error_report_err(local_err);
  814. return 1;
  815. }
  816. if (device) {
  817. int ret;
  818. ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
  819. if (ret != 0) {
  820. error_report("Failed to create client thread: %s", strerror(ret));
  821. exit(EXIT_FAILURE);
  822. }
  823. } else {
  824. /* Shut up GCC warnings. */
  825. memset(&client_thread, 0, sizeof(client_thread));
  826. }
  827. nbd_update_server_watch();
  828. /* now when the initialization is (almost) complete, chdir("/")
  829. * to free any busy filesystems */
  830. if (chdir("/") < 0) {
  831. error_report("Could not chdir to root directory: %s",
  832. strerror(errno));
  833. exit(EXIT_FAILURE);
  834. }
  835. state = RUNNING;
  836. do {
  837. main_loop_wait(false);
  838. if (state == TERMINATE) {
  839. state = TERMINATING;
  840. nbd_export_close(exp);
  841. nbd_export_put(exp);
  842. exp = NULL;
  843. }
  844. } while (state != TERMINATED);
  845. blk_unref(blk);
  846. if (sockpath) {
  847. unlink(sockpath);
  848. }
  849. qemu_opts_del(sn_opts);
  850. if (device) {
  851. void *ret;
  852. pthread_join(client_thread, &ret);
  853. exit(ret != NULL);
  854. } else {
  855. exit(EXIT_SUCCESS);
  856. }
  857. }