qemu-nbd.c 33 KB

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