qemu-nbd.c 33 KB

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